text:
Q: Can a function have equal maximum and minimum value? When I heard that the maximum value can be smaller than the minimum  value,  it striked me whether they can both be equal. I want to enquire whether it is true.

A: (A) $\bf 1$ Variable function :
It is possible that (minima $\leq$ maxima) OR (minima $>$ maxima), though these will be a different points on the curve.
Pictorially, we can see that here :

In the above graph as you can see, we have a minima at point $A$ and for each of the $3$ different purple curves, we have a point $B$ where $\bf \text{Maxima}>\text{or}=\text{or}<\text{Minima}$ (from top to bottom respectively).
(B) $\bf 2$ Variable functions :
In this case, in addition to earlier cases, it is possible that the same point is both a Minima & a Maxima!
Consider the following function:
$$\bf z=x^2-y^2$$
At $(x,y)=(0,0)$ , we have $z=0$ which is a minima when considering Variable $\bf x$ & a maxima when considering variable $\bf y$.
Such Points are known as "Saddle Points" or "MiniMax Points" (more details here) & are very common.

A: If there are several local maxima   and local minima then one local max being less than one local min is ordinary.
However, in case $f(x)$ has single  local max and single local min, then the situation of  $f_{max}\le f_{min}$ is more interesting as it implies that there is a discontinuity in the function in $(x_{max}, x_{min})$. For example:
$f(x)=\frac{(x-2)^2}{x-3}$, $f_{max}=f(2)=0$ and $f_{min}=f(4)=4$
see below

EDIT An example for $f_{max}=f_{min}$
$$f(x\le 0)=1-(x+2)^2, f(x>0)=1+(x+2)^2$$ as below

A: If you're talking about local maxima and minima, then it's definitely possible. As a simple example, check out $y = x (x-1)^2 (x+1)^2$:

This has a local minimum at $(1, 0)$ and a local maximum at $(-1, 0)$, in addition to its two other extrema.


text:
Q: Are resources used by a Java application freed when it terminates? Java applications may use IO streams, sockets or database connections that should be closed when they are no longer needed.
However, applications may be terminated (e.g. by killing the process). Will all used resources be freed in this case? Who will free them: OS or JRE?

A: The JVM will release all active resources upon termination; however, this does not ensure that the other end will free the resource too, so explicitly closing resources is in every programmer's best interest.
An alternative to explicitly closing streams exists in Java 7, called the try-resource "statement", which is the equivalent of closing a resource in a finally block after a try block.  More info on that can be found here.

A: If your software doesn't take care of resource management properly, the following will happen:

*

*at runtime: the JVM will attempt during the duration of your program to close open streams if they're are seemingly unused (during garbage collection cycles),

*at your program's termination point: the JVM should close open streams of all kinds left open by your program,

*at the JVM's process termination point: the operating system will take care of releasing anything that hasn't been properly released by the JVM when it exists (hopefully, or this OS has some serious issues...).

As mentioned by Vulcan, none of this ensures that they are properly dealt with on the other end, obviously.
Note that the 3rd bullet point is a rather generic thing: most operating systems will take care of this, and it doesn't relate to the Java Platform's internals. It's about the OS managing its processes and resources on its own.
More Info
See also:

*

*Cleanup of resources on an abnormal Exit, also on StackOverflow

*How do I implement graceful termination in Java

*Java Theory and Practice: Good Housekeeping Practices, at the IBM Developer Series

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serving contextual based ads on sites built entirely in Flash? What's the status of adsense (or equivalent) being able to serve contextual based ads on sites built entirely in Flash?

A: Check out Mochiads. Adsense ish type of service for embedding into Flash applications.
(they're behind mochiweb, the erlang web server, which is way cool)


text:
Q: Component not rendering updated controller variable on onchange event I'm very new to Visualforce and Apex development. I've been trying to create a solution on AppExchange with these two, but there is an issue I am facing. Here it goes:
<apex:inputText id="form-heading"  value="{!formHeading}" styleClass="icon-input" html-placeholder="Enter Heading Text">
    <apex:actionSupport event="onchange" action="{!setvar}" reRender="outText,outHeading">
    </apex:actionSupport>
</apex:inputText>

This is from a component called c:Sidebar hosted on a page called create.
So the value of form heading is being updated based on the onchange event of the input.
This is my other controller on the same page called c:FormComponent:
<apex:outputPanel id="outText">
    <script>
        x += 1;
        alert('The value of x is now: ' + x + ' {!formHeading}');
    </script>
    <apex:outputText styleClass="form-heading" style="font-size:30px;color:#3582FF;" value="{!formHeading}"/>
</apex:outputPanel>

The component is getting rerendered after the onchange variable, but the value still remains the same and is driving me insane. I've added a counter to confirm that the outputText is getting rendered, and it is.
This is my controller:
public class HomeController {

    public String formHeading {get;set;}

    public HomeController(){
        formHeading = 'This is the form heading';
    }

    public void setvar(){
        // system.debug('var#####'+acct.Name);
    }
}

I am not able to understand, what the approach is here. They all share a common controller; so after every render, the value should be updated, isn't it?!
Please help me out.
Cheers, Aadhit


text:
Q: php variable in javascript I have the following code in php:
$test = 'abc';
echo '<script type="text/javascript">\n';
    echo 'movtitle = ' . $test . ';\n';
    echo '</script>';

and I tried to do an alert(movtitle), but it doesn't print out anything. What am I doing wrong?

A: I'd do it this way:
<?php
$test = 'abc';
?>

<script type="text/javascript">
    alert('<?php echo $test; ?>');
</script>

A: You are missing the quotes around the value of movtitle:
 echo "movtitle = '" . $test . "';\n";

A: You are solving this problem wrong way, upside down.
There are no PHP variables in javascript at all. There is only some string you have to output in PHP.
So, the right way would be:

*

*Get to know, what javascript code you want to have. Ask here or google for it and then edit it to make it fit your needs (add 'abc' to alert in this case)
test, if it works.

*Write PHP code that builds the same JS you wrote manually.
3. See what you get. Most important part. Do not watch PHP code. Always watch resulting JS code. Find the differences and then correct PHP code to eliminate them. It's no more than just simple string operations.
Edit: it seems you failed at opt. 1. Do you have pure JS code working? It seems there is some problem with your browser, not PHP

A: you migh try this:
echo 'movtitle = "' . $test . '";\n';
which will create javascript that looks like this
movtitle = "Cassablanca";
Note also that the \n will not work inside the single quotes.

A: An it would be even a good idea to JSON encode the variable:
$test = 'abc';
print("<script type=\"text/javascript\">\n");
printf("movtitle = JSON.parse('%s');\n", json_encode($test));
print("</script>");

With this solution you can pass multiple object types to javascript.

A: There are a couple issues at play here:
First, you're using single quotes for your echo statements, so your escape characters aren't working. The /n characters are being echoed literally, so your output looks like this:
<script type="text/javascript">\nmovtitle = abc;\n</script>

You need double quotes for the escaping to work, so you can either swap quotes (i.e. double on the outside, single on the inside) or just escape the double quotes themselves:
Option 1:
echo "<script type='text/javascript'>\n";
    echo "movtitle = '" . $test . "';\n";
    echo "</script>";

Option 2:
echo "<script type=\"text/javascript\">\n";
    echo "movtitle = \"" . $test . "\";\n";
    echo "</script>";

Your second problem is that you're not surrounding the "abc" value with quotes. The output, as shown above, results in the following JavaScript line:
movtitle = abc;

This is saying "assign the value of the variable "abc" to the variable "movtitle". Since there is no variable "abc" in the code, the line fails. The line needs to be output like this:
movtitle = "abc";

Note that my example code above fixes this issue for you.

An even better option would be to not echo this with PHP at all. Instead, drop out of PHP and write your raw HTML directly. You can hop into PHP quickly just to drop in the variable:
<?php
  // normal processing
  $test = 'abc';
?>

<script type="text/javascript">
  movtitle = " <?php echo $test; ?>";
</script>";

<?php
 // resume processing
?>

In general, it's better to keep your PHP processing work and your HTML output as separate as possible. Do all your work upfront in PHP, then include a template file with the same sort of "fill-in-the-blanks" PHP variable use as I show in my last example.


text:
Q: Can`t get results from my database (class PDF extends) class PDF extends
Can`t get results from my database into my class PDF extends.
I have done several tests but unfortunately without success.
How can I get the results from: $users[post_id]?
// Logo
$this->Image('logo.png',10,6,30);
// Arial bold 15
$this->SetFont('Arial','B',15);
// Move to the right
$this->Cell(80);
// Title
$this->Cell(30,10,'{$users[post_id]}',1,0,'C');
// Line break
$this->Ln(20);


text:
Q: How to create a Debian docker container that can run docker containers? I need a Debian container that can run containers itself (and has access to systemd). Following this post, I have tried to run
docker run -v /var/run/docker.sock:/var/run/docker.sock --name debian-buster-slim -h 10-slim -e LANG=C.UTF-8 -it debian:10-slim /bin/bash -l

but the container cannot run docker containers. What am I doing wrong?


text:
Q: Detect Touches on Edges of Apple TV Remote When using the Apple TV remote to interact with a tvOS application, the location of the initial touch event is always the same (e.g., x: 960.0, y: 540.0) because there is no relation to the view the user is interacting with.
Apple's video player shows the option to skip forward/backward 10 seconds if the user touches the edges of the Apple TV remote. How does Apple detect the user touches the edge of the Apple TV remote? This is possible if the user is swiping the touch area of the Apple TV remote, but Apple's video player also does this when the user puts their finger on the edge of the touch area of the Apple TV remote.

A: Here's a solution: https://dcordero.me/posts/directional_clicks_on_tvos.html
He uses the GameController API to treat the touchpad like a d-pad.


text:
Q: Highlight specific words in a sentence with diacritrics I am searching for some improvements, particularly in the regex, in the way I highlight specific words in a string. Here is the situation :

*

*I have keywords into my database stored without any diacritrics,

*The user comes with a string with diatrics,

*I find the matches between the keywords and my string modified so that it does not contain any diacritrics,

*I hightlight the matched words in the original sentence with diacritrics.

var sentence = "J'eusse été amélioré sans des aigÜs si hauts améliorés et raisonnable. Amélioration réaméliorée";
var word = ['eusse','ameliore','aigu','aimerais']; //Matched keywords extracted from database where there are stored without diacritrics

var new_s = sentence, match, output, nb = 0, index = [];
var new_s_cache = removeDiacritics(sentence).replace("'"," ");

for (var i=0;i<word.length;i++){// For each matched word it stores its position and length in the array called index
          var wordInput = word[i].substr(0,4);
          var re = new RegExp("(?:^|\\W)"+wordInput+"(\\w*)(?!\\w)","gi");
          while (match = re.exec(new_s_cache)) {
            index.push([match.index,match[0].length]);
          }
        }
index.sort(); // Sort index so that it highlights word in the right order
        for (var j=0;j<index.length;j++) { //It hightlights the word in the orginal sentence with diatrics
new_s = new_s.substr(0,index[j][0]+1+nb) + "" + new_s.substr(index[j][0]+1+nb,index[j][1]) + "" + new_s.substr(index[j][0]+index[j][1]+1+nb);
            nb = nb + 7; // take into account the "" length
        }

output = new_s ;

Where am I searching improvements ?

*

*The regex : I want to catch the similar words to keywords. That's why I took arbitrary the 4 first letters and then run a regex to find the words that contains this 4 letters but it's not optimal. Indeed for instance I'd like to find 'unapproved' when the keyword is 'approve'.

*The idea of the code : the juggle between the original sentence and the one without diacritrics appears to be quite fragile.

Here is the JSfiddle : https://jsfiddle.net/qqabomsg/3/
Thanks in advance!


text:
Q: Exact formulation of Paley-Zygmund inequality The Paley-Zygmund inequality states that $P(X \succ c\mathbb{E}[x]) \succ (1-c)^2 \frac{\mathbb{E}[X]^2}{\mathbb{E}[X^2]}$ for $X\succ 0$ and $0\prec c \prec 1$.
I've used $\succ$ here because I have seen this formula with pretty much any combination of $>$ and $\geq$ plugged in for the various instances of $\succ$.I guess for continuous random variables this sloppiness doesn't matter much in practice, but what is the exact formula here?

A: Inside the probability function, if we allow equality, we increase the probability. Hence, the inequality is stronger if we do not allow equality there. Outside of the probability, the statement is strengthened if we allow equality. For the condition on $X$, we increase the strength of the statement if we allow equality. The same holds for $c$ (i.e., $0$ and $1$ should be allowed). So, we get the strongest statement if we state that for any $X\ge 0$ and $0\le c \le 1$,
$P(X > c \mathbb{E}[X]) \ge (1-c)^2 \frac{\mathbb{E}[X]^2}{\mathbb{E}[X^2]}$. And so one should use this form.
Having said this, the statement also requires $\mathbb{E}[X^2]>0$, or in the lower bound we get $0/0$, which has no meaning. Also, $c=1$ gives a vacuous statement, so it is not crucial to allow $c=1$ in the statement.


text:
Q: Finding the big O complexity for the following code int sum = 0;
for(int i=1;i<n;i++)
    for(int j=1;j<i*i;j++)
for(int k=1;k<j;k++)
    if (j % i==1)
        sum++;

The first statement is constant.
The first for loop takes n times.
The second for loop takes n^2 times.
The third for loop takes n times.
The if statement takes constant time.
The final statement takes constant time.
Thus final complexity is n x n^2 x n x n = O(n^4)
Is my understanding and final answer correct?

A: The time complexity of the third loop is O(n^2) since it is k<j and j will equal i*i (n*n). But the complexity of the example would be O(n^3) as you only multiply the time complexity if they are nested. Otherwise, for things occurring in sequence, their time complexity should be added O(1 + n^3 + n^2), which is simplified to the term of the highest order O(n^3) as with very large numbers this will be the only term that matters.
See this post for a more detailed answer, there are more resources there too.
int sum = 0;                  O(1)

for(int i=1;i<n;i++)          O(n)
    for(int j=1;j<i*i;j++)    O(n^2)
                            = O(n^3)

for(int k=1;k<j;k++)          O(n^2)
    if (j % i==1)             O(1)
        sum++;                O(1)
                            = O(n^2)

= O(1 + n^3 + n^2)
= O(n^3)


text:
Q: Update multiple records with the same value from another table I'm trying to update the field ID_T1 in the table T2 with the ID field of T1, but the only thing that joins them is the DESC field in both tables, which is a problem, since all updates I've tried returns "single-row subquery returns more than one row" because in T1 there is more than one record with the same DESC
T1
|DESC | ID |
|A    |  1 |
|B    |  2 |
|C    |  3 |

T2
|DESC | ID | ID_T1 |
|A    |  1 |       |
|B    |  2 |       |
|C    |  3 |       |
|A    |  4 |       |
|B    |  5 |       |
|C    |  6 |       |

Expected result should be:
T2
|DESC | ID | ID_T1  |
|A    |  1 |    1   |
|B    |  2 |    2   |
|C    |  3 |    3   |
|A    |  4 |    1   |
|B    |  5 |    2   |
|C    |  6 |    3   |

A: You got it the the wrong way around ;)
UPDATE T2 d
    SET (d.id_t1) = (SELECT c.id FROM T1 c WHERE d.desc= c.desc);


text:
Q: How Moles Isolation framework is implemented? Moles is an isolation framework created by Microsoft.  A cool feature of Moles is that it can "mock" static/non-virtual methods and sealed classes (which is not possible with frameworks like Moq).  Below is the quick demonstration of what Moles can do:
Assert.AreNotEqual(new DateTime(2012, 1, 1), DateTime.Now);

// MDateTime is part of Moles; the below will "override" DateTime.Now's behavior
MDateTime.NowGet = () => new DateTime(2012, 1, 1);
Assert.AreEqual(new DateTime(2012, 1, 1), DateTime.Now);

Seems like Moles is able to modify the CIL body of things like DateTime.Now at runtime.  Since Moles isn't open-source, I'm curious to know which mechanism Moles uses in order to modify methods' CIL at runtime.  Can anyone shed any light?

A: Moles implements a CLR profiler (in particular the ICorProfilerCallback interface) that allows to rewrite MSIL method bodies before they are compiled into assembly code by the .NET runtime. This is done in particular through the JitCompileStarted callback.
In each method, Moles introduces a detour that looks like this:
static struct DateTime
{
    static DateTime Now
    {
        get
        {
            Func<DateTime> d = __Detours.GetDelegate(
                null, // this point null in static methods
                methodof(here) // current method token
                );
            if(d != null)
                return d();
            ... // original body
        }
    }
}

When you set a mole, your delegate is stored in the underlying __Detours dictionary which gets looked up whenver the method is executed.

A: This is working like as wrapper to any assembly you want, for example mscorlib (this example baseing on Moles Assembly Wrapper of mscorlib). This giving to you power to replace any .NET method by the delegate written by coder.
This is not working automagicaly. You must first create before this start works, Moles XML configuration file with list of Assemblies to "Wrapper" and by this code Moles generate a References of this assembiles from config file. And you must in this file add using namespace System.Moles, and before function [HostType("Moles")]


text:
Q: How to get LINQPad to Dump() System.__ComObject references? I am playing around with using LINQPad to rapidly develop small ArcObjects (a COM-based library for ESRI's ArcGIS software) applications and have had some success in using it to Dump() the properties of COM objects that I initialize from .NET, but any COM objects that are obtained from an existing COM object are simply dumped as System.__ComObject references, which is not particularly useful:

This help topic explains why this is happening, which I think I understand, but would like to know what options there are for working around this behavior, especially in the context of making LINQPad (even) more powerful.
Interestingly, Visual Studio's debugger is able to display the properties of these objects, and even values for value types:

What mechanism does Visual Studio use to achieve this introspection, and why doesn't LINQPad's Dump method do the same? Edit: See related question about how VS does this: How does Visual Studio's debugger/interactive window dump the properties of COM Objects in .NET?
The ArcObjects .NET SDK includes PIAs with RCWs for each CoClass a COM interface may be implemented by, so I'm thinking it should be possible to wrap these objects programmatically.
As a workaround I have successfully used Marshal.CreateWrapperOfType() within my LINQ queries to coerce LINQPad to dump the properties of the object when I happen to know which CoClass should be used. Of course, this only properly dumps value type properties -- any COM-based reference type properties are still reported as System.__ComObject, so a proper solution would have to work recursively to get those wrapped as well.
In a previous question I learned that the CoClass can be determined at runtime if it implements IPersist, which a good portion of ArcObjects do. Can I somehow use this technique, or another one, to automatically coerce a System.__ComObject to the appropriate RCW from the PIAs? And if so, how can I implement this in LINQPad, e.g. by providing an ICustomMemberProvider implementation? Can this be made to be recursive, so that properties that are also COM objects be wrapped as well?
I am using LINQPad 4.x which targets .NET 4.0, but am also interested in supporting LINQPad 2.x (so solutions that work on both .NET 3.5 and .NET 4.0 would be preferred, but that's not a requirement).
Update: I've figured out the first part of my question which was how to wrap a System.__ComObject in its RCW using the CLSID returned by IPersist.GetClassID. See this related question and this answer for the code I'm using.
I would still like to know how I can work this into LINQPad's Dump method.

A: I've been having some of the same issues (except I'm working with iTunes COM library).
In visual studio you don't realize it but each debug window is asking the COM library to create the type when you open it.  This is different than Dump() which is, well, not interactive.
The only solution I've found is if I know what type the list is to do a OfType<>() cast to that type.  This will iterate over the list and force COM to create the elements.
So in your example above you would say:
var layers = map.EnumerateLayers("etc")
      .Select(s => s.OfType<Layer>())
      .Dump();

NB - Your millage may vary, it turns out for the OP example this was needed.
var layers = map.EnumerateLayers()
      .OfType<IGeoFeatureLayer>()
      .Dump();

Depending on the COM you might have to take this to the next step and pull out the members from there (with com you have to ask to get the value) something like this:
var layers = map.EnumerateLayers("etc")
      .Select(x => x.OfType<Layer>())
      .Select(x => new { x.Depth, x.Dimention, }) // etc
      .Dump();

Sure would be nice if there was a "magical" way to make this happen, but I don't believe there is because of the nature of COM.


text:
Q: Even when I have no quotes to escape, it still says I have an unclosed string (Jquery) I've used the find function to be completely sure that there are no quotes that need to be escaped. The html to be put into my "viewbox" div is entirely single quotes, and I'm surrounding it with double quotes. Not a single exception. When I remove what I'm trying to insert, and replace it with a simple 'test', it works fine, so it doesn't seem to be a library issue, or anything like that. Also, the code itself that I'm trying to insert works when I save it as an html file. I'm almost certain I'm overlooking something. I've tried, searched, and done everything I can think of. Here's the javascript code.
EDIT: I put all the lines of code onto one line. It's valid, but instead of rendering a bootstrap carousel, it just displayed all the images at once, one after another.
$(document).ready(function () {
$('#aprilissue').click(function () {
$('#viewbox').html(
    "

"
    );
});

//when I remove what's above, the code below works.

$('#mayissue').click(function () {
$('#viewbox').html(
"test2"
    );
});
$('#juneissue').click(function () {
$('#viewbox').html(
"test3"
    );
});
$('#julyissue').click(function () {
$('#viewbox').html(
"test4"
    );
});

    });

A: You can't have multiline strings.
To fix this, use separate strings with concatenation:
$('#viewbox').html("
" +
               "
" +
               "
") //... etc.

A: you cant have a single string that spans multiple lines like that, to get it to work that way you would have to do something like this
 $('#viewbox').html("
" +
"
" + .....

With that said, I will then add.  DO NOT ADD HTML THAT WAY
Use a template, or anything other then what you posted.  A very cheap and easy way it to create the html on the page and use css to mark it as display: none, then refenrce the parent object in JS and pass the outerHtml.

A: A good way to write a long multiline string is to use the magic backslash  \ at the end of every line. JS, and you, will be happy:
$('#viewbox').html("\

\

\

\
    ................ \

\

\
    \
");

CONCEPT JSFIDDLE DEMO


text:
Q: I want to make column header dynamic in react ag-grid by using value from database I want to make no of columns and column header in react ag-grid dynamic  Like for example I have value coming from database as 3 so my no of columns should be 3 automatically and there name/headers should be m1, m2 , m3 respectively.

A: You can achieve this by dynamically updating the grid's column definition whenever required (in your case when you get new values from database).
Refer the documentation for more.


text:
Q: Razor MVC - Object Edit Field Change Log Users modify a DB object in an edit form that I have, pretty straight forward.
I need to implement a 'change log' on this object. I need to record which fields where changed and what they were before and after. I'm using Razor MVC.

A: I've done this by writing triggers for the table on update/delete.  On update/delete of a record, the trigger pushes the record to a History table, in a History database.  This creates the change log.  Then you would just need to display it; to identify the change would require evaluating each and every field.
There's nothing already built that wold do this for you that I know of.


text:
Q: Code generation tool/framework for PHP As far as I know, many PHP frameworks use syntactic sugar to provide illusion of real functions. Some provide scaffolding/skeleton generation, which is limited. Syntactic sugar is slow and IDE/editors do not provide intellisense for Syntactic sugar functions/methods and member data. I'm wondering if there any tool/framework to generate PHP code based on some popular frameworks and built around a relational schema? Thanks in advance.

A: I think Symfony has something that you might find interesting.

A: Try Zend Framework.

Zend Framework (ZF) is an open source, object-oriented web application framework implemented in PHP 5 and licensed under the New BSD License.

A: I found QCodo http://www.qcodo.com/wiki/article/background/metaprogramming which satisfies requirements. Thank you very much for participating. You all earned my vote.

A: Zend_Framework has code generator called Zend_Tool, tough it's still unstable.

A: Zend_CodeGenerator
For posterity, I thought I would mention the rather impressive solution I just found to this problem.
Zend_CodeGenerator was added to Zend Framework as of, I believe, version 1.8, and I'm very impressed with it so far. Like most ZF components, it works just fine as a standalone tool; you needn't implement the rest of the framework in your project.
So far it seems easy to use and quite powerful.

A: Have a look at Cygnite Framework's Crud generator. It is very simple and easy to use. The New Cool Kid build on Symfony2 console component, I found interesting, made my job simple and fast.
Cygnite CLI generates controller, model, views, layout, form component, required field validation, pagination etc. with a simple command.
php cygnite generate:crud controller_name table_name database_name

You may alter the code based on your need.
Have a look, may help someone.
Generate CRUD application within 2 minute
Cygnite Framework Code Generator


text:
Q: Strongly Typed RedirectToAction (Futures) using async Controllers having this code it gives me a warning : Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
    public async Task<ActionResult> Details(Guid id)
    {
        var calendarEvent = await service.FindByIdAsync(id);
        if (calendarEvent == null) return RedirectToAction<CalendarController>(c => c.Index());
        var model = new CalendarEventPresentation(calendarEvent);
        ViewData.Model = model;
        return View();
    }

    public async Task<RedirectResult> Create(CalendarEventBindingModel binding)
    {
        var model = service.Create(binding);
        await context.SaveChangesAsync();
        return this.RedirectToAction<CalendarController>(c => c.Details(model.CalendarEventID));
    }

if I do add the await operator I get :
Error  CS4034  The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
if I add the async modifier like this :
return this.RedirectToAction<CalendarController>(async c => await c.Details(model.CalendarEventID));

the error is Error CS1989  Async lambda expressions cannot be converted to expression trees
So how can I use strongly typed RedirectToAction (I'm using MVC Futures) with async controllers?

A: I have figured this out!
I have a base controller and there I have an extension method for async redirects
protected ActionResult RedirectToAsyncAction<TController>(Expression<Func<TController, Task<ActionResult>>> action)
        where TController : Controller
    {
        Expression<Action<TController>> convertedFuncToAction = Expression.Lambda<Action<TController>>(action.Body, action.Parameters.First());
        return ControllerExtensions.RedirectToAction(this, convertedFuncToAction);
    }

this will prevent warnings. Then you can just call RedirectToAsyncAction from your Controller.
public ActionResult MyAction()
    {
       // Your code
        return RedirectToAsyncAction<MyController>(c => c.MyAsyncAction(params,..)); // no warnings here
    }


text:
Q: Popup panel in Windows Phone I'd like to create a control, which behaves similarly to the Windows Phone's keyboard button. When user taps and holds the control, it should expand to show additional options.
Though I generally know, how to implement this control, I have no idea on how to display a panel, which will exceed the boundaries of the control. If there is a way to achieve this effect in Windows Phone (and should be - the keyboard is being displayed this way), how can I do it?

A: You can add a Popup control to your control and show it by setting the Popup's IsOpen property to true. The Popup can show outside of the control's context. Here's a really cheesy UserControl which shows its Popup on Hold:
<UserControl x:Class="PhoneApp48.WindowsPhoneControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    d:DesignHeight="480" d:DesignWidth="480"
    Hold="UserControl_Hold">

    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
        <Rectangle HorizontalAlignment="Stretch" Height="100" Fill="Yellow" />
        <Popup x:Name="myPopup" IsOpen="False">
            <StackPanel Width="{Binding ElementName=LayoutRoot, Path=ActualWidth}" Background="{StaticResource PhoneBackgroundBrush}">
                 <TextBlock TextWrapping="Wrap" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." />
                 <Button Click="Button_Click">Close</Button>
            </StackPanel>
        </Popup>
    </Grid>
</UserControl>

Code:
private void UserControl_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
    myPopup.IsOpen = true;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    myPopup.IsOpen = false;
}


text:
Q: Creating multiple objects inside loop The below code overwrites @journey_lines 10 times leaving only the last journey saved as an array. I want to create a new array object for each journey (1 to 10).
# Save text file to string
data = File.read("workdata.txt")

# Split string into blocks of text relevant to each journey
journeys = data.split(/\n\s\n/)

# Store the amount of journeys as a variable called journeys_size
journeys_size = journeys.length

# Split each journey into lines and save to an array called "journey_lines"
journeys[1..10].each { |i| @journey_lines = i.split(/\n/) }

# Inspect journey_lines
p @journey_lines

Is there a way of inserting a variable into the iteration value? Something like...
journeys[1..#journeys.size].each { |i| @journey_lines[1..#journeys_size] = i.split(/\n/) }

Or a better way of doing this all together. I've been trying to do this for a while. Please help!

A: You should use map method instead
@journey_lines = journey.map {|item| item.split(/\n/) }


text:
Q: Does ksh88 interpret a number as decimal using 10#n syntax? I would like to treat a number with leading zero as a decimal with the least effort
so I intend to use the following syntax:
x=08
y=$(( 10#$x - 1 ))

Will the following syntax work on ksh88?

A: Appears so:
$ command -v ksh
/usr/bin/ksh
$ what /usr/bin/ksh
/usr/bin/ksh:
        Version M-11/16/88i
        SunOS 5.8 Generic 110662-24 Apr 2007
$ ksh

$ x=08
$ y=$(( 10#$x - 1 ))
$ echo "$x - $y"
08 - 7

From the "Arithmetic Evaluation" section of the man page:

Constants are of the form [ base# ] n where
  base   is  a  decimal  number  between  two  and  thirty-six
  representing the arithmetic base and n is a number  in  that
  base.  If base is omitted then base 10 is used.


text:
Q: bind list to dropdownlist, what to do with value? I am binding a List to a DropDownList. But I want to give other values to the value per list item.
I have following ddl and list:
List<string>

sport, volleyball, rugby
<select>
    <option selected="selected" value="0"> Alle soorten</option>
    <option value="sport">sport</option>
    <option value="volleyball">volleyball</option>
    <option value="rugby">rugby</option>
</select>

But I want following (ID in the value)
<select>
    <option selected="selected" value="0"> Alle soorten</option>
    <option value="1">sport</option>
    <option value="2">volleyball</option>
    <option value="3">rugby</option>
</select>

How do I need to create a List so I can get the above dropdownlist.
Thanks

A: What you could do is to create the ListItems manually like this:
List<string> yourValues;
for(var i=0; i < yourValues.Count; i++)
    YourDropDown.Items.Add(new ListItem(yourValues[i], i.ToString());

Or you could create a temporary variable and bind your drop down list with a linq query, like this:
List<string yourValues;
var index = 0;
YourDropDown.DataSource = yourValues.Select(x => new { Text = x, Value = index++ });
YourDropDown.DataBind();

and combine that with the markup:
<asp:DropDownList ID="YourDropDown" DataValueField="Value" DataTextField="Text" runat="server" />

A: If you are able to change the type of your source I would recommend to use a dictionary. You can do it this way:
var source = new Dictionary<int, string>();
source.Add(0, "Sports");
source.Add(1, "Football");
dropDown.DataSource = source;
dropDown.DataTextField = "Key";
dropDown.DataValueField = "Value";
dropDown.DataBind();

This would lead to this:
<select name="DdlCat2" id="DdlCat2" class="cats">
    <option selected="selected" value="Sports">0</option>
    <option value="Football">1</option>
</select>

Later you can access the ID or value like this:
dropDown.SelectedItem.Value
dropDown.SelectedItem.Text

A: Here is the one more way. Convert the DataSet Table to list and bind to  dropdown.
var filter = from dr in ds.Tables[0].AsEnumerable()
            where (dr.Field<int>("FilterID") == 1)
            select new
            {
                FilterID = dr.Field<int>("FilterID"),
                FilterName = dr.Field<string>("FilterName")
            };

ddlSample.DataSource = filter;
ddlSample.DataTextField = "FilterName";
ddlSample.DataValueField = "FilterID";
ddlSample.DataBind();
filter = null; // null the var


text:
Q: Unity Mecanim Blend Issue on 180 Degree Turn I have a quadruped that I want to animate with mecanim in Unity. I have set up a root node for it, and the animation rotates/moves it correctly. I have 2 mecanim states - turning 180 degrees and forward walking. I set a transition between this 2 states. When the blending comes into the action and I want the animal to rotate 180 degrees and walk forward, at the end of the turn instead of continuing walking, it turns another 360 degrees and then does walking animation.
In the attached video you can see the described behaviour.
Any help on this is highly appreciated.


text:
Q: Every time I launch the project, it is only a black screen import UIKit
import CoreData
class KontakteTableViewController: UITableViewController {

    @IBOutlet var KontakteTableView: UITableView!

    var kontakteArray = [Kontakt]()
    var selectedKontakt: Kontakt?

    override func viewDidLoad() {
        super.viewDidLoad()

        KontakteTableView.delegate = self
        KontakteTableView.dataSource = self

       loadData()

    }
    @IBAction func addKontaktButton(_ sender: UIBarButtonItem) {
    }
    @IBAction func searchKontaktButton(_ sender: UIBarButtonItem) {
    }
    @IBAction func deleteAllButton(_ sender: UIBarButtonItem) {
    }

    func createKontakt()  {
        let alert = UIAlertController(title: "Add contact", message: nil, preferredStyle: .alert
        )
        alert.addTextField { (textField) in
            textField.placeholder = "Vorname"
        }
        alert.addTextField { (textField) in
            textField.placeholder = "Nachname"
        }
        alert.addTextField { (textField) in
            textField.placeholder = "Telefonnummer"
            textField.keyboardType = .numberPad

        }

    let action = UIAlertAction(title: "OK", style: .default) { (_) in
        if alert.textFields?[0].text?.count != 0 && alert.textFields?[1].text?.count != 0 &&  alert.textFields?[2].text?.count != 0  {

            let vorname = alert.textFields?[0].text
            let nachname = alert.textFields?[1].text
            let telefonnummer = Int64((alert.textFields?[2].text)!)

            // Core Data
            let kontakt = CoreDataService.defaults.createKontakt(_vorname: vorname!, _nachname: nachname!, _telefonnummer: telefonnummer!)

            // Array
            self.kontakteArray.append(kontakt)
            self.KontakteTableView.reloadData()

        } else {
            self.errorMessage(_message: "Bitte Daten angeben")

        }
    }
    alert.addAction(action)
        present(alert, animated: true, completion: nil)

 }

    func loadData() {
        let kontakteArray = CoreDataService.defaults.loadData()

        if let _kontakteArray = kontakteArray {
            self.kontakteArray = _kontakteArray
            self.KontakteTableView.reloadData()
        }

    }
    func errorMessage(_message: String) {
        let alert = UIAlertController(title: "Fehler", message: _message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { (_) in }
            alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    }
    @objc func longPress(_ sender: UIGestureRecognizer) {
        if sender.state == UIGestureRecognizer.State.ended {
            let longPressLocationPoint = sender.location(in: self.KontakteTableView)

            if let pressIndexPath = self.KontakteTableView.indexPathForRow(at: longPressLocationPoint) {
                var task = UITextField()

                let alert = UIAlertController(title: "Änderung", message: "Neue Daten eingeben", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: .default) { (action) in
                    self.kontakteArray[pressIndexPath.row].telefonnummer = Int64(task.text!)!
                    self.KontakteTableView.reloadData()
                    CoreDataService.defaults.saveContext()

                }
                alert.addTextField { (textField) in
                    textField.placeholder = "Neue Telefonnummer"
                    textField.keyboardType = .numberPad
                    task = textField
                }
                let cancelAction = UIAlertAction(title: "Abbrechen", style: .default) { (_) in

                }
                alert.addAction(action)
                alert.addAction(cancelAction)

                present(alert, animated: true, completion: nil)
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "GoToKontakteInfo" {
            let destVC = segue.destination as! KontaktInfosViewController
            destVC.kontakt = selectedKontakt
        }
    }

}
extension KontakteTableViewController {

// MARK: - Table View DataSource

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return kontakteArray.count
    } // Zeile erstellen
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        cell.addGestureRecognizer(longPressRecognizer)

        let kontakt = kontakteArray[indexPath.row]

        cell.textLabel?.text = "Name: \(kontakt.vorname!) Alter: \(kontakt.nachname!) Telefonnummer: \(kontakt.telefonnummer)"
        return cell
    }

}

extension KontakteTableViewController {
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            CoreDataService.defaults.deleteKontaktFromDataStack(indexPath: indexPath, kontakteArray: &kontakteArray)
            KontakteTableView.reloadData()
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedKontakt = kontakteArray[indexPath.row]

        performSegue(withIdentifier: "GoToUserInformationSeque", sender: nil)
        KontakteTableView.deselectRow(at: indexPath, animated: true)

    }

}

A: The problem may be in your storyboard. Select your first screen that you want to be presented and in the attributes inspector, check "Initial View Controller". Sometimes when I change around the storyboard this happens to me.


text:
Q: c++ reading line by line but not able to show output line by line I am trying to run a C++ code. My input file has number of lines and I am trying remove the spaces in each line and then display. But, when i run the code the output is coming in a single line i.e all thelines of the file are being shown in one single line.
Please solve my problem , so that i get the output line by line.
Thanks.
I have tried this code. This is my code:
int main()
{
    int i = 0, len, j;
    std::string str;
    ifstream iFile("g.txt");
    while (std::getline(iFile, str) != 0)
    {
        len = str.length();
        for (i = 0; i < len; i++)
        {
            if (str[i] == ' ')
            {
                for (j = i; j < len; j++)
                {
                    str[j] = str[j + 1];
                }
                len--;
            }
        }
        cout << str;
    }
}

A: cout<<str; is going to write the string to the output buffer and that is it.  The next time you call it the str you write out will start right after that last str that was written.  If you want each str on its own line then you can use
cout << str << endl;
//or
cout <<str << "\n";

The reason each line does not retain its newline character is that getline() reads until it encounters a newline and then stores everything up to that newline in the string.  It then tosses that newline out instead of adding it to the string.

A: You are writing like this:
cout<<str;

You need to output the new-line after your string, which is done as follows:
cout<<str<<endl;


text:
Q: Find matching values from one column to another column in same table SQL Server If I have this table:

I want to use T-SQL to go through each row and find the EmpID that corresponds to the SupervisorID for each row, and assign the LastName of the supervisor to SupervisorLastName.
So the result should be:

I started with this, but I think it is just checking if SupervisorID is equal to EmpID at the individual row level so it returns nothing.
CASE
    WHEN (EmpID = SupervisorID)
        THEN CAST(LastName AS CHAR(30))
END AS SupervisorLastName

I guess my first example was misleading because I actually want to create the column SupervisorLastName. My example shows that it already exists. Thanks

A:   ALTER TABLE TableName
  ADD SuperVisorLastName NVARCHAR(100) DEFAULT NULL;

  UPDATE TB1
  SET SuperVisorLastName = TB2.LastName
  FROM TableName TB1
  CROSS APPLY (SELECT TOP 1 * FROM TableName TB2 WHERE TB2.EmpID =
  TB1.SupervisorID) TB2

I would do something like the above just add the column defaulted to null. Then do a cross apply to get the correct last name and update the column. Not copy and pastable but should give you a rough idea of how you could do it.
That being said you already technically know who the supervisor is because of the ID on there. So you do not need to unnecessarily repeat data in your data base.

A: Could you try something like this?
SELECT t1.*,
       t2.LastName AS SupervisorLastname
FROM table1 t1
LEFT JOIN (SELECT EmpID, LastName FROM table1) t2 ON t2.EmpID = t1.SupervisorID

A: SELECT  t1.EmpID,
    t1.FirstName,
    t1.LastName,
    t1.SupervisorID,
    t2.LastName AS SupervisorLastname
FROM #testTable t1
LEFT JOIN #testTable t2 ON t2.EmpID = t1.SupervisorID


text:
Q: Extract date from a path in powershell I have a folder called files which has a path like : C:\users\xxxx\desktop\files
Inside this folder are different folders: 2015-12-02, 2015-12-01, 2015-11-30, etc
Inside each folder there are multiple files. I was looking to append the folder date at the end of each file inside the folder. I have written the below script for that:
function checkfile($file) {
    $filenm = $file.FullName
    return($filenm.Contains('.txt'))
}

function renamefile($file) {
    $filenm = $file.Name
    $ip = $file.FullName.Substring(34)
    $ip1 = $ip.Substring(1,4) + $ip.Substring(6,2) + $ip.Substring(9,2)
    $txt = $filenm.Split(".")[1] + "_" + $file.name.Split(".")[3] + "_" + $file.name.Split(".")[4] + "." + $file.name.Split(".")[2] + "." + $ip1
    Rename-Item $file.FullName -NewName $txt
}

$sourcepath = "C:\users\xxxx\desktop\files"
$inputfiles = (Get-ChildItem -Path $sourcepath -Recurse) | Where-Object { checkfile $_ }

foreach ($inputfile in $inputfiles) {
    renamefile $inputfiles
}

The problem I'm facing is in the above script I have used substring(34) to extract the date from the file path. If for some reason the source path changes (to say : H:\powershell\scripts\files) then 34 will not work.
How can I extract the correct date from the file path irrespective of the full file path?

A: Why not:
$sourcepath = "C:\users\xxxx\desktop\files"

Get-ChildItem -Path $sourcepath -Include "*.txt" -Recurse | % {
    Rename-Item $_ "$($_.BaseName)_$($_.Directory)$($_.Extension)"
}

BaseName is the file name without the extension
Directory is the directory name (your date)
Extension is the file extension (i.e. .txt)
$(...) is used to make sure ... is evaluated properly
% is an alias for ForEach-Object and will iterate over the objects coming from the pipeline.
$_ will hold the current object in the ForEach loop
Here, your checkfile function is replaced by -Include "*.txt".
Example :
C:\users\xxxx\desktop\files\2015-12-02\sample.txt

becomes
C:\users\xxxx\desktop\files\2015-12-02\sample_2015-12-02.txt

Not sure if you need it, but if you want to remove the dashes from the date, you could use:
Rename-Item $_ "$($_.BaseName)_$($_.Directory -replace '-','')$($_.Extension)"

EDIT : OP wished to remove the dashes but append the date after the file extension, so:
$sourcepath = "C:\users\xxxx\desktop\files"

Get-ChildItem -Path $sourcepath -Include "*.txt" -Recurse | % {
    Rename-Item $_ "$($_.Name).$($_.Directory.Name -replace '-', '')"
}

A: The particulars of the problem aren't entirely clear. I gather that the date your are interested in is in the fullpath. You want to extract the date from the path and rename the file, such that the new filename includes that date at the end.
However your script implies that there are at least five periods in the path. But I don't see that mentioned in the OP anywhere.
So there are a few problems and open items I see:
1. What is the syntax of a full path? That includes the five or more periods
2. Will the date always be at the same directory depth? I'm guessing xxxx represents the date. If so the date is the second subdirectory. Will the date always be in the second subdirectory?
3. Related to #2, will there ever be paths that include two or more dates?
Assuming my guesses are correct AND that the date will always be the second subdirectory, then extracting the date would be:
`$dateString = $file.fullpath.split('\')[3]

If some of my guesses are incorrect then please add details to the OP. If #3 is true then you'll need to also explain how to know which date is the correct date to use.

A: An option that you could do is just cd to each path. Then use Get-ChildItem in each dir, without using -Recurse.
In rename $ip would just be $file, no need for FullName.
For example, define your functions and then:
$sourcefile = 'Whateversourcediris'
cd $sourcefile
$directories = (Get-ChildItem)
foreach ($direct in $directories) {
    cd $direct
    $inputfiles = (Get-ChildItem)|where-object{checkfile $_}
    foreach ($inputfile in $inputfiles) {
        renamefile $inputfile
    }
    cd..
}

Hope this helps.


text:
Q: R: looking for a more efficient way of running rbinom() taking probabilities from a large matrix I have a 20000x90 matrix M of probabilities ranging between 0 and 1. I want to use these probabilities to return a 20000x90 matrix of 1's and 0's (i.e. for each probability p in the matrix I want to run rbinom(1,1,p)).
This is my current solution which works:
apply(M,1:2,function(x) rbinom(1,1,x))

However, it is quite slow and I am wondering if there is a faster way of achieving the same thing.

A: rbinom is vectorised, so you can pass the vector (or matrix) of probabilities; you just need to change the n, the number of observations, from 1 to the number of values in M.
An example:
# with loop
set.seed(74309281)
M = matrix(runif(20000*90), nr=20000, nc=90)
a1 = apply(M,1:2,function(x) rbinom(1,1,x))

# without loop
set.seed(74309281)
M = matrix(runif(20000*90), nr=20000, nc=90)
a2 = matrix(rbinom(length(M),1,M), nr=nrow(M), nc=ncol(M))

all.equal(a1, a2)
# [1] TRUE


text:
Q: Automatization of Screen Scraping for Project-Calls First of all, I am a complete novice regarding coding, therefore I don't really know where to start. I hope screen-scrapting is the right description.
My challenge:
I have a website which regularly publishes project-calls ("Bekanntmachung" in german: https://www.bmbf.de/foerderungen/).
These calls have a set format with set sections (sorry for the german, but you get an idea: https://www.bmbf.de/foerderungen/bekanntmachung-2888.html).
From some of the sections I want to extract information, e.g. What is the Name/Topic of the call, who can apply, how much money do you get, when is the deadline, who to contact. This information is always formulated in a very similar, if not exactly the same way and at a similar position.
I would like to write/get a tool, which can automatically extract this information for all the calls from the last 3-6 Months and put it in a excel file.
So where do I start? What language should I use, is there any database of similar algorithms I could look into and adjust to get the information I need?
Thank you for the help.
Best,
Jonas.

A: At the bottom of the page, there is a "follow us" and a link to an RSS feed. If that shows what you want, that could do half your work. It's already updated and parsable XML.


text:
Q: Android automative system image not available Why Android automative system image is not available to create an emulator?

A: Android Automotive emulator :-> you need to add system image of polestar and for that select Tools > SDK Manager
Then , Click the SDK Update Sites tab
Now Click on Add Icon
Enter Name and Url for image
Name: Polestar 2 System Image
URL: https://developer.polestar.com/sdk/polestar2-sys-img.xml

A: Usually the system image should be available by default in the SDK Manager.
Tools->SDK Manager->Android SDK.
Under Tools->SDK Manager->Android SDK->SDK Tools you can install the Intel x86 Emulator Accelerator
Under Tools->SDK Manager->Android SDK->SDK Update Sites you should be able to see the system image name and urls. If you don't find you can add them as below

*

*Android Automotive System Images: https://dl.google.com/android/repository/sys-img/android-automotive/sys-img2-1.xml

*Android System Images: https://dl.google.com/android/repository/sys-img/android/sys-img2-1.xml

*Intel HAXM: https://dl.google.com/android/repository/extras/intel/addon2-1.xml

*Google API add-on System Images: https://dl.google.com/android/repository/sys-img/google_apis/sys-img2-1.xml

*Google API with Playstore System Images: https://dl.google.com/android/repository/sys-img/google_apis_playstore/sys-img2-1.xml


text:
Q: Div captura o tamanho de outra Bom dia prezados(as), tenho um html e de vez em quando preciso inserir uma imagem que é uma "}" para determinar que em uma música irá repetir aquele trecho.
Como meu texto se adapta ao tamanho da tela, quando movimento ele muda de tamanho e a imagem é fixa, o que preciso é que ela se adapte ao tamanho do texto.
No planejamento que tive, comecei com uma ideia muito boa, deixei a div que possui o louvor sem Height, dessa forma ele fica automático, ficando na altura exata do texto. Se eu coloco a div onde está a chave sempre da mesma altura (até mesmo quando a outra é redimensionada).
Abaixo segue uma imagem onde destaquei as duas div's para entenderem melhor:

Caso eu consiga de alguma maneira, deixo minha resposta, até lá, aceito qualquer ajuda ou ideia.
CSS:
#louvor{
        background-color: rgba(00,00,00,0.8);
        margin-left: 1%;
        width: 93%;
        position: relative;
        float: left;
        font-size: 3.5vw;
        text-align: left;
        color: white;
        text-transform: uppercase;
        text-shadow: 1px 1px black;
        font-family: "Futura XBlk BT", Times, serif;
}

HTML:

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

        <link href="../../css/style.css" rel="stylesheet" />

            CORO:

            AS MINHAS MÃOS TRAZEM CHAGAS TÃO FUNDAS

            QUE TANTA AMARGURA EU PUDE ABRIGAR

            DE TODA DOR DE VERGONHA E PECADO

            EU FUI COROADO PARA TE SALVAR

A: consegui desenvolver algo que me atenda, vou publicar a resposta para que se alguém tenha dúvidas futuras e ache meu código viável, está a disposição.
Primeiro, dentro do meu HTML eu adicionei uma imagem normalmente:

            AS MINHAS MÃOS TRAZEM CHAGAS TÃO FUNDAS

            QUE TANTA AMARGURA EU PUDE ABRIGAR

            DE TODA DOR DE VERGONHA E PECADO

            EU FUI COROADO PARA TE SALVAR

Depois de forma muito simples, adicionei um css para a imagem:
.chave-big{
    height: 19vw;
    float: right;
}

Desta forma, estou utilizando um tamanho height com um valor responsivo "vw" e defini que a imagem terá o valor float para a direita, desta forma, ele acompanha meu texto no tamanho, porque meu texto também é responsivo baseado no "vw".
Obrigado a todos.

A: Criei uma div qualquer, com um texto qualquer:

      Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e o

Então criei o seguinte código css, peguei uma imagem qualquer no google e coloquei como se fosse a sua chave, coloquei para ela não se repetir e do lado direito, para o texto não ficar por cima dela, coloque um padding a direita e coloquei para ela ficar de acordo com a altura da div.
.teste{
  background-color: #f00;
  width: 200px;
  background: url('https://teja8.kuikr.com/i6/20171219/After-1-year-of-use--it-is-still-going-well-VB201705171774173-ak_WBP1721615504-1513671149.jpeg') right;
  background-repeat: no-repeat;
  background-size: auto 100%;
  color: #fff;
  padding-right: 20px;
}

Resultado: https://jsfiddle.net/r1rdznc3/1/

Se você for utilizar este mesmo código css em mais de uma parte na
  pagina, não utiliza id, utiliza classe.


text:
Q: symbols not found with zlib functions As from title, when compiling
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <assert.h>
#include <zlib.h>

int main(){

    char *infilename = "triples.txt.gz";
    char *outfilename = "out_test.txt";
    gzFile infile = gzopen(infilename, "rb");
    FILE *outfile = fopen(outfilename, "wb");
    if (!infile || !outfile) return -1;

    char buffer[128];
    int num_read = 0;
    num_read = gzread(infile, buffer, sizeof(buffer));
    while (num_read > 0) {
        fwrite(buffer, 1, num_read, outfile);
    }

    gzclose(infile);
    fclose(outfile);
    return 0;
}

I get the message
Undefined symbols for architecture x86_64:
  "_gzclose", referenced from:
      _main in ccfPmLqz.o
  "_gzopen", referenced from:
      _main in ccfPmLqz.o
  "_gzread", referenced from:
      _main in ccfPmLqz.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

I am having some troubles figuring out what it is saying. zlib seems to be installed as while adapting the code I had some errors regarding specific zlib functions (like not enough arguments for gzopen).

A: You didn't link zlib when you compiled. Assuming zlib is in the standard path, you need to compile as
gcc -lz -o c_test sometest.c


text:
Q: Measuring transport time between two nodes my goal is to measure the transport time between two network nodes, using different routers (and set ups), different network adapters (and set up) and different data-volumes.
My hardware set-up are single-board-computers with Debian CLI installed and are reachable over ssh.
The Question: If there any Linux CLI tool to measure the transport time?
I heard from tcpdump, which visualises the TCP-header. But I use UDP and I can't find any good tool for UDP (maybe because UDP don't have this information in it's header).
My first approach was to write two own small programs: a sender-receiver, which measure the time, and a repeater. But I think, that measuring in the application layer leads to unpredictable errors. So I'm looking for a tool, which uses lower layer.
Thanks in advance
Alex


text:
Q: SQLAlchemy DateTime to datetime.datetime How do you make comparisons between DateTime fields and datetime.datetime objects in SQLAlchemy queries?
For instance, if I do
candidates = session.query(User).filter_by((User.time - datetime.datetime.utcnow()) > datetime.timedelta(months=2))

I will get
TypeError: unsupported operand type(s) for -: 'DateTime' and 'datetime.datetime'

I'm guessing this is because the DateTime field is never fully extracted when we use the filter_by command, hence it is not coverted to a datetime.datetime object? Is this correct? How do SQLAlchemy users generally handle this?
Note: User.time is a DateTime field.

A: First of all, notice that datetime.timedelta does not take 'months' as an argument. Try it with 'weeks=8' instead (http://docs.python.org/2/library/datetime.html#datetime.timedelta).
Second, use 'filter' rather than 'filter_by' as the latter is for simpler queries involving queries by value (i.e. User.name='Bob' http://docs.sqlalchemy.org/en/rel_0_8/orm/query.html#sqlalchemy.orm.query.Query.filter).
So, what I would write would look like this:
candidates = session.query(User).filter((User.time - datetime.datetime.utcnow()) > datetime.timedelta(weeks=8))

And finally, what is the mapping of your 'User' table, maybe the problem is with the Columns definitions?


text: Q: Basis for differentials of a smooth plane curve Given a smooth plane curve $C$ cut out by a homogeneous polynomial $f(x,y,z)=0$, how to calculate a basis for the space of global differential forms? There is the adjunction formula which shows that the canonical bundle of $C$ is $\omega_C = \omega_\mathbb{P^2} \otimes O(d)|_C$ where $d$ is the degree of the curve but it's not clear that the map on global sections is surjective.


text:
Q: Quadrature rule for adaptive scheme with reuse I want to integrate a funktion, which is every slow to evaluate and spiky. Therefore I want to use an adaptive scheme.
I would like my subintervals to reuse the points I already calculated. I can only think of the trapezoidal rule, where the rule involves two points only. Is there any higher order rule where I do not discard points I already calculated?
The way I understand Gauss–Kronrod and Clenshaw–Curtis they only reuse the points if I don't change the interval. Is there any method, where I the same points for the inital interval and my subintervals?


text:
Q: Is there any difference between flatten and flatMap(identity)? scala> List(List(1), List(2), List(3), List(4))
res18: List[List[Int]] = List(List(1), List(2), List(3), List(4))

scala> res18.flatten
res19: List[Int] = List(1, 2, 3, 4)

scala> res18.flatMap(identity)
res20: List[Int] = List(1, 2, 3, 4)

Is there any difference between these two functions? When is it appropriate to use one over the other? Are there any tradeoffs?

A:
Conceptually there is no difference in the result... flatMap is taking
  bit more time to produce same result...

I will show it more practically with an example of flatMap, map & then flatten and flatten

object Test extends App {
  // flatmap
  println(timeElapsed(List(List(1, 2, 3, 4), List(5, 6, 7, 8)).flatMap(identity)))
  // map and then flatten
  println(timeElapsed(List(List(1, 2, 3, 4), List(5, 6, 7, 8)).map(identity).flatten))
  // flatten
  println(timeElapsed(List(List(1, 2, 3, 4), List(5, 6, 7, 8)).flatten))

  /**
   * timeElapsed
   */
  def timeElapsed[T](block: => T): T = {
    val start = System.nanoTime()
    val res = block
    val totalTime = System.nanoTime - start
    println("Elapsed time: %1d nano seconds".format(totalTime))
    res
  }
}

Both flatMap and flatten executed with same result after repeating several times
Conclusion : flatten is efficient

Elapsed time: 2915949 nano seconds
List(1, 2, 3, 4, 5, 6, 7, 8)
Elapsed time: 1060826 nano seconds
List(1, 2, 3, 4, 5, 6, 7, 8)
Elapsed time: 81172 nano seconds
List(1, 2, 3, 4, 5, 6, 7, 8)

A: Conceptually, there is no difference.  Practically, flatten is more efficient, and conveys a clearer intent.
Generally, you don't use identity directly.  It's more there for situations like it getting passed in as a parameter, or being set as a default.  It's possible for the compiler to optimize it out, but you're risking a superfluous function call for every element.
You would use flatMap when you need to do a map (with a function other than identity) immediately followed by a flatten.

A: You can view flatMap(identity) as map(identity).flatten. (Of course it is not implemented that way, since it would take two iterations).
map(identity) gives you the same collection, so in the end it is the same as only flatten.
I would personally stick to flatten, since it is shorter/easier to understand and designed to exactly do this.


text:
Q: WPF mvvm View won't update when called from different ViewModel I've been trying to update a property inside a usercontrol with it's own VM.
<Label Content="{Binding Path =LabelText ,UpdateSourceTrigger=PropertyChanged }" Grid.Column="0"/>
The Label itself works when I set it's text in the VM's constructor, and also updates if I use a command within the VM.
But changing it from outside won't do anything:
        private LabelTextBoxVM _testThing;
        public LabelTextBoxVM TestThing
        {
            get => _testThing;
            set
            {
                _testThing = value;
                NotifyPropertyChanged("TestThing");
            }
        }

           private void Update()
        {
            TestThing.LabelText = "Eureka";
            TestThing.TextBoxText = "Wooosh";
            NotifyPropertyChanged("TestThing");
        }

From all I've read, calling NotifyPropertyChanged for TestThing should update the content of both Label and Textbox, but nothing happens.

A: @Clemens
I found the answer, provided by you actually, in another question:
wpf-mvvm-usercontrol-binding
I have to set my DataContext in the parent view, binding to a property in the parent, and delete the Datacontext inside the childVM
So:
<myViewes:UserControlName DataContext="{Binding VMProperty}/>"
And this part cannot be in my UserControls:
<UserControl.DataContext>
        <viewModels:UserControlVM/>
</UserControl.DataContext>

I am guessing this was what you meant by "inheriting" the VM
Thank you!


text:
Q: Using range() as a value when creating a dictionary I am trying to use range() to fill in values in a list of dictionaries from a custom range.
I have this code:
import requests
import json
import time

test = []
for x in range(5000,5020):
    page_url = f'https://api.jikan.moe/v4/anime/{x}/full'
    response = requests.get(page_url)
    json_data = json.loads(response.text)
    test.append(json_data)
    time.sleep(1)

anime_data = []
for dic in test:
    anime = {
        'call_id': range(5000,5020),
        'title': dic.get('data',{}).get('title','title not found'),
        'mal_id': dic.get('data',{}).get('mal_id', 'id not found'),
        'url': dic.get('data',{}).get('url', 'url not found')
    }
    anime_data.append(anime)

The goal is to use numbers from 5000 to 5020 in sequence for the 'call_id' key of each dict, so that the output would look like:
[{'call_id': 5000,
  'title': 'title not found',
  'mal_id': 'id not found',
  'url': 'url not found'},
 {'call_id': 5001,
  'title': 'title not found',
  'mal_id': 'id not found',
  'url': 'url not found'},
 {'call_id': 5002,
  'title': 'Bari Bari Densetsu',
  'mal_id': 5002,
  'url': 'https://myanimelist.net/anime/5002/Bari_Bari_Densetsu'}]

The code did not work as intended. How can I get the desired result?

A: Another approach to the problem: fundamentally, we would like to iterate over two lists in parallel - the raw API responses, and the numbers (from the range) that we want to use in the anime entries. So, the naive response is to use zip, thus:
for call_id, dic in zip(range(5000, 5020), test):
    anime = {
        'call_id': call_id,
        'title': dic.get('data',{}).get('title','title not found'),
        'mal_id': dic.get('data',{}).get('mal_id', 'id not found'),
        'url': dic.get('data',{}).get('url', 'url not found')
    }
    anime_data.append(anime)

However, this overlooks a more specific, built-in tool: the built-in enumerate function. We just have to set the start point appropriately; we don't need to worry about how many elements there are - it will just keep incrementing until we run out.
That looks like:
for call_id, dic in enumerate(test, 5000):
    anime = {
        'call_id': call_id,
        'title': dic.get('data',{}).get('title','title not found'),
        'mal_id': dic.get('data',{}).get('mal_id', 'id not found'),
        'url': dic.get('data',{}).get('url', 'url not found')
    }
    anime_data.append(anime)

A: Since there is already a loop to produce all the same 'call_id' values that are in range(5000,5020) - in order to make the API calls in the first place - a simple approach is to just create the final data directly in the first loop, instead of storing json_data results and trying to process them in a later loop. That looks like:
anime_data = []
for x in range(5000,5020):
    page_url = f'https://api.jikan.moe/v4/anime/{x}/full'
    response = requests.get(page_url)
    json_data = json.loads(response.text)
    anime = {
        'call_id': x,
        'title': json_data.get('data',{}).get('title','title not found'),
        'mal_id': json_data.get('data',{}).get('mal_id', 'id not found'),
        'url': json_data.get('data',{}).get('url', 'url not found')
    }
    anime_data.append(anime)
    time.sleep(1)

We can organize the logic better by using functions to split up the tasks performed each time through the loop, and by pre-computing the .get('data',{}) result:
def query_api(anime_id):
    page_url = f'https://api.jikan.moe/v4/anime/{anime_id}/full'
    response = requests.get(page_url)
    return json.loads(response.text).get('data',{})

def make_anime_data(anime_id, raw_data):
    return {
        'call_id': anime_id,
        'title': raw_data.get('title','title not found'),
        'mal_id': raw_data.get('mal_id', 'id not found'),
        'url': raw_data.get('url', 'url not found')
    }

anime_data = []
for x in range(5000,5020):
    raw_data = query_api(x)
    anime_data.append(make_anime_data(x, raw_data))
    time.sleep(1)


text:
Q: Reading the text file line by line and push to an array in AS3 I need some code in AS3 that will read a text file line by line and insert it into an array. Is this possible without having any special character?
sample.txt
    car
    van
    scooter
    bike

I need to read the file and insert it into an array like:
Array[0]=car
Array[1]=van
Array[2]=scooter
Array[3]=bike

A: Here is an example of loading and reading different file types with ActionScript 3:
      import flash.filesystem.FileMode;
      import flash.filesystem.FileStream;
      import flash.filesystem.File;

      var myFile:File = File.appResourceDirectory; // Create out file object and tell our File Object where to look for the file
      myFile = myFile.resolve("mySampleFile.txt"); // Point it to an actual file

      var fileStream:FileStream = new FileStream(); // Create our file stream
      fileStream.open(myFile, FileMode.READ);

      var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); // Read the contens of the
      fileContents_txt.text = fileContents; // Display the contents. I've created a TextArea on the stage for display

      fileStream.close(); // Clean up and close the file stream

After reading the string, you can use the int.valueOf() to convert the string to the integer.

A: Something like this may work:
var myTextLoader:URLLoader = new URLLoader();

myTextLoader.addEventListener(Event.COMPLETE, onLoaded);

function onLoaded(e:Event):void {
    var myArrayOfLines:Array = e.target.data.split(/\n/);
}

myTextLoader.load(new URLRequest("myText.txt"));

The array in the onLoaded function will have your array of items.
Edit- for fun, I ran the code with a sample file and it worked like a charm.

A: hmmm, it's really a bit strange to use space as a separator.
I mean, you could do it this way:
var result:Array = [];
for each (var s:String in source.split(" ")) {
     var a:Array = s.split("=");
     result[a[0]] = a[1];
}

yet relying on " " for splitting, really is not such a good idea,
can't you use JSON, CSV or XML?

A: This will work for small files, not for humongous files like say firewall or webserver log files.
Those files won't load completely into memory at all.
Is there a solution to
1/ read a file until you encounter the end of line char,
2/ process that which is read,
3/ and then continue until the next end of line/end of file char ?
I think it would be possible using filestream reading 1 byte at a time and seeing if it contains a newline char, and pushing that byte content onto an array until you encounter the EOL char, but I'm not (yet) strong enough in AS to write something like that without loosing 3 months of my life... plus I'm not too sure about the speed of the process.
Anyone ? I would prefer to not launch a seperate question as this essentially the same demand but for larger files...

A: if you are using a real time recording, text is more fast to generate than others like .json or .xml. But xml and json are more easy to read and parse.

A: For those wondering about large text files, you can't know when there'll be a line break before you read the line break byte. What I suggest is to have a loop that would instead of read all bytes with

fileStream.readUTFBytes(fileStream.bytesAvailable);

You do a few hundred bytes at a time, process whatever you need, then continue reading after.


text:
Q: How would you turn a single-level df to a multilevel df in Pandas? I have a dataframe in Pandas that looks like so:
   a   b   c   d
0  1   2   3   4

I'd like to turn the columns into a MultiLevel index, so that the dataframe looks like this:
   a   b
   c   d
0  1   2
1  3   4

I have tried df.reindex(columns=pd.MultiIndex.from_arrays([["a","b"],["c","d"]])) but this does not preserve the values.
Any help is appreciated!

A: Try this:
(pd.DataFrame(
    df.to_numpy()
    .reshape(2,-1),
    columns = pd.MultiIndex.from_arrays([df.columns[:2],df.columns[2:]])))

a better answer that mozway suggested:
(pd.DataFrame(
    df.to_numpy()
    .reshape(2,-1),
    columns = pd.MultiIndex.from_arrays(df.columns.to_numpy().reshape(2,-1)))

Output:
   a  b
   c  d
0  1  2
1  3  4

A: One way to do is:
    cols = ['c', 'd']
    other_cols = df.columns.drop(cols)
    new_idx = pd.MultiIndex.from_arrays([other_cols, cols])
    pd.DataFrame(np.vstack([df[other_cols], df[cols]]), columns=new_idx)

output:
    a   b
    c   d
0   1   2
1   3   4


text:
Q: Creating a custom endpoint for rest, I see the endpoint exists in the wp-json, but the request is returning 404 I have attempted to register the route, tried all sorts of different parameters, feel my code looks like many of the examples on this site, but can't figure out why it doesn't work.
//Register REST Route
add_action('rest_api_init', 'add_advent_api');

function add_advent_api()
{
    register_rest_route('adventapi/v1', '/adventapi/', array(
        'methods' => 'WP_REST_Server::READABLE',
        'callback' => function () {
            return 'hello';
        },
        'args' => array(
            'adventyear' => array(
                'required' => true,
                'type' => 'integer',
                'description' => 'Year required',
                'minimum' => 1972,
                'maximum' => 9999,
            ),
            'adventday' => array(
                'required' => true,
                'type' => 'integer',
                'minimum' => 1,
                'maximum' => 24,
            ),
        ),
        'permission_callback' => function () {
            return true;
        }
    ));
}

function advent_query(WP_REST_Request $request)
{
    return 'i work';
    /*    $adventyear = $_GET['adventyear'];
    $adventday = $_GET['adventday'];

    $args = array(
        'post_type' => 'advent',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => 'advent_year',
                'value' => $adventyear,
            ),
            array(
                'key' => 'advent_day',
                'value' => $adventday,
            ),

        ),

    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        echo 'i ahve posts';
    } else {
        echo 'No Results';
    } */
}

A: There's an issue in your code: The HTTP method is not valid because WP_REST_Server::READABLE is a class constant, hence it should not be wrapped in quotes:
register_rest_route( 'adventapi/v1', '/adventapi/', array(
//  'methods' => 'WP_REST_Server::READABLE', // wrong
//  'methods' => "WP_REST_Server::READABLE", // wrong
    'methods' => WP_REST_Server::READABLE,   // correct

    // ... other args.
) );

You should also ensure that you use the correct request/HTTP method as well as correct endpoint URL, e.g. https://example.com/wp-json/adventapi/v1/adventapi, when making requests to the API.


text:
Q: Iteration over references? I would like to perform the same operation on several arrays, something like:
#include<vector>
#include<algorithm>
int main(void){
    std::vector<double> a, b;
    for(auto& ab:{a,b}) std::sort(ab.begin(),ab.end()); // error
}

This code fails, since auto& is a const-reference. Is there an elegant way around it?

A: I think the issue is that it's a bit like binding a temporary to a non-const reference. There is no "concrete" collection there so it is a bit like a temporary.
IF you have a temporary vector there, it will bind to a const reference but not a non-const one.
I also think this won't ever work what you are doing, but this should work:
#include<vector>
#include<algorithm>
int main(void)
{
    std::vector<double> a, b;
    for(std::vector<double>* ab:{&a,&b})
      std::sort(ab->begin(),ab->end()); // or begin(*ab),end(*ab)
}

and auto may work too.

A:
This code fails, since auto& is a const-reference. [emphasis mine]

Your reasoning doesn't hold. In a range-based for loop, what you declare (here, auto& ab) is not bound to the range expression (here, {a,b }). Instead, ab will be initialized from the elements of the range, not the range itself.
Instead the error stems from calling std::sort with parameters ab.begin()/ab.end(), which can easily be witnessed by commenting the body of the loop. As RMartinho has pointed out, the elements of the std::initializer_list<std::vector<double>> are immutable, and you can't sort a const container (std::sort shuffles elements using moves, can't assign to a const element).
Assuming you want to (independently) sort both vectors, you can do:
for(auto& ab: { std::ref(a), std::ref(b) })
    std::sort(std::begin(ab.get()), std::end(ab.get()));

Notice that according to template argument deduction rules, auto& is fine here and auto will be deduced to const std::reference_wrapper<std::vector<double>>, yielding std::reference_wrapper<std::vector<double>> const& as the type of ab.

A: I think CashCows solution is nice. Just to show a different way: You could also use variadic templates to solve this.
#include <vector>
#include <algorithm>

using namespace std;

void mysort() {} // termination version

template<typename Arg1, typename... Args>
void mysort(Arg1 &arg1, Args&... args )
{
    sort(arg1.begin(), arg1.end());
    mysort(args...);
}

int main(void)
{
    vector<double> a, b;
    mysort(a, b);
}

@CashCow: It is possible to pass an algorithm as argument but it is a little bit ugly because of the use of decltype:
#include <vector>
#include <algorithm>

using namespace std;

template<typename Algo>
void mysort(Algo algo) {} // termination version

template<typename Algo, typename Arg1, typename... Args>
void mysort(Algo algo, Arg1 &arg1, Args&... args )
{
    algo(arg1.begin(), arg1.end());
    mysort(algo, args...);
}

int main(void)
{
    vector<double> a, b;
    mysort(&sort<decltype(a.begin())>, a, b);
}


text:
Q: DllImport from class library or web service project I created a console application to import "C" Dll using DllImport
The "C" Dll has reference to other Dll's and Config files in same folder.
When i put all the files in bin directory of Console applicaiton it works perfect.
But when i create a Web application to consume the same it does not work. (The dll reference are fine when i set the path, but it seems the config files are not getting loaded)
I have tried below but did not help.

*

*Copy the DLL's and config files to System32.

*Give access permission to IIS.

*Disable shadow copy.

None seem to work, Any other suggestions?

A: I solved the issue.
I used Directory.SetCurrentDirectory(); to set the path of the dll's and config files.
if its not possible to change the current directory. Place the files in path Directory.GetCurrentDirectory();

A: You'll need to move the configuration into the web.config file for the web application
There's some good advice on how to do that here: Custom section/collection in Web.Config


text:
Q: Local caching with Parse I'm facing a pretty big problem today: I decided to use Parse as a backend for my mobile application. When retrieving data from server, Parse put the result in a local cache so we can use it offline too, which is great. But when adding or updating an object offline, Parse has no mechanism to update the local cache, which leads to big problems when the app has to be used offline.
I decided to maintain a local cache by myself using SQLite : I look on the server entries and on the local cache entries and then, using the dates, I manage to synchronize the data. The problem is that the updatedAt and createdAt fields are set when data are saved in the backend (which is normal), but then how do I know that an entry created offline is older or younger that the online data ? I could use the phone's time but that's quite random knowing that there could be a difference of some minutes.
Any idea?
I'm even open about new tools to use. I mean I'm not focused on Parse so if you have the perfect tool just tell me!

A: you could set a last synced time in shared preferences and if the updated or created time is > the last sync time then you know it is new then update the last sync time again when your sync is done

A: How about saveEventually()? Based on the explanation in the API docs, I think this will solve the problem.
Also, one more suggestion, if you want to cache your ParseObject, instead of the painful SQLite and tables and all, you could use internal storage to save the object as is explained in this article.

A: There is a problem on Class with pointer.
Known bug: https://groups.google.com/forum/#!topic/parse-developers/arRBB7S559M


text:
Q: Transversal vector field Let $X$ be a vector field on some manifold $M$, $Y \subset M$ a submanifold.
What does it mean for $X$ to be transversal to $Y$ , denoted  $Y \pitchfork X$?
It appears in my lecture in the following definition:
$(M, \omega)$ symplectic. A hypersurface $W \subset M$ is called of contact type, if there exists a vector field $Y$ defined on a neighborhood of $W$ in $M$, s.t.
1)$Y \pitchfork W$
2)$L_Y \omega = \omega$


text:
Q: Very strange C# RemotingException When I compile and run my program in Debug mode, everything works as intended. However, when I compile and run in Release mode, things get a little... strange. I receive the following exception if I run the Release mode executable

RemotingException occurred: The async result object is null or of an
  unexpected type.

We do use .NET remoting in our application, however, I can confirm this is not a problem with any of my remote calls. This is happening right when I open the program, before I can even step into the Main() method. I have not really been able to find any help on the internet regarding this particular exception/message combination, other than a suggestion about the path being too long (but neither my working copy or the installed copy should have paths long enough to trigger this). Any assistance on this is greatly appreciated, as I'm not entirely sure how to proceed with this error.

A: Check here: mystery RemotingException raised when changing Platform Target to Any CPU
It seems to change the paths to the DLL's you want to access. Take a look at the paths in the linked question. They are well over 127 chars, and there is nothing you can do about it.
Example:
'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities.Sync\10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.Sync.dll
EDIT: Try changing to "x86" and see if the error goes away.


text:
Q: Modifying a Date Variable I want to return the month from my date variable in SAS Visual Analytics. I did calculated item --> month('Date_Variable') and it returned numbers 1-12, but I want it to return the month name.

A: you don't need to calculate the month. Just use a format.
input(dateVariable, monname10.)

A: You don't need to create a new calculated item.
You can create a new duplicate of the date variable and change the format of that by right-clicking on the variable and changing the format.


text:
Q: UITableView's last row's separator is disappearing/reappearing I'm developing for iOS 7, and I've noticed that for non-grouped table views, the last row's bottom separator sometime appears and sometimes disappears. If I select that row, it usually causes it to disappear, but sometimes I get the opposite behavior. Has anyone else come across this issue?

A: Create your own cell separator and add it to your cell
 UIImageView *customSeperator=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"YourOnePixelImg.png"]];

 [customSeperator setFrame:CGRectMake(0, cell.frame.size.height-3, cell.frame.size.width, 2)];

 [cell  addSubview:customSeperator];


text:
Q: OAuthException when trying to upload/post photos to group I am currently trying to upload photos to pages and groups through an app. I have these codes:
try
{
    $facebook->setFileUploadSupport(true);
    $args = array('message' => 'This is my image caption',);
    $args['image'] = '@'.realpath('./uploads/terragarden1.png');
    $response = $facebook->api('/GROUP_ID/photos/','POST',$args);
}
catch(FacebookApiException $e)
{
     echo "Error: ".$e;
}

The value of $args['image'] would be something like this:
@/home/publica/public_html/AutoPost/uploads/terragarden1.png

The problem is that it throws an OAuthException: An unknown error has occurred. I don't quite know what to do with this kind of error.
Additional:
When I try to post image using the same code and just changing
$response = $facebook->api('/GROUP_ID/photos/','POST',$args);
into $response = $facebook->api('/me/photos/','POST',$args);, the image would successfully be posted on the user's wall. What might be the problem here?

A: This works fine for me on pages:
$attachements = array(
        'access_token' => $page->getToken(),
        'message' => $post_pub['title'],
        'url' => 'http://site.com/images/your_image.png' );
        try{
           $result = $facebook->api('/'.$page->getIdFacebook().'/photos', 'POST', $attachements, function(){
           });
        }
        catch(Exception $e){ }

Might want to try switching from 'image' to 'url'

A: I got the same issue.
There is a topic about it here: https://developers.facebook.com/bugs/1430985030446221?browse=external_tasks_search_results_527428908614f7c36099745
I've been tried to do this with js sdk, with the same error response.


text:
Q: How to rotate desktop background? How to rotate desktop background image in Ubuntu?

A: If you just want to rotate the background then you should open the image you are using for the background in an image editing application (like Pinta) and rotate it there. Save the updated image and use it for your background.


text:
Q: iPad Catelog Application I want to create an Ipad/iPhone app that will act as a catalog to allow users to select items and send request to the company to process

*

*User Downloads the App

*Login into the app

*Downloads the available Categories and Items ( Text details and 2 size of images)

*Should be able to browse offline

*While sending the request for the items needs to be online but can select the options offline.

*Should be able to upload an image/design to the order list and add remarks.

My Main question is - Can we download data from the server like images and cache in locally into the local database and directory ?

A: Yes.  You can save whatever info you want into a local sandboxed, file system.  http://developer.apple.com/library/mac/ipad/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/FileSystemOverview/FileSystemOverview.html
It looks like the PhoneGap Framework will also allow local storage.  See http://en.wikipedia.org/wiki/PhoneGap


text:
Q: Max memory allocation on AWS EBS I am using ElasticBeanstalk to host my Grails app.
As of now I am using m1.small instance which has 1.7 GiB of main Memory. My question is what is the MaxHeap and Max PermGen I can allocate to my instance? As of now my configuration looks like below
Initial JVM heap size: 512m
JVM command line options: -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled -XX:+UseConcMarkSweepGC
Maximum JVM heap size: 512m
Maximum JVM permanent generation size: 256m

Any suggestion for selecting the optimum numbers so that I can use max memory for my Tomcat and still have enough left for the OS itself?
Rephrasing the question what is the MAX out of 1.7 GiB can I allocate to something other than the OS(tomcat in this case)

A: You really need to profile your application stack.
It's easy to increase the size of the heap above the amount of physical memory by adding swap which increases Virtual memory.
For performance you want to find the right fit between instance and application.
Run your application stack in a vagrant instance first and measure it.  Adapt until
you get consistent performance, but m1.small instances may be slowed down by others on the same physical host.
That said, you can run top, and sort on Virtual memory.
Example: (Compare VIRT, RES, and SHR columns)
 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
1220 root      20   0  308m 1316  868 S  0.0  0.3   0:00.43 VBoxService
1126 root      20   0  243m 1576 1040 S  0.0  0.3   0:00.02 rsyslogd
1324 root      20   0  114m 1380  764 S  0.0  0.3   0:00.84 crond
1966 vagrant   20   0  105m 1880 1536 S  0.0  0.4   0:00.12 bash
1962 root      20   0 95788 3740 2832 S  0.0  0.7   0:00.18 sshd
1965 vagrant   20   0 95788 1748  836 S  0.0  0.3   0:00.11 sshd
1323 postfix   20   0 78868 3280 2448 S  0.0  0.7   0:00.00 qmgr
1322 postfix   20   0 78800 3232 2408 S  0.0  0.6   0:00.00 pickup
1314 root      20   0 78720 3252 2400 S  0.0  0.6   0:00.01 master
1238 root      20   0 64116 1180  512 S  0.0  0.2   0:00.80 sshd

This is on a rather small vagrant instance:
$ cat /proc/meminfo
MemTotal:         502412 kB
MemFree:          350976 kB
Buffers:           27148 kB
Cached:            45668 kB
SwapCached:            0 kB
Active:            45240 kB
Inactive:          39616 kB
Active(anon):      12164 kB
Inactive(anon):       44 kB
Active(file):      33076 kB
Inactive(file):    39572 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       1048568 kB
SwapFree:        1048568 kB
Dirty:                 4 kB
Writeback:             0 kB


text:
Q: What is the gcc equivilant for Xlc '-qthreaded' compiler option? I am currently porting my compiler from AIX XLC compiler to GCC compiler on AIX.
I want to know if there is an GCC equivalent compiler option available for the -qthreaded (XLC).

A: -pthread is the closest GCC option for use cases where -qthreaded is applied for XL; however, it is not equivalent to the -qthreaded option for IBM XL.
The GCC documentation for -pthread merely states that it sets macros (http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#index-pthread) and modifies the link step (http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html#index-pthread-1). -qthreaded does not cause _THREAD_SAFE to be defined as a macro, nor does it cause -lpthreads to be present in the link step. GCC's -pthread is more like XL's _r invocations (which does set the macro and modify the link step).
What -qthreaded does is to disable optimizations that are unsafe for multithreaded programs. It appears that, at least historically, -fno-tree-loop-if-convert-stores would at least partially be a GCC equivalent to -qthreaded.


text:
Q: Why does debug_backtrace not always return an "args" array? I am writing some custom template logic for WordPress (which isn't really relevant, just for context). WordPress has a function wp_debug_backtrace_summary which basically just summarizes information from the stack trace.
The issue is that I'm getting a warning based on the 'args' argument not always being defined. While this looks like this is a known WordPress bug (31215), what I don't understand is why args is sometimes not defined.
The issue only arrises when my custom logic which uses output buffering to pre-render some template parts before rendering the whole template.
The PHP docs seem to imply that the args parameter should always be defined, and I haven't been able to find a lot that speaks to this issue.
Any help from PHP experts would be appreciated.


text:
Q: How to install node modules to a folder outside the project folder? I am running a React project and npm install installs all of the modules in the root folder of the project, in which it creates around 30 000 new files, which then slows dows web cloud syncing (I am unable to exclude locations). How can I install this large directory at a different location, that is outside the project folder or maybe globally somehow?
I have tried npm install -g after deleting the node_modules folder, but that said that everything is up to date and npm list -g shows only one item, that is the project. After that running npm start does not work, gives error 'react-scripts' is not recognized as an internal or external command

A: Learn Next JS and try to make server side rendering


text:
Q: How to attach Connector after locking I created a small sample simulation with a custom gripper and "handle". To connect the gripper to the object I used the Connector. Locking seems to work. However, I can't get the object move together with the gripper after locking.
Any ideas on how to solve this?
Below is a picture of the simulation. To clarify what I mean, I want the can to move together with the robot gripper after locking the Connectors.

Update:
Here is the screenshot with Connector display enabled:

A: First, I strongly recommend enabling the connector axes visualization to better understand what is happening from the menu 'View / Optional Rendering / Show Connector Axes'
From your Connector definition they are several things to pay attention (https://cyberbotics.com/doc/reference/connector#field-summary):

*

*The 'type' field should be "active" for the robot and "passive" for the can.

*The 'model' field of both connectors should be the same.

*The 'unilateralLock' and 'unilateralUnlock' should probably be true in your case.

*It may also be convenient to set the 'snap' field to true.

Finally, you may also want to check this sample simulation using connectors too:
https://cyberbotics.com/doc/guide/samples-devices#connector-wbt


text:
Q: I want to perform a simple tensorial contraction I want to perform a simple tensorial contraction like, if KroneckerDelta[i, j] is contracted with some arbitrary tensor A_{lkj} (not-necessarily symmetric) it should give the answer as A_{lki}. Is their any way to do it?

A: The following code
tc[KroneckerDelta[i_, j_], A_[l_, k_, j_]] := A[l, k, i];

seems to do what you want. The expression
tc[KroneckerDelta[i, j], A[l, k, j]] == A[l, k, i]

evaluates to True as it seems you wanted. If this is not doing what you want, please give an actual example of the result you expect.


text:
Q: What can trigger postgresql shutdown? Today on one of my servers strange thing happened: postgresql turned off by itself.
I checked postrgesql logs (/var/log/postgresql/postgresql-9.5-main.log) and this is what I found:

2017-08-16 07:56:18 CEST [1601-2] LOG:  received fast shutdown request
2017-08-16 07:56:18 CEST [1601-3] LOG:  aborting any active transactions
2017-08-16 07:56:18 CEST [1606-2] LOG:  autovacuum launcher shutting down
2017-08-16 07:56:18 CEST [1603-1] LOG:  shutting down
2017-08-16 07:56:18 CEST [1603-2] LOG:  database system is shut down

Previous entries are from June, so they are irrelevant.
Nobody logged in to the machine for almost two weeks (according to the logs...).
Assuming that I'm not hacked what could trigger this shutdown request? What can I do to find out what happened?
I had to turn on postgres again because it's production machine, but I really want to know what had happened.
I have PostgreSQL 9.5.8 on Ubuntu 16.04.2.

A: There is a similar post on Database Administrators with an answer here: https://dba.stackexchange.com/questions/14199/postgresql-performed-a-fast-shutdown-by-itself-why-how-was-it-able-to-do-tha
Maybe this will help?