text:
Q: What is the simplest example of accessing Amazon Mechanical Turk? I am looking for a simple example of accessing the Amazon Mechanical Turk web service in C#. I know there is a SDK for C# but I want to understand the basic mechanics before using that.

A: Here is the simplest code example I've come up with to access Mechanical Turk. It creates the signature and calls the GetAccountBalance operation.
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace TurkTest {
    class Program {

        static void Main(string[] args) {
            const string SERVICE_NAME = "AWSMechanicalTurkRequester";  // requester service for MTurk
            const string TIMESTAMP_FORMAT = "yyyy-MM-ddTHH:mm:ss.fffZ";

            // Modify these with your values.
            const string operation = "GetAccountBalance";
            const string accessKey = "<Your access key>";
            const string secretAccessKey = "<Your secret access key>";

            // Millisecond values in the timestamp string can result in intermittent BadClaimsSupplied errors.
            // Get the current UTC time and use that to create a new time with milliseconds set to zero to avoid this case.
            DateTime now = DateTime.UtcNow;
            now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, 0, DateTimeKind.Utc);
            string timeStamp = now.ToString(TIMESTAMP_FORMAT, CultureInfo.InvariantCulture);

            // Create the hash-based messaged authentication algorithm (SHA1) using our secret access key as the key.
            var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secretAccessKey));

            // Combine the service name, operation and timestamp and then hash them to produce the signature.
            var dataBytes = Encoding.UTF8.GetBytes(SERVICE_NAME + operation + timeStamp);
            string signature = Convert.ToBase64String(hmac.ComputeHash(dataBytes));

            // Build the URL to send to Amazon
            string url =
                @"https://mechanicalturk.amazonaws.com/?Service=AWSMechanicalTurkRequester&AWSAccessKeyId={0}&Version=2012-03-25&Operation={1}&Signature={2}&Timestamp={3}";
            url = string.Format(url, accessKey, operation, signature, timeStamp);

            // Send a request and write the response to the console.
            using (WebClient client = new WebClient()) {
                using (StreamReader reader = new StreamReader(client.OpenRead(url))) {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }

            Console.Read();
        }
    }
}


text:
Q: what is the difference between lex and yacc I have worked with lex for executing some code whenever some regular expression is found,
Can Yacc do something more than that? If yes, then what?

A: Yes, YACC is a parser, Lex is a lexical analyzer. They are typically used together: you Lex the string input, and YACC the tokenized input provided by Lex.
Now, a regular expression can only represent regular languages. One of the constraints of a regular language is the lack of "memory". You cannot define the rules for acceptance further down the string based on what has come before.
This is mostly clearly seen in the case of parenthesis. A regular language can't match nested parenthesis to the correct level. Or any other such structure. The grammars of (most) computer languages can and do, and, because of that, they can't be be parsed with a Lexer or a regular expression. That's where YACC comes in.
One can reverse the question as well. If YACC can do more, why not use it for the lexical analysis? Well, it so happens that you can verify the validity of a regular expression very efficiently, which is not the case of general grammars -- not to the same level. Still, YACC can do basic lexical analysis, if the lexical rules of the language are simple enough.

A: lex and yacc are normally used together.  This is how you usually construct an application using both:

Input Stream (characters) -> Lex (tokens) -> Yacc (Abstract Syntax Tree) -> Your Applcation

More generally, what Lex will do is read a source file, from the beginning, and try to match a number of regular expressions (lex has its own, special syntax for this, which is a bit different from perl or sed regular expressions), and will then invoke another program with each token it recognizes.  Tokens may either just be a plain enumerated value, like for a key word or operator, or it might have some metadata attached, like for a literal value.
Lex is usually (though not neccesarily) used to invoke Yacc.  Yacc uses a LALR parser algorithm, which roughly speaking, works by pushing each token onto a stack.  If the stack has a sequence of tokens that it recognizes, it will pop all of the tokens, perform an action, and push another token back on the stack.
The proper vocabulary for what Yacc works on is actually terminals and non-terminals.  A terminal is a token that it got from the invoking program (usually Lex), and a non-terminal is the result of matching a sequence on its stack.
Usually the actions taken by each Yacc rule are either to evaluate the result of a calculation that the rule corresponds with, or to produce an intermediate representation, like a syntax tree, for another application layer to process.
Yacc, like lex, can be used separate from the other.  For instance, you could use Yacc by passing it individual characters from the source text, and use Yacc rules to recognize each kind of token.  However Yacc is not designed to be very easy to use that way, and so the resulting lexer will be much more complex than an equivalent lexer in Lex.  A more typical use would be to make a hand-coded lexer for reasons of either performance or because you need a smarter lexer.  A common example of the second case is as used in C-like languages that have to know about previous uses of identifiers to know if they are used to describe types or variables.

A: lex is a lexical analyzer. It splits text up into tokens. Its power is roughly equivalent to regular expression matching. yacc is a parser generator. It takes a sequence of tokens (say, from lex) and interprets them as series of statements. Its power is roughly equivalent to context free grammars.
A typical application of lex and yacc is for implementing programming languages. lex tokenizes the input, breaking it up into keywords, constants, punctuation, etc. yacc then implements the actual computer language; recognizing a for statement, for instance, or a function definition.
In a practical sense, you often use lex to process input text into chunks. Then you use yacc to string those chunks together and process them into some larger meaning.

A: lex is for tokenizing input.  That is, separating out your input into the lowest-level objects that your grammar defines.  For example, you use lex to identify keywords, identifiers, strings, comments, whitespace, and so on.
yacc is for parsing your grammar.  A grammar is a description of your language, typically defined in EBNF or some other context-free grammar.  Once you describe your grammar to yacc, you can use it to run the actions of your tool when elements of the language are recognized.  This might be, for example, constructing syntax trees for expression solving, defining scope objects, recording variable defintions, and so forth.
They are complimentary products.

A: Lex is a tool for building lexical analyzers, that can do some rather stupid lexical stuff (like finding keywords). Yacc is a parser generator, that can create parsers for real computer languages. Its analysis is normally based upon the output of lex (which is a stream of tokens) and from this can create your parse-tree of the programming language -- something that is more than lex does.
Traditionally, compiler builders distinguish between lexical and syntactical analysis -- which are two important steps in a compiler (further ones to follow eg. code creation, optimization).

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL server RUNNABLE process I've a process that is open since 2 days ago and is executing a select as last command, but this session got stuck in runnable status.
I checked inputbuffer several times and everytime it shows the same query
I will share you the result of sp_who2 and please note that last batch is for 2 days ago:

I checked query plan and didn't find any unusual things and it takes 1 second to show result but it's still in my active expensive query in activity monitor

other point is I ran profiler for this SPID since yesterday and here is the result :

this process lock some objects on my db and it blocks and rebuilding index on this tables

now what should I do ? should I kill it without finding root cause?
sp_WhoIsActive result

the result of EXEC sp_WhoIsActive @find_block_leaders = 1, @sort_order = '[blocked_session_count] DESC', @get_locks =1


text:
Q: Trigger Gradle Task after import Eclipse Project We ported our custom Gradle setup (GWT, builder configuration etc.) for Eclipse from the STS Gradle Plugin to the Buildship Plugin.
We use special self-developed tasks which are performed automatically after an import of a Gradle project through the STS plugin via the eclipse-task and afterEclipseImport-task. Does the new Buildship plugin allow to trigger tasks after the import in Eclipse in a similar manner?
Has anyone of you successfully triggered a Gradle task after project import with the Gradle Buildship plugin?

A: Better late than never: It has been introduced in Buildship 3.1 and requires Gradle 5.4 or above:
https://www.eclipse.org/community/eclipse_newsletter/2019/june/buildship.php
You can register tasks to be executed every time Eclipse is synchronizing the workspace with the working copy:
eclipse {
    synchronizationTasks myCustomSyncTask
}

And tasks to be executed every time Eclipse is performing a build:
eclipse {
    autoBuildTasks myCustomBuildTask
}


text:
Q: The observer call method returns null I am working in Restful android using square's retrofit REST Client Library. The problem that I have faced is when using Observable of retrofit it returns null in the Observer's call method. But when i call the API with callback it returns the data. The interface that i used is as follows:
@GET("/Contact/{Id}")
public Observable<Contact>(@Query("Id")String Id);

And in the main Activity i called this observable's object like this
APICall.GetSingleContact("5bc10c61-9dc8-4580-864f-e4b0bc05749a")
    .subscribe(new Action1<Contact>() {
         @Override
         public void call(Contact contact) {
             textView.setText(contact.FirstName);
         }
    });

any help please.

A: I think you should be using:
@GET("/Contact/{Id}")
public Observable(@Path("Id")String Id)
Instead of:
@GET("/Contact/{Id}")
public Observable(@Query("Id")String Id);

A: Finally, i have got the solution there was no problem in the observable there was in the json parsing.


text:
Q: How to show loader image when uploading file using codeigniter 3 file upload library I am trying to figure out a way using codeigniter file upload library.
View:
<?php echo form_open_multipart('welcome/staff_bulk_upload_process', ['role' => 'form']); ?>
    <fieldset>

            <img src="<?php echo base_url("assets/images/ajax-loader.gif"); ?>">

           Import Staff Data
           <input type="file" class="form-control" id="staff_file" name="staff_file" />

            <button type="submit" class="btn btn-default btn-block" id="importStaff">Upload File</button>

    </fieldset>
<?php echo form_close(); ?>

My objective is to toggle the hidden/show class of bootstrap. So that when the file upload is in progress it should display the image and when it is done, image should be hidden.
controller:
public function staff_bulk_upload_process()
    {
        $this->load->model('welcomemodel/welcome_model');
        $time = substr(time(), 5);
        $file_name = 'staff_bulk_upload_file' . $time . '.csv';
        $config['upload_path'] = './uploads/staff/add/';
        $config['allowed_types'] = 'csv';
        $config['max_size'] = 2048;
        $config['file_name'] = $file_name;

        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload('staff_file'))
        {
            $error = array('error' => $this->upload->display_errors());
            $this->session->set_flashdata('staff_import_message', '
'.$error['error'].'
');
        }

        redirect('welcome');
    }


text:
Q: If I have struct inside another struct and I am trying to have them inside an array I have a struct that is named item, now I have another struct that is called array that calls item. The struct item arrayofListis required to be of the size 5
#include <stdio.h>
#include <string.h>
#define MaxItems 5
#define NameLength 20
#define UnitLenght 6

struct item
{
    char name[NameLength];
    float amount;
    char unit[UnitLenght];
};
struct array
{
    struct item arrayofList;
};

int main(void)
{
    struct array shopping[MaxItems];

Am I giving the list size of 5 or am I doing it incorrectly

A: If you wanted struct array to contain an array of 5 LISTs, you would declare it as follows:
struct array
{
    struct LIST arrayofList[MaxItems];
};

and then just use it as
int main(void)
{
    struct array shopping;

But I will agree with the Jabberwock, currently this struct array is superfluous and you could achieve the same functionality by removing struct array altogether and using an array of LIST directly instead:
int main(void)
{
    struct LIST shopping[MaxItems];

Unless you intend on eventually adding more attributes to struct array, this would be simpler.

A: You probably want this:
#include <stdio.h>
#include <string.h>

#define MaxItems 5
#define NameLength 20
#define UnitLenght 6

struct item  // one item
{
    char name[NameLength];
    float amount;
    char unit[UnitLenght];
};

int main(void)
{
    struct item shopping[MaxItems];  // array of MaxItems struct items
    ...
}

A: Why you need the struct array? You can just write:
struct item shopping[MaxItems];


text:
Q: Do I need to enable DRS to use Dynacache in Websphere Application Server Cluster We are running a websphere commerce application with several websphere application servers configured in a cluster.
We are using dynacache, so each server in the cluster will have its own cached objects in its own JVM.  We are using CACHEIVL with database triggers for all cache invalidations.
I was reading http://www.ibm.com/developerworks/websphere/library/techarticles/0603_crick/0603_crick.html
and found an interesting sentence:
"Furthermore, cache replication is necessary to ensure that invalidation messages are shared between the servers in a cluster."
After thinking about this it would make sense that for the invalidation to work it would need to be triggered on all the servers in the cluster, but I couldn't find confirmation of this in the mountains of IBM doco.
Does anyone know if you can use trigger based cache invalidation (through CACHEIVL) when you have several application servers clustered each with their own cache without DRS turned on?  or do I need to use DRS for this to work?

A: There are 3 main techniques used to invalidate cache within WebSphere Commerce across a cluster:

*

*Let the cache entries expire after a configured time limit.

*Enable DRS so that one server may process the invalidation signals and propagate them to the other servers.

*Enable the cache invalidation scheduled job DynaCacheInvalidationCmd to run on each server of the cluster independently.

So, to answer your question : It is not mandatory to use DRS.
http://pic.dhe.ibm.com/infocenter/wchelp/v7r0m0/topic/com.ibm.commerce.admin.doc/tasks/tdcenabcdcinvalidtrigs.htm

A: Better question to ask IBM Software Support.    As far as I know, CACHEIVL does trigger the invalidation as you said but not exactly sure about DRS since I don't remember needing to configure that when setting up.


text:
Q: Show only one database on SQL Server I have a database server with several databases on it.  I'd like to create a login for one of these databases, but when the user logs in to the server, I don't want the other databases on the server to show up.  Is this possible?
I've created a login on the server and gave that login the db_readonly role on just one server.  However, when I connect via SQL Server Managment Studio, I see a list of all of the databases.  I can't see what tables are defined in each of them.
I want to remove this clutter so that when a user connects there is only one (or two if you include master) database available.

A: you may use the SSMS interface as following: -
1) Go to your SQL Server Instance, right click and select Properties.
 2) Choose Permission on the left pane.
 3) Select the specific user that you mention on the "Logins or roles" section.
 4) At the permissions for  section, check on Deny column for "View any database"
 5) Go to the newly added databases, right click and select Properties.
 6) Add the specific user under "Users or roles"
 7) At the permissions for  section, check on Grant column for "View database state" or any other permission that you would like to grant"


text: Q: AppStore frozen on Catalina 10.15.7 I just reformatted my SSD and reinstalled Catalina 10.15.7.  Everything appears to be fine, there are no updates available, but my AppStore is unresponsive.  It launches with a window, but the window remains black and the wait cursor appears.  My only option is to Force Quit.  How can I fix this issue?


text:
Q: How to make the table left-align with the header I made a page containing a header and a table here http://www.datanumen.com/outlook-repair/compare.htm
Now, I want the left border of the table align with the left border of the header image. How to do so?
Thanks

A: Try using the following CSS code:
table {
   margin:auto;
   width: 100px !important;
}


text:
Q: oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Invalid JWT I am using Google Cloud Vision API on my Raspberry PI. It works fine when I use it on my home (on which the cloud account was first accessed) network but if I access the API from a different network it raises a token refresh error. I have synchronized the time using NTP but is of no help.
Detailed error:

oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.

A:
invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe.

This is caused by poor synchronisation of the computer's clock where the code was executed that had a lag of 5 minutes or more.   The error means that the token is not valid and its not valid because the time on the PI is different then the actual time.  I know that you say you are checking NTP but I suggest you check timezone as well.
I know this is a PI so debugging is probably limited but try outputting your id token and decryption its a jwt you should be able to see the iat and exp values.  It might help you figure out what time it thinks it is.


text:
Q: Change keybinding to show Unity Sidebar I tend to use the Super key in my keybindings (e.g. move between workspaces, vim commands, etc.) and holding the super key shows the sidebar. It's really annoying especially if I'm on the maximised window.
Is there a way to change this binding so that holding super doesn't show the sidebar?
Thanks.

A: You should install CompizConfig Settings Manager with the command:
    sudo apt-get install compizconfig-settings-manager
Then, in Compiz, there is a Unity Plugin (look for the purple logo below). Under this section, it says "Key to show the luncher." Change it or disable it. Go nuts.


text:
Q: Trouble showing text over images in slick gallery I am having trouble adding text over multiple images in a "Slick" gallery. I can get the text that I want to show on the first image of the gallery but when adding the text to the other slides they only appear on the first slide.
I used the following css for the text overlay:
.classTextOver{
  position: absolute;
   font-size: 16px;
   color: white;
   top:60%;
  left:18%;
}

Any help would be appreciated.
You can find the code snippet here:
https://jsfiddle.net/dkxq3ztg/1/

A: This answer looks like it might create other issues for the slideshow, but if you use relative positioning, you can fix the text problem. Replace your .ClassTextOver with this:
.classTextOver {
position: relative;
top: 300px;
font-size: 40px;
color: white;
font-family: 'champion';
font-weight:normal;
left:100px;
}


text:
Q: Sharepoint Central Administration not running I am getting the following error when I try to browse either the Central Administration or the Web Application:-
Unable to connect to database.
Check database connection information and make sure the database server
is running

In the event log, I have the following error entry:
The description for Event ID ( 27745 ) in Source ( Windows SharePoint Services 3 ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: #50071: Unable to connect to the database SharePoint_AdminContent_a9991124-7852-4cc2-8a15-470a061b7a0d on svrhspuneet.  Check the database connection information and make sure that the database server is running..
Please help me resolve this.
Thanks

A: Hi Puneet try running the sharepoint configuration wizard again. your problem will get resolved.


text:
Q: Beginner Python user - need help iterating through a column in a MySQL db and store the values in a list The python code below connects to my database. What I'm trying to do is iterate through a column which contains integer values, and put all of those values into a list. I will need the values in the list because I want to normalise them between a range of 0 and 1.
import MySQLdb
import sys

db = MySQLdb.connect(host="****", user="****", passwd="****", db="****", port=3306)
cursor = db.cursor()
cursor.execute("SELECT columnName FROM TABLE5")

col1 = []
numrows = int(cursor.rowcount)
for x in range(0,numrows):
    row = cursor.fetchall()
    col1.append(row[x])
    print col1

cursor.close()
db.close()
sys.exit()

The above currently outputs the following:
[('67',)]
Traceback (most recent call last):
 File "miner.py", line 12, in <module>
  col1.append(row[x])
IndexError: tuple index out of range

If anyone could help that would be great!

A: cursor.execute("SELECT columnName FROM TABLE5")
col_names = [row[0] for row in cursor.fetchall()]

is probably what you want cursor.fechall() will return something like
[("ColName1",),("Colname2",),...]

so we just iterate over that list and take the first item from each tuple
you could also do something fancy like
col_names = list(itertools.chain.from_iterable(cursor.fetchall()))

but really the simple list comprehesion should be plenty sufficient

A: I think you're confused about the use of cursor.fetchall().  I'm guessing you think it will return all the columns for a single row.  But really it returns all the rows from the query you executed.
Therefore, you need to execute cursor.fetchall() only once, outside your loop.
Additionally, while your loop (or rather, something close to it) will work, it's unnecessarily complex and "un-Pythonic".  That's because the results of fetchall() (a list of all the rows) can be directly iterated over without worrying about the count.  It iteration will produce a single row object, which contains the columns you want.  So:
col1 = []
all_the_rows = cursor.fetchall()
for row in all_the_rows:
    # We want the first-and-only column value in the row
    col1.append(row[0])

 # Wait until we have all the values to print them.
print col1

You can simplify this further (Joran has an example above), but it may be best to start with a regular for-loop construction and move on to the advanced concepts once you have this nailed down.


text:
Q: FullCalendar - Calendar not showing (ASP.NET Core) I am a student who is trying to develop a scheduler for a certain project, but I cannot seem to get FullCalendar to work on my page. I tried using the page the guide helps you create, but that did not work, so now I am trying to use one of the demo pages provided in the FullCalendar folder that I downloaded.
I previously used VS 2015, but now switched over to VS 2017 Community but that didn't help either.
My page:
@{
ViewData["Title"] = "Schedule";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<meta charset='utf-8' />
<link href='~/fullcalendar/fullcalendar.min.css' rel='stylesheet' />
<link href='~/fullcalendar/fullcalendar.print.min.css' rel='stylesheet' media='print' />

Calendar

Thanks in advance to any helpers!
EDIT (April 26th):
I pressed F12 as suggested and saw that the console logs an error saying "Uncaught TypeError: $(...).fullCalendar is not a function".
I looked at some other posts that mentioned this issue but I could find no second mention of jquery and made sure the order of references was correct, which were the mentioned solutions in those situations.
Is there anything else that can be causing this?
EDIT (April 27th):
All files seem to be loading:
Loaded files in website

A: It looks like the layout page is calling the jquery file again, see this picture.
Try to remove one of them and make sure the jquery file is being called before the fullcalendar.js


text:
Q: Solution to one-dimensional Wave Equation with Method of Characteristics Consider the

Problem. Let $\gamma$ be a parameterized curve in $\mathbb{R}^{2}$ by $\gamma: I \to \Omega$, where $I$ is an interval of $\mathbb{R}$ and $\Omega$ an open in $\mathbb{R}^{2}$. Let $a,b,c: \Omega \to \mathbb{R}$ be given functions. Determine a function $\varphi(x,y)$ solution of the equation
  $$a(x,y)\frac{\partial \varphi}{\partial x} + b(x,y)\frac{\partial \varphi}{\partial y} = c(x,y) \tag{Eq 1}$$
  where $\varphi(\gamma(t)) = \varphi_{0}(t)$ with $\varphi_{0}: I \to \mathbb{R}$ is a given function.

Proof. (just a loosely idea) Fixed a point $\gamma_{0} = \gamma_{0}(s_{0}) = \gamma_{0}(x_{0},y_{0})$ of $\gamma$, consider the curve $\Gamma(t) = (x(t),y(t))$ passing through $\gamma_{0}$, that is, $\Gamma(0) = \gamma_{0}$. Define $z(t) = \varphi(x(t),y(t))$ where $\varphi$ is a solution of Eq 1. If $\Gamma$ is differentiable, by the Chain Rule,
$$\frac{dz}{dt} = \langle \Gamma'(t), \nabla\varphi(\Gamma(t)) \rangle = \frac{dx}{dt}\frac{d\varphi}{dx} + \frac{dy}{dt}\frac{d\varphi}{dy}.$$
Therefore, if $\Gamma$ satisfies the system of ODE
$$\begin{cases}
\frac{dx}{dt} = a(x,y),&x(0) = x_{0}\\
\frac{dy}{dt} = b(x,y),&y(0) = y_{0},
\end{cases}\tag{Sy 1}$$
we can the solution $\varphi$ solving
$$\frac{dz}{dt} = c(x,y),\quad z(0)=\varphi(s_{0}).$$
If we repeat the previous argument for all points $\gamma(s)$, $s \in I$, we obtain a family of curves on which the solution $\varphi$ can be determined.
The solutions of the Sy 1 define a change of variables, that is, a function
$$f: \mathbb{R}^{2} \to \mathbb{R}^{2}$$
$$(t,s) \mapsto (x,y)$$
and the Inverse Function Theorem ensures a solution if $(a,b)$ is transversal to curve $\gamma$ where $(a,b)$ represents $(x,y) \mapsto (a(x,y),b(x,y))$.

My objective is to apply the Method of Characteristics (the Problem) to solve the one-dimensional linear Wave Equation that is given by

$$\frac{\partial^{2} u}{\partial^{2} x} - c_{0}^{2}\frac{\partial^{2} u}{\partial^{2} y} = 0$$

and we write
$$\frac{\partial^{2} u}{\partial^{2} x} - c_{0}^{2}\frac{\partial^{2} u}{\partial^{2} y} = \left(\frac{\partial }{\partial x} + c_{0}\frac{\partial }{\partial y}\right)\left(\frac{\partial }{\partial x} - c_{0}\frac{\partial }{\partial y}\right)u = 0.$$
Let
$$\left(\frac{\partial }{\partial x} - c_{0}\frac{\partial }{\partial y}\right)u = v(x,y) = v.$$
Then it's enough to solve

$$\underbrace{\frac{\partial u}{\partial x} - c_{0}\frac{\partial u}{\partial y} = v}_{(1)}\quad\text{and}\quad\underbrace{\frac{\partial v}{\partial x} + c_{0}\frac{\partial v}{\partial y} = 0}_{(2)}$$

I broke the Wave Equation in (1) and (2) because the Problem is only for order $1$, since the partial  derivatives are of order $1$. Then I think that solving the two equations, I'll find a solution for Wave Equation. This is the way that I found to use the Problem.
Now, I want to use the Problem for solve (2) and so, use the solution for (2) to solve (1).
I couldn't apply the above problem to get a solution to the equations (1) and (2). Hans Lundmark gave me a good reference, but in it, the author does the construction with some different details and my professor wants me to use the problem, exactly as it is, to get the solution. I wish someone could help me with this.

A: I'm not sure I understand exactly what your specific problem is, but for a general description of the method of characteristics for the one-dimensional wave equation $$u_t+c(u)u_x=0$$ (which includes the linear case with $c(u)=c_0$ constant), I can recommend Chapter 2 of Whitham's Linear and Nonlinear Waves.

A: There is a mistake in the equation that you wrote :
$$\frac{\partial^{2} u}{\partial^{2} x} + c\frac{\partial^{2} u}{\partial^{2} y} = \left(\frac{\partial }{\partial x} + c\frac{\partial }{\partial y}\right)\left(\frac{\partial }{\partial x} - c\frac{\partial }{\partial y}\right)u = 0.$$
The correct equation is :
$$\frac{\partial^{2} u}{\partial^{2} x} - c^2\frac{\partial^{2} u}{\partial^{2} y} = \left(\frac{\partial }{\partial x} + c\frac{\partial }{\partial y}\right)\left(\frac{\partial }{\partial x} - c\frac{\partial }{\partial y}\right)u = 0.$$
And moreover it is true only if $c=$constant.
If $c=c(x,y)$ some terms with $\frac{\partial c}{\partial x}$ and $\frac{\partial c}{\partial y}$ would appear.
In the elementary case of $c=$constant one can separate
$$\frac{\partial }{\partial x} + c\frac{\partial }{\partial y}=0$$
and
$$\frac{\partial }{\partial x} - c\frac{\partial }{\partial y}=0$$
The method of characteristics leads to the solutions, respectively :
$$u_1(x,y)=f(y+cx)$$
and
$$u_2(x,y)=g(y-cx)$$
where $f$ and $g$ are independent arbitrary functions.
So, the general solution of $\frac{\partial^{2} u}{\partial^{2} x} - c^2\frac{\partial^{2} u}{\partial^{2} y} =0$ is :
$$u(x,y)=f(y+cx)+g(y-cx)$$
If the equation is $\frac{\partial^{2} u}{\partial^{2} x} + c\frac{\partial^{2} u}{\partial^{2} y} =0$, the general solution is :
$$u(x,y)=f(y+i\sqrt{c}\:x)+g(y-i\sqrt{c}\:x)$$
ADDITION after the discussion in the comments section :
Solving $\left(\frac{\partial }{\partial x} + c_{0}\frac{\partial }{\partial y}\right)u=0$
$$\begin{cases}
\frac{dx}{dt}=1\:,\quad x(0)=x_0 \quad\text{leads to}\quad x=t+x_0 \\
\frac{dy}{dt}=c_0\:,\quad y(0)=y_0 \quad\text{leads to}\quad y=c_0t+y_0 \\
\frac{du}{dt}=0\:,\quad u(0)=u_0 \quad\text{leads to}\quad u=u_0
\end{cases}$$
A first family of characteristic curves  comes from $x=t+x_0$ and $y=c_0t+y_0$ which are the parametric equation of $y=c_0(x-x_0)+y_0$
$$y-c_0x=c_1\quad\text{with}\quad c_1=y_0-c_0x_0.$$
A second family of characteristic curves comes from $\quad u=u_0=$constant$=c_2$
The general solution of the PDE $\left(\frac{\partial }{\partial x} + c_{0}\frac{\partial }{\partial y}\right)u=0$ expressed on the form of implicit equation is
$$F(c_1,c_2)=F(y-c_0x\:,\: u)=0$$
where $F$ is an arbitrary function of two variables.
Or, equivalently on explicit form :
$$u=g(y-c_0x)$$
where $g$ is an arbitrary function.


text:
Q: Invalid interval format exception in hsqldb but query works in Postgres I'm running a query in postgresql. It works fine in psql but for the purpose of unit testing I created a inmemory HSQLDB and executed the same query in it. But "Invalid interval format" exception is thrown.Since I'm new to hsqldb so I cant figure out the root cause of the problem.
QUERY:
INSERT INTO microbatch_redrive
SELECT mii.*,(to_char(CURRENT_TIMESTAMP ,'yyyy-mm-ddThh:mi:ss.msZ')) FROM
(SELECT * FROM
  ( SELECT mi.*,me.extractid FROM
    (SELECT * FROM microbatch_info WHERE
        ((numattempts<= ${maxNumOfAttempts})
        AND (starttime>= '${starttime}')
        AND (starttime<= '${endtime}')))
    AS mi LEFT OUTER JOIN microbatch_extract_info AS me ON mi.microbatchid = me.microbatchid)
    AS mime WHERE((mime.raverunstatus='SUCCEEDED' AND mime.extractid is null)
    OR (mime.starttime < to_char(CURRENT_TIMESTAMP,'yyyy-mm-ddThh:mi:ss.msZ') AND mime.raverunstatus='NOT_STARTED')
    OR (mime.raverunstatus = 'FAILED')
    OR (mime.raverunstatus='STARTED' AND mime.starttime< (to_char(CURRENT_TIMESTAMP - INTERVAL '1 hour' * ${extractTimeIntervalInHour},'yyyy-mm-ddThh:mi:ss.msZ')))
    )
) AS mii LEFT OUTER JOIN
(SELECT microbatchid FROM microbatch_redrive WHERE raverunstatus='REDRIVE_SUCCEEDED') AS mr ON mii.microbatchid=mr.microbatchid WHERE mr.microbatchid IS NULL;

ERROR:
 Caused by: org.hsqldb.HsqlException: data exception: invalid interval format
[junit]     at org.hsqldb.error.Error.error(Unknown Source)
[junit]     at org.hsqldb.error.Error.error(Unknown Source)
[junit]     at org.hsqldb.types.IntervalType.getIntervalType(Unknown Source)
[junit]     at org.hsqldb.ParserBase.readIntervalType(Unknown Source)
[junit]     at org.hsqldb.ParserBase.readDateTimeIntervalLiteral(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readSQLFunction(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readFunction(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readColumnOrFunctionExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowElementList(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowOrCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowValuePredicand(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadPredicateRightPart(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowElementList(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanPrimaryOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTestOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanFactorOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTermOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanPrimaryOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTestOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanFactorOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTermOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readWhereGroupHaving(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSubqueryTableBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSubqueryTableBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableSubqueryOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readTableOrSubquery(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableReference(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadFromClause(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDML.compileInsertStatement(Unknown Source)
[junit]     at org.hsqldb.ParserCommand.compilePart(Unknown Source)
[junit]     at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
[junit]     at org.hsqldb.Session.executeDirectStatement(Unknown Source)
[junit]     at org.hsqldb.Session.execute(Unknown Source)

Thanks in advance.

A: INTERVAL '1 hour' is a Postgres specific interval syntax.
In standard SQL you would need: INTERVAL '1' hour  which is also supported by HSQLDB (and Postgres if you need a statement that works with both products).
So the complete expression should be:
CURRENT_TIMESTAMP - INTERVAL '1' hour * ${extractTimeIntervalInHour}


text:
Q: android Interstitial ads & banner ads I want to use google ads for my project .
I can show banner and Interstitial ads base on document exist in developers google.
in this document use different id for testing banner and Interstitial ads.
I want to know , is it possible to get just one id for both banner & Interstitial ads?
are they same? or they are completely different .

A: Both are different ads and you can't use the same ID for both types of ads, For more details see this link


text:
Q: Basic Interface Explanation I feel like I should know this, but can't really explain it when asked.
I have a method:
public <T extends IByteConverter<T>> int write(T obj) throws IOException {
    byte[] byteArray = obj.toByteArray();
    raFile.write(byteArray);
    //keeps track of size of what was written
    return byteArray.length;
}

and my interface:
interface IByteConverter<T> {
    public byte[] toByteArray();
    public T fromByteArray(byte[] byteArray);
}

When I call obj.toByteArray(), How does my program know what to do? No where in my class do I actually implement the code in IByteConverter, but the program works just as expected. Is there a simple way to explain what is going on?

A: Let's make the thing easier to understand with another example : you define an interface Fruit, which has a method getColor(). The contract of this method is that it returns a color.
Based on this contract, you define a class that takes an array of Fruits, and counts the number of red ones.
You don't need any implementation for this method to compile, because you can be sure that the only thing that can be passed to this method is an array of objects, which are instances of a class that indeed implements the Fruit interface. In order for this method to be run, you'll need to define at least one class that implements the Fruit interface (like Apple for example), and to construct an array of objects of this class.
That's what polymorphism is all about: you can call a method of an object without knowing what its actual class is, provided it respects the contract of its interface.
Generics don't make this different. Since obj is of type T, and since T extends IByteConverter, you can call the toByteArray() method on obj.

A: This type of method <T extends IByteConverter<T>> gives possibility to know about internal methods of object T. This declaration obligates the caller to put paramaters that extends type IByteConverter so at least all methods from IByteConverter will be accessible inside this method.


text:
Q: Calling and json file and displaying it on html I want to display images from my json file on a html page and organise them into rows of 3 or 4. Below is an example of the layout I want my page but this is hard coded,I have included images because I have having difficulty pasting the code (I can put this on fiddler) don't mind some of the word under the pictures some p tags needed taken out:
HTML:

 class="bold">Iphone5s

Here is a snip from my json file:
json data
I am using this script to call the data although it has not been calling the json file:
the script
I have positioned the images when hard coding like this:
I have been at this for over a day and cannot get it to work, If anyone has any ideas on how to get this to work I would be very grateful.
Kind regards!

A: Please make sure that you are appending JSON data dynamically so please remove the HTML content, or only make a parent container who will hold all this Output data.Make a JSON file with the name 'iproducts.json' on the same path.
$.getJSON('iproducts.json',function(products){
        var output="

Product_id	Info	Imgpath	Price
";
$.each(products.appleitems,function(index,value){
 output+="
"  + value.Product_id + "			" + value.Information+"	"+"<img src ='images/" + value.Imgpath + ".jpg' alt='applepro' id='appleinf'" + value.Price +"	"
});

output+="

";
console.log("output =" + output);


text:
Q: Default Value in RecordField throws JavaScript error on execute Adding following Record Fields to the GridPanel Store makes the site throw a JavaScript Error  Uncaught SyntaxError: Unexpected identifier to the Chrome Console
<ext:RecordField Name="listname" AllowBlank="false" DefaultValue="Listname" />
<ext:RecordField Name="recipients" AllowBlank="false" DefaultValue="Listmembers" />
<ext:RecordField Name="usage" AllowBlank="true" />
<ext:RecordField Name="responsible" AllowBlank="false" DefaultValue="please add Responsible Person(s)/ Group(s)" />

Firebug console gives following error:
SyntaxError: missing } after property list
[Break On This Error]
...,name:"responsible",defaultValue:please add Responsible Person(s)/ Group(s)}]}),...
---------------------------------------------|
admin.aspx (line 16, col 60)

It looks as if the Default Value is not correctly quoted as String, how can I fix this?

A: It seems the default Value of a Record Field is generally supposed to be a javascript variable. double-quoting it defaultValue="'foo bar'" fixes the problem


text:
Q: Java memory leak and garbage collection, This question has baffled myself and my cohorts. In the program I had written I was experiencing a memory leak. The var Platform, was being reassigned each iterations to a new object. But for some reason the old platform objects where not being cleaned by the gc and after many iterations the heap overflows:
Some of you may realise this is a PSO algorithm. But for those who don't this function has to be evaluated 1000's of times, and basicplatform is an extremely data extensive object, so multiple instances would eventually give a memory overflow, just to give a little context.
Buggy code:
public class Fitness implements FitnessFunction{

protected Platform platform;

public Fitness(){

}

public Fitness(Platform platform) {
    this.platform = platform;
}

@Override
public double fitness(Particle p) {

    try {
        platform = new BasicPlatform("testData.csv");
    } catch (Exception e) {
        e.printStackTrace();
    }

    platform.startSimulation();
    double prof = platform.getFitness();
    v.clear();
    if(prof != 0)
    return -prof;
    return 0;
}

}

After being confused as to why there is leak, as surely there shoudln't be, my friend showed me this solution, which he used before in a similar situation:
public class TradingRuleFitness implements FitnessFunction{

protected Platform platform;

public Fitness(){

}

public Fitness(Platform platform) {
    this.platform = platform;
}

@Override
public double fitness(Particle p) {

    Vector<Platform> v = new Vector<Platform>();
    try {
        //platform = new BasicPlatform("testData.csv");
        v.add(new BasicPlatform("testData.csv"));
    } catch (Exception e) {
        e.printStackTrace();
    }

        double prof = v.get(0).getFitness;
        v.clear();
        if(prof != 0)
        return -prof;
        return 0;
    }

}

Nearly exactly the same but this time instead of re-assigning the var platform we create a new object inside a vector and delete it after I have finished with it.This method seems to force the gc into cleaning up.
The question is why does this vector method work but not the original which technically should and are there any cleaner solutions?
p.s I have cleaned up unnesscary bits of code, as the question is about the object creation and removal

A: In the first case, if your Fitness object si retained, so will your Platform object be retained as it a field.
In the second case, your Platform is held in a local variable and is discard when fitness returns.
It doesn't have to be a Vector, it could be a plain local variable.
Try removing the field in both examples and it should work either way.

A: Seems in the first example you also cleared the "unnesscary bits of code" for the vector itself :)
It'll be hard to give a correct answer like this...


text:
Q: Multivariate functions whose value is independent of the order of the arguments Let $r_1, r_2, \ldots, r_k$ be positive integers with or without repetition such that $1\le r_i \le n$ for $i = 1, 2, \ldots, k$. Let $f$ be a continuous multivariate function with the property that the value of $f(r_1, r_2, \ldots, r_k)$ is independent of the order the arguments $r_1, r_2, \ldots, r_k$. The trivial examples are:
$f(r_1, r_2, \ldots, r_k) = g(r_1) + g(r_2) + \ldots + g(r_k)$,
$f(r_1, r_2, \ldots, r_k) = g(r_1)g( r_2) \ldots g(r_k)$ and
$f(r_1, r_2, \ldots, r_k) = c$
where $g$ is a continuous univariate function and $c$ is a constant. I have two questions
Questions:

*

*Are there other non trivial examples of such functions?

*Are there infinitely many such non trivial functions $f$?

A: You could symmetrize an arbitrary function by averaging it over the symmetric group.
Explicitly: take your favourite function $h$ in $n$ variables, and set $f(r_1, ..., r_n) = \frac{1}{n!}\sum_{\sigma} h(r_{\sigma(1)}, ..., r_{\sigma(n)})$ where the sum is taken over all permutations $\sigma$ of the numbers $1,...,n$.
I'd love to hear of an example which isn't obtained by symmetrization!
edit: heh.  Any such example would be its own symmetrization.  So I guess in some sense this is a complete, if overly glib, answer.

A: I don't understand why you say that $f$ is continuous if its inputs are positive integers. Anyway, you can take any symmetric polynomial in the $g(r_i)$, e.g. $\sum_{i < j} g(r_i) g(r_j)$.

A: Another very famous class of multivariate functions that satisfies this permutation invariance is: Symmetric gauge functions, for example, all the vector $\ell_p$ norms; also in fact their quasi-norm cousins are symmetric.
It is not clear to me where does it matter that the inputs be positive integers.
For example, suppose $r_1,\ldots, r_n$ are $n$ indeterminate elements of some group (possibly non-abelian). Then, using the kind of symmetrization over $S_n$ (that B. Young mentions), we can obtain symmetric functions in an even more general setup.
P.S.: You might also enjoy looking at the book: Symmetric functions and Hall Polynomials by MacDonald.


text:
Q: Apple APNS unregistered token repeatedly While running some tests, APNS pushes do not deliver any messages but the
application:applicationdidRegisterForRemoteNotificationsWithDeviceToken: method returns the same device token. And the feedback service keeps unregistering that device token.
token: EF71199500531549811F0881D92347BB4ABC73AA34A92839478C6500ED003909  date: 2018-10-02 13:48:08 +0000
token: EF71199500531549811F0881D92347BB4ABC73AA34A92839478C6500ED003909  date: 2018-10-02 14:09:35 +0000
token: EF71199500531549811F0881D92347BB4ABC73AA34A92839478C6500ED003909  date: 2018-10-02 15:19:23 +0000
token: EF71199500531549811F0881D92347BB4ABC73AA34A92839478C6500ED003909  date: 2018-10-02 15:29:25 +0000

Has anyone come across this behaviour before? And have any idea what is causing this?
Note: this does not seem to be a common problem, but it did happen on a clients device, so is a bit irritating.
If it is relevant the push and feedback where with NWPusher, and the app itself was an ad-hoc app, installed over-the-air to an iOS 12, iPhone X.

A: My best guess as to what was causing this:
It seems that the feedback service will return the token multiple times if you keep sending pushes to a dead token.
And it is possible that the client did not accept notifications. In this situation iOS 12 (at least) does generate an initial device token. Not sure why, or if this has always been the case when no notifications are requested.
Then the design of the app meant that the original token, which was stored, was sent to our backend server on a login condition. making it look like it was being refresh.


text:
Q: Alternate Formulation of Kinetic Energy for Lagrangian So I have a question regarding this system:

It is supposed to be a simple model of an aircraft with the fuselage idealized as a concentrated mass $M_0$ and the wings modeled as rigid bars carrying weights at the end of mass $M$. The flexibility of the wings are modeled with springs with torsional stiffness $k_t$.
The fuselage is free to translate in the $x$ direction while the small mass rotates about the larger mass in the $\theta$ direction. One can derive the equations of motion of the system with Lagrange's equation with $x$ and $\theta$ as the generalized coordinates.
One way to derive the kinetic energy of the small mass ($K_m$) is to obtain the velocity of it ($\dot{x}_m$) as a function of the velocity of the larger mass ($\dot{x}$) and the angular velocity ($\dot{\theta}$).
$$ \dot{x}_m = \dot{x} + l\dot{\theta}\\
K_m = \frac{1}{2}M\dot{x}_m^2 = \frac{1}{2}M(\dot{x}^2 + 2l\dot{x}\dot{\theta} + l^2\dot{\theta}^2)
$$
However, if one were to use the definition of the kinetic energy of a rigid body $B$ rotating about a moving point $C$ in inertia frame $F$ (see note 1 below), which is:
$$ K_B = \frac{1}{2}m_B\dot{x}_C^2 + \frac{1}{2}I_B\dot{\theta}_B^2
$$
Applied to this question, the kinetic energy of the small mass is:
$$ K_m = \frac{1}{2}M\dot{x}^2 + \frac{1}{2}I_m\dot{\theta}^2 = \frac{1}{2}M\dot{x}^2 + \frac{1}{2}(Ml^2)\dot{\theta}^2 = \frac{1}{2}M(\dot{x}^2 + l^2\dot{\theta}^2)
$$
It seems that the kinetic energy derived by the 2 methods results in 2 different expressions. The correct answer provided by my school is the former. But what is missing in the second approach that leads to the difference?
Note 1: This definition comes from "Introduction to Structural Dynamics and Aeroelasticity" from Hodges and Pierce. The definition can also be commonly found in other physics textbooks like  "Introduction to Classical Mechanics" by D. Morin.

A: The inconsistency arises because the norm of the velocity vector is computed incorrectly.
The formula for the kinetic energy is $T=\frac{1}{2}m\cdot \overrightarrow{{v}}^2$.
Now for small values of $\theta$ the movement of the mass M is collinear with the direction of the x-axis.  In that case $\overrightarrow{v}=[v_x, v_y, v_z] = [\dot{x}+l\dot{\theta}, 0, 0]$ is a good approximation and the OP's first formula for $K_m$ is correct in that approximation.
For the second form of the OP's $K_m$ formula they add $\dot{x}$ and $l\dot{\theta}$ quadratically, which is correct only if the two respective vectors are orthogonal to each other.  For instance it would be approximately correct at $\theta\approx \pi/2$.
For the problem at hand, the first $K_m$ formula is correct.


text:
Q: How to handle system.exit in the cucumber test case newbie to cucumber and selenuim in java
I am calling a method in cucumber test case and there if it goes into the else part it would send a mail and exit from the system.when i am running this method with cucumber then it will send the mail and exit with test case.
How to resolve that
and after that by using selenium i want to open the browser and check the mailbox to check the mail has sent by the code or not.

A: You can use Runtime.getRuntime().addShutdownHook(hook);
When you invoke this method, the thread hook will be called whenever the VM wants to shutdown (including when a System.exit() is called). You can add all your validation in the hook thread.
Check the  Java Doc for more information about shutdown hook.

A: call the method (selenium)  before the exit
else{
    //code to send the mail
     seleniumMethod();
    System.exit();
 }
seleniumMethod(){

//check mail
    }


text:
Q: Find which interval row in a data frame that each element of a vector belongs in I have a vector of numeric elements, and a dataframe with two columns that define the start and end points of intervals. Each row in the dataframe is one interval. I want to find out which interval each element in the vector belongs to.
Here's some example data:
# Find which interval that each element of the vector belongs in

    library(tidyverse)
    elements <- c(0.1, 0.2, 0.5, 0.9, 1.1, 1.9, 2.1)

    intervals <-  frame_data(~phase, ~start, ~end,
                               "a",     0,     0.5,
                               "b",     1,     1.9,
                               "c",     2,     2.5)

The same example data for those who object to the tidyverse:
elements <- c(0.1, 0.2, 0.5, 0.9, 1.1, 1.9, 2.1)

intervals <- structure(list(phase = c("a", "b", "c"),
                            start = c(0, 1, 2),
                            end = c(0.5, 1.9, 2.5)),
                       .Names = c("phase", "start", "end"),
                       row.names = c(NA, -3L),
                       class = "data.frame")

Here's one way to do it:
    library(intrval)
    phases_for_elements <-
    map(elements, ~.x %[]% data.frame(intervals[, c('start', 'end')])) %>%
      map(., ~unlist(intervals[.x, 'phase']))

Here's the output:
    [[1]]
    phase
      "a"

    [[2]]
    phase
      "a"

    [[3]]
    phase
      "a"

    [[4]]
    character(0)

    [[5]]
    phase
      "b"

    [[6]]
    phase
      "b"

    [[7]]
    phase
      "c"

But I'm looking for a simpler method with less typing. I've seen findInterval in related questions, but I'm not sure how I can use it in this situation.

A: cut is possibly useful here.
out <- cut(elements, t(intervals[c("start","end")]))
levels(out)[c(FALSE,TRUE)]  <- NA
intervals$phase[out]
#[1] "a" "a" "a" NA  "b" "b" "c"

A: Inspired by @thelatemail's cut solution, here is one using findInterval which still requires a lot of typing:
out <- findInterval(elements, t(intervals[c("start","end")]), left.open = TRUE)
out[!(out %% 2)] <- NA
intervals$phase[out %/% 2L + 1L]
#[1] "a" "a" "a" NA  "b" "b" "c"

Caveat cut and findInterval have left-open intervals. Therefore, solutions using cut and findInterval are not equivalent to Ben's using intrval, David's non-equi join using data.table, and my other solution using foverlaps.

A: David Arenburg's mention of non-equi joins was very helpful for understanding what general kind of problem this is (thanks!). I can see now that it's not implemented for dplyr. Thanks to this answer, I see that there is a fuzzyjoin package that can do it in the same idiom. But it's barely any simpler than my map solution above (though more readable, in my view), and doesn't hold a candle to thelatemail's cut answer for brevity.
For my example above, the fuzzyjoin solution would be
library(fuzzyjoin)
library(tidyverse)

fuzzy_left_join(data.frame(elements), intervals,
                by = c("elements" = "start", "elements" = "end"),
                match_fun = list(`>=`, `<=`)) %>%
  distinct()

Which gives:
    elements phase start end
1      0.1     a     0   0.5
2      0.2     a     0   0.5
3      0.5     a     0   0.5
4      0.9  <NA>    NA    NA
5      1.1     b     1   1.9
6      1.9     b     1   1.9
7      2.1     c     2   2.5

A: Just lapply works:
l <- lapply(elements, function(x){
    intervals$phase[x >= intervals$start & x <= intervals$end]
})

str(l)
## List of 7
##  $ : chr "a"
##  $ : chr "a"
##  $ : chr "a"
##  $ : chr(0)
##  $ : chr "b"
##  $ : chr "b"
##  $ : chr "c"

or in purrr, if you purrrfurrr,
elements %>%
    map(~intervals$phase[.x >= intervals$start & .x <= intervals$end]) %>%
    # Clean up a bit. Shorter, but less readable: map_chr(~.x[1] %||% NA)
    map_chr(~ifelse(length(.x) == 0, NA, .x))
## [1] "a" "a" "a" NA  "b" "b" "c"

A: Here is kind of a "one-liner" which (mis-)uses foverlaps from the data.table package but David's non-equi join is still more concise:
library(data.table) #v1.10.0
foverlaps(data.table(start = elements, end = elements),
          setDT(intervals, key = c("start", "end")))
#   phase start end i.start i.end
#1:     a     0 0.5     0.1   0.1
#2:     a     0 0.5     0.2   0.2
#3:     a     0 0.5     0.5   0.5
#4:    NA    NA  NA     0.9   0.9
#5:     b     1 1.9     1.1   1.1
#6:     b     1 1.9     1.9   1.9
#7:     c     2 2.5     2.1   2.1

A: For completion sake, here is another way, using the intervals package:
library(tidyverse)
elements <- c(0.1, 0.2, 0.5, 0.9, 1.1, 1.9, 2.1)

intervalsDF <-
  frame_data(  ~phase, ~start, ~end,
               "a",     0,      0.5,
               "b",     1,      1.9,
               "c",     2,      2.5
  )

library(intervals)
library(rlist)

interval_overlap(
  Intervals(intervalsDF %>% select(-phase) %>% as.matrix, closed = c(TRUE, TRUE)),
  Intervals(data_frame(start = elements, end = elements), closed = c(TRUE, TRUE))
) %>%
  list.map(data_frame(interval_index = .i, element_index = .)) %>%
  do.call(what = bind_rows)

# A tibble: 6 × 2
#  interval_index element_index
#           <int>         <int>
#1              1             1
#2              1             2
#3              1             3
#4              2             5
#5              2             6
#6              3             7

A: Here's a possible solution using the new "non-equi" joins in data.table (v>=1.9.8). While I doubt you'll like the syntax, it should be very efficient soluion.
Also, regarding findInterval, this function assumes continuity in your intervals, while this isn't the case here, so I doubt there is a straightforward solution using it.
library(data.table) #v1.10.0
setDT(intervals)[data.table(elements), on = .(start <= elements, end >= elements)]
#    phase start end
# 1:     a   0.1 0.1
# 2:     a   0.2 0.2
# 3:     a   0.5 0.5
# 4:    NA   0.9 0.9
# 5:     b   1.1 1.1
# 6:     b   1.9 1.9
# 7:     c   2.1 2.1

Regarding the above code, I find it pretty self-explanatory: Join intervals and elements by the condition specified in the on operator. That's pretty much it.
There is a certain caveat here though, start, end and elements should be all of the same type, so if one of them is integer, it should be converted to numeric first.


text:
Q: "non-fast-forward updates were rejected" when trying to push remote branch I have a remote project in projects/my_project
in my local host i'm in my_project
when trying to push my changes using git push origin master
this error appears to me
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.
i need to push to my_project not projects .

A: You have upstream changes. You have two options:

*

*Execute git pull origin master, resolve any conflicts, and then re-push

*Execute git push -f origin master. This will totally overwrite the history in your remote repository, so DO NOT do this unless you're absolutely sure.

A: You should not specify "master" unless you are trying to push to the remote master branch;
Try:
git push --set-upstream projects my_project
This makes the assumption that when you say "projects/my_project" you are referring to
a branch called "my_project" on the remote called "projects".
The --set-upstream set up you current "my_project" branch to track the remote "projects/my_project" branch so you don't need to specify it explicitly every time.

A: In my experience, this problem happens because there are changes on the server that you have not pulled to your machine yet. Try doing a pull, fixing any conflicts (if any), and then committing and pushing again.
I would also recomend using something like SourceTree if you are new to git.
Here's the link: http://www.sourcetreeapp.com/
Cheers,


text:
Q: create symlink in electron app my app is based on drag and drop functionality so I can't start electron as admin to use fs.symlin() because d&g will get disabled when your app is running as admin on windows os
I'm trying to create symlink in ipcmain of electron
fs.linkSync(app.path,destination)

A: so turns out d&d won't work in admin mode because of diffrences between two context, it is better to handle symlink creation in background, oh anyways i didn't reach any solution , there are some libraries like sudo-electron but when i want to create more than 1 symlink user will propmt like 10 times which is frustrating


text:
Q: RedirectToAction with Parameters? I am trying to call action from another action by passing parameter values. Url is adding /category?id=1, but I was expecting /category/1. Don't know why it is sending with ?id=.
edit:
 return RedirectToAction(actionName: "Index", controllerName: "Category",
                routeValues: new {id=id});

    [HttpGet]
    [Route("Admin/Category/{langID:int=0}")]
    public ActionResult Index(int langId)
    {
       --
    }

after redirection url is Admin/Category?id=1
MapRoute
routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "AdminPages",
            url: "Admin/{controller}/{action}/{id}",
            defaults: new { controller = "Category", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "CategoryEdit",
            url:"Admin/{controller}/{action}/{id}",
            defaults: new { controller = "Category", action = "Index", id = UrlParameter.Optional });

A: change your routeValues to routeValues: new { langId = id}; to match your action signature


text:
Q: Mysql datetime different in Javascript I post here today because I encounter a problem storing a Datetime in mysql with Javascript. The datetime I store, and I can see in Phpmyadmin is not the same as the datetime I got with a query (Select)
I think this is a timezone related problem, but I don't know how to solve this. I tried to save time in UTC with
UTC_TIMESTAMP()

But I still don't get the right datetime.
I store the datetime with :
connection.query("UPDATE `users` SET `last_disconnect` = now() WHERE `users`.`uuid` = ?", [userId])

(I tried to create a new Javascript date and store it but it's the same)
Here is the datetime stored (the datetime I can see in Phpmyadmin) :
2019-06-04 21:19:39

Here is my query :
connection.query("SELECT last_disconnect FROM users WHERE uuid=?", [userId])

Here is what I got with the query :
2019-06-04T20:19:39.000Z

Here is what I got when I create a new date with this :
console.log(new Date(dateFromRequest))

->
Tue Jun 04 2019 22:19:39 GMT+0200 (heure d'été d'Europe centrale)

The datetime I want to get in Javascript is the datetime stored in Mysql :
2019-06-04 21:19:39

My time zone is GMT +2
When I check the datetime in Mysql it says Timezone +0200
Does someone know what is wrong with what I am doing ?
Thank you in advance !

A: mysqljs - Connection options#dateStrings

Execute query without dateStrings
connection.query('SELECT * FROM user', function (error, results, fields) {
    if (error) throw error;
    console.log(results[0].registerDate)
});

Output
_> node index.js
2018-06-04T20:13:17.000Z

Execute same query but with dateStrings
const connection = mysql.createConnection({
    user: 'root',
    password: '1234',
    database: 'test',
    dateStrings: true // yo, im here
});

Output
_> node index.js
2018-06-04 23:13:17

Simple example
connection.query('SELECT * FROM user', function (error, results, fields) {
    if (error) throw error;
    results.map(x => {
        const date = new Date(x.registerDate);
        console.log(date.getFullYear())
    })
});

Output
_> node index.js
2018


text:
Q: How do I change system-wide font settings in Kubuntu? How do I change the font/size for the icon captions, Dolphin text, and window decoration text?  They all went from 12 point to 10 point after I installed KDE updates on Kubuntu 12.04.

A: KDE System Settings
KDE System Settings > Application Appearance > Fonts

KDE UserBase: http://userbase.kde.org/System_Settings/Application_Appearance
Might also interest:

*

*Font setting reset after restart in kubuntu 12.04

*How to launch Configure Kde control module by command line?


text:
Q: PDF's page layout and dimensions not good for printing So now that I have a 600+ page PDF (book) on my hands, I'd like to get a print out of it -- never thought I would. Turns out that the PDF's page formatting is not right for the print-on-demand service I plan on using (Lulu).
This question has been asked before, here in particular: Does \documentclass{book} by default take care of gutter for inner side of page?
I've attempted to implement the solutions offered, but neither of them have worked. For instance, below is the clean original layout (see code below for its dimensions):

And here's the adversely impacted layout once I've applied the solutions mentioned here and here.

Obviously, I'd rather not go over laying out the whole document again.
What options do I have, considering that, for hardbacks, Lulu requests the following dimensions:
Live Area (the page as it appears in the PDF): 190.5mm x 266.7mm
Trim Area: 212.7mm x 279.4mm
Document Size: 231.8mm x 317.5mm
Thank you.
See below for my PDF's dimensions:
\documentclass[oneside,centered,twocolumn]{book}
%\usepackage[T1]{fontenc}
\special{papersize=190.5mm,266.7mm}
\usepackage[left=12.7mm,right=12.7mm]{geometry}

\usepackage{blindtext}

\begin{document}
\tableofcontents
\blinddocument
\end{document}

A: Here's the code I've come up with to give my document the layout Lulu requires for their POD hardbacks. As suggested, it's then "simply" a question of going through the entirety of the book, page by page, and check that all the elements that make up the document look fine.
\documentclass[twocolumn]{book}
%\usepackage{showframe}
\usepackage{blindtext}
\usepackage{fontspec}
\setmainfont{TeX Gyre Pagella}
\linespread{1.05}

\usepackage{geometry}
\geometry{
    paperwidth=212.7mm, paperheight=279.4mm,
    tmargin  =30mm,
    bmargin  =30mm,
    lmargin  =35mm,
    rmargin  =25mm,
    headsep  =0.5cm,
    footskip =0.5cm,
    columnsep=.3cm,
    headheight=.5cm
}

\begin{document}
\tableofcontents
\blinddocument
\end{document}


text:
Q: Customize Passport Queries time of authenticating For every request I found that 4 queries are fired to validate the user and the token. Among them one is to fetch the user (select * from user) based on the user id. This queries are fired by Passport/Laravel But what I want is to modify this query to add one status field check also to check if any user become invalid during the token validity period. If we only check with the id then if any user become inactive(By changing status then also we will not be able to stop the user as deleting the token for the user is not a good solution for me).
Queries Fired on every request by Passport Laravel:
select * from oauth_access_tokens where id = ?
select * from user where id = ? limit 1 ["2"]
select * from oauth_access_tokens where id = ?
select * from oauth_clients where id = ?

So, can anyone tell me how to change the 'select * from user where id' query in passport at time of Token validation.

A: You can add this method on your User model (or any model you're authenticating with passport)
    ...
    public function findForPassport($username)
    {
        return $user = (new self)->where('email', $username)->where('is_active', 1)->first();
    }
    ...

of course you can modify is_active by whichever column you are using (and/or any query constraint for that matter), as long as it returns Illuminate\Contracts\Auth\Authenticatable contract.

A: I wouldn't try and modify passports default behaviour as I have no idea what else it might impact both now and in future upgrades.
Your best bet might be to hook into the passport events and apply you business logic to a listener that is called when the events are fired


text:
Q: Python platform settings in NetBeans don't work I am trying to use Netbeans 8.1 on OSX 10.9 for my first Python project an got a similar problem as import argparse fails, some setup/path issue?. I get this ImportError when trying to import any libraries:
File ".../hello.py", line 2, in <module>
    from flask import Flask
ImportError: No module named flask

The same classic program can be run in command window by python hello.py or python3 hello.py.
I added import sys; print "\n".join(sys.path) command in the beginning of my program to see the path. It shows, that NetBeans 8.1 doesn't follow the platform and path selections from Tools > Python Platforms.
I changed Python 2.7.10 or Python 3.5 as the selected (and default) platform, but the sys.path is always the same which refers to python2.7. That is always different from the ones defined in Python Path tab. (Restarting IDE did not help.)
I need to change the active path, what can I do?

A: The project platform must be set in Project properties window. The Python Platform Manager settings do not affect to any existing projects!


text:
Q: iframe blocked as insecure content, even though the iframe is HTTPS I am trying to embed an iframe (containing shellinabox, if that's relevant) onto an HTTPS webpage. The HTML I'm using to embed the iframe is pretty straightforward:

However, Chrome blocks the iframe from loading because it is "insecure content," and I have to manually unblock it for it to work. The Chrome console reports an error like this:
Mixed Content: The page at 'https://example.com/mainpage/' was loaded over HTTPS, but requested an insecure resource 'http://example.com/shellinabox/'. This request has been blocked; the content must be served over HTTPS.

I am confused by this because clearly my HTML code is embedding the HTTPS version of example.com/shellinabox. Moreover, when I visit https://example.com/shellinabox directly, the lock icon is green, nothing is blocked, and there are no indications of any SSL problems on that page.
I also tested this in Firefox, IE, and MS edge, and they all have the same behavior (so it's not a Chrome-specific issue). What gives?

A: This is an old question but I encountered the same issue. My use case is slighty different to yours, but hopefully this helps.
For me, my route on my python flask server ended with the "/" character. In my iframe, I was calling the route without the slash at the end of the src and was seeing the same error. Adding a slash to the src in the iframe did the trick for me.

I'm not exactly sure why the missing slash on the end the src attribute would cause this error. If anyone can explain why, I'll gladly update my answer.

A: your code is loading the page over https but that page is then probably trying to load additional scripts or assets over http. or it may have scripts in the page that are making ajax requests over http. youll have to examine the page and look in the developer console to see exactly what the insecure requests are. it's probably not an issue with how you are creating the iframe element.


text:
Q: Is there a way to apply a single gradient across game objects in Unity? Part 1: Forgive me if the question itself is unclear. I am learning how to use Unity and script in C#, and I want to know if there's a way to apply a gradient of color (or an image) utilizing the game objects that already exist as the places where the gradient will show up.
Say I have a group of these circles that randomly grow and change size during the game run.
Example image of circles
I am not sure of the correct terminology, but a couple of words come to mind, i.e. shader/mask. My goal is to display the gradient/image only within where the game objects exist. So instead of white circles, it's circles display parts of the one singular image/gradient.
Part 2:
To take a it a step further, I'd like to know how to have the gradient continuously run through its spectrum so one can see the colors shift across the circles.
Again, still very new to this kind of stuff, but would anyone know what steps I would need to take to get there.
Thanks!


text:
Q: Having troubles with react-semantic-ui and router so heres the sample:
simple menu/header JSX:
<Menu fixed='top' inverted>
    <Container>
        <Menu.Item header>Simple Blog</Menu.Item>

        <Menu.Item name='home' as={Link} to='/'
                   active={this.state.activeItem === 'home'}
                   onClick={this.handleItemClick}>Home</Menu.Item>

        <Menu.Item name='create-p' as={Link} to='/create-post'
                   active={this.state.activeItem === 'create-p'}
                   onClick={this.handleItemClick}>Create post</Menu.Item>
    </Container>
</Menu>

then I have basic index.js:
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>

    <BrowserRouter>

            <ApplicationMenu/>
            <Container style={{marginTop: '5em'}}>
                <Route exact path="/" component={Posts}/>
                <Route exact path="/home" component={CreatePost}/>
            </Container>

    </BrowserRouter>
</Provider>
, document.querySelector('.start'));

It renders and looks fine. When I click one of menu items I can see the URL changing, but no action is taken besides that. Router does not render new component. If I select the changed URL and click enter, it renders the proper one, but it looks like it does not react on url changes provoked by semantic ui component.
For debug purposes I prototyped these menu items just using clean html and css (pure sui, not react one) and it worked.
Did anyone have have similar problems and managed to figure it out?
Thanks for any answer.

A: This is a common problem to react-router-dom.
React works the way that it rerenders everytime either:

*

*the properties of a component change

*the internal state changes

If you change the URL of the page, you do not trigger a rerender of that component. Therefore, your index.js won't be rerendered.
A simple solution to this problem is to wrap your Component with a withRouter.
So your new index should look like this:
import { withRouter } from 'react-router-dom';

ReactDOM.render(withRouter(
<Provider store={createStoreWithMiddleware(reducers)}>

    <BrowserRouter>

            <ApplicationMenu/>
            <Container style={{marginTop: '5em'}}>
                <Route exact path="/" component={Posts}/>
                <Route exact path="/home" component={CreatePost}/>
            </Container>

    </BrowserRouter>
</Provider>)
, document.querySelector('.start'));

Now when the URL changes, the higher order component "withRouter" notices it and rerenders the component in it, so your correct component will be rendered.
As documented here: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md
If you want to know more about the problem, read this GitHub issue: https://github.com/ReactTraining/react-router/issues/5037

A: Your Route path don't match your Item Link to.
Try changing your routes to:
<Switch>
 <Redirect exact path="/" to="/home">
 <Route exact path="/home/" component={Posts}/>
 <Route exact path="/create-post/" component={CreatePost}/>
</Switch>

BTW: Take a look at react-router's <NavLink> to use instead of <Link> for your Navbar items.


text:
Q: Retrieve variable from WiX during CustomAction I am trying to retrieve a variable from WiX during an install. Here is the tests I have tried:
try
{
    string reqid = session["REQUESTID"];
    TraceLog.LogMessage("CustomAction => ReportUpgradeStatus: Straight Session is valid");
}
catch
{
    TraceLog.LogMessage("CustomAction => ReportUpgradeStatus: Straight Session is invalid");
}
try
{
    string reqid = session.CustomActionData["REQUESTID"];
    TraceLog.LogMessage("CustomAction => ReportUpgradeStatus: CustomActionData is valid");
}
catch
{
    TraceLog.LogMessage("CustomAction => ReportUpgradeStatus: CustomActionData is invalid");
}
try
{
    string reqid = session.GetProductProperty("REQUESTID");
    TraceLog.LogMessage("CustomAction => ReportUpgradeStatus: GetProductProperty is valid");
}
catch
{
    TraceLog.LogMessage("CustomAction => ReportUpgradeStatus: GetProductProperty is invalid");
}

I have some xml in Product.wxs as such:
<InstallExecuteSequence>
  <Custom Action="SetRequestIdProp" Before="InstallFiles" />
  <Custom Action="ReportUpgradeStatusMVACA" After="SetRequestIdProp" />
  <ScheduleReboot After="InstallFinalize"/>
</InstallExecuteSequence>

<Fragment>
  <Binary Id="CustomActionBinary" SourceFile="..\..\..\Bin\$(var.Configuration)\InstallationCA.CA.dll"/>
  <Property Id="REQUESTID" Value="[REQUESTID]" />
  <CustomAction Id="SetRequestIdProp" Property="REQUESTID" Value="[REQUESTID]" />
  <CustomAction Id="ReportUpgradeStatusMVACA"
              BinaryKey="CustomActionBinary"
              DllEntry="ReportUpgradeStatusMVA"
              Execute="commit"
              Return="check" />
</Fragment>

How can I access the RequestID property? I seriously am at a loss here as I everything I try to make that value appear does nothing.
Any advice at all would be welcome.
EDIT: Problem resolved. Here is what I needed to do:
I changed my CustomAction to:
<CustomAction Id="SetRequestIdProp"
              Property="ReportUpgradeStatusMVACA"
              Value="REQUESTID=[REQUESTID];APPLIANCEID=[APPLIANCEID];SERVICEURL=[SERVICEURL];STATUSDIR=[STATUSDIR];AUTOUPDATE=[AUTOUPDATE]" />
<CustomAction Id="ReportUpgradeStatusMVACA"
              BinaryKey="CustomActionBinary"
              DllEntry="ReportUpgradeStatusMVA"
              Execute="deferred"
              Return="check"
              HideTarget="no" />

And my InstallExecuteSequence to:
<Custom Action="SetRequestIdProp" Before="ReportUpgradeStatusMVACA" />
<Custom Action="ReportUpgradeStatusMVACA" Before="InstallFinalize" />

I got the info using:
RequestId = Int32.Parse(session.CustomActionData["REQUESTID"]),
ApplianceId = Int32.Parse(session.CustomActionData["APPLIANCEID"]),
ServiceUrl = session.CustomActionData["SERVICEURL"],

Thanks for the help.

A: Your custom action is a commit custom action (and I wonder why - it's unusual). That means it is also deferred, so you need to pass data via CustomActionData, and this seems to be a good explanation:
How to pass CustomActionData to a CustomAction using WiX?


text:
Q: AsseticBundle / CompassFilter: Any way to throw an exception when a template can't compile? I'm wondering if anyone can help me with some AsseticBundle configuration in conjunction with Symfony 2's dev environment.
Each time a page loads in the dev environment Assetic will recompile any assets, in my case I am compiling Sass files using the CompassFilter.
My problem is that when I have a malformed Sass file my page simply loads without any generated stylesheet - instead I want Assetic to show me the Compass/Sass compiler output as if an exception had occurred (i.e. I get the Symfony2 "oops" screen).
Does anyone know if there is a configuration to achieve this?
My current config.yml is:
assetic:
    debug:          %kernel.debug%
    use_controller: false
    sass: /var/lib/gems/1.8/bin/sass
    filters:
        compass:
          bin: /var/lib/gems/1.8/bin/compass
          apply_to: "\.scss$"
        scss: ~

with config_dev.yml overriding only one line to:
assetic:
    use_controller: true

A: No, what you ask for is not supported because the stylesheet is processed when it is requested, not when the HTML is requested. However, you should be able to see the error if you request the referenced stylesheet directly.


text:
Q: doctrine2 flush() silently crashes for no apparent reason I'm writing a converter that takes a document from database (mongo db), does some magic with its fields and writes it back. Repeat for all relevant docs.
The problem is, after successful processing EntityManager#flush() just silently crashes not committing any changes to db or returning an error code.
I encountered this crash before but I've been able to evade it by reducing quantity of entities to flush(). Now it won't work even with one.
The code goes like this:
public function convertTagsAction() {

$result = [];
$result['docs processed'] = 0;
$result['tags added'] = 0;
$repo = $this->getRepo('Portal');
$cnt = 0;
$dm = $this->getDM();

$docs = $repo->findBy([...]);

$result['docs to process'] = count($docs);

foreach($docs as $doc) {

....//executing just for ONE doc at the moment

  $result['docs processed']++;

  //file_put_contents('1.txt', print_r($doc, true));
  //Everything is ok in the file

  $dm->persist($doc);
  echo $dm->getUnitOfWork()->size();
  // returns 6087 which I deem strange

  //this helped me before to manage this problem
  $cnt++;
  if ($cnt >= 20) {
    $dm->flush();
    $cnt = 0;
  }
}
try {
  $dm->flush();
} catch (Exception $e) {
  echo $e->getMessage(); //Nah, won't tell me anything
}
return $this->success($result);
}

So now, whenever flush() is called, the script just quits and not even returns any output (should do so in the last line). Any ideas how to solve it?


text:
Q: how to find key from any array php I have a string, I need to know at what index is that string exist in the array. My array is as follows:
array(3)
{
    [0]=>object(stdClass)#47170 (3)
    {
        ["countries"]=>string(2) "HK"
        ["last_seen_date"]=>string(10) "2016-09-17"
        ["ad_uid"]=>string(14) "157d5908a1ca83"
    }
    [1]=>object(stdClass)#47171 (3)
    {
        ["countries"]=>string(2) "HK"
        ["last_seen_date"]=>string(10) "2016-09-27"
        ["ad_uid"]=>string(14) "157d7978513bc3"
    }
    [2]=>object(stdClass)#47230 (3)
    {
        ["countries"]=>string(2) "HK"
        ["last_seen_date"]=>string(10) "2016-09-27"
        ["ad_uid"]=>string(14) "157ea7239824e9"
    }
}

The last seen date is:2016-09-27.
I would like to know at what index does 2016-09-27 exist in the array. So I know what is ad_uid related to that date. I have a method which does this.
 public function getAd_uid($last_seen_date,$values){
 $key = array_keys($values,$last_seen_date);
 print_r($key);
 }

The result gets an empty array. I have tried array_serach() has same empty results. Any other alternative solutions to achieve results?

A: To find all $ad_uids last_seen at particular date you can use array_filter which will return you all elements you are looking for. If you need ad_uids only, you can apply array_map to that array as following:
<?php
// $array is the array in question.

$filtered = array_filter($array, function($item) {
    return $item->last_seen_date == "2016-09-27";
});

$ad_uids = array_map(function($item){return $item->ad_uid;}, $filtered);

Example

A: As each each entry of your array is an object and you know the attributs' names of theses objects (I assume they never change), I would do it like this :
/**
 * @param   string  $last_seen_date
 * @param   array   $values
 * @return  mixed   null|int
 */
function getAdUid($last_seen_date, array $values) {
    // Just in case no entry match
    $matching_index = null;
    // Loop through each entry: $entry is an object
    foreach($values as $index => $entry) {
        if($entry->last_seen_date == $last_seen_date) {
            $matching_index = $index;
            break; // end loop: we found that we are looking for
        }
    }

    return $matching_index;
}

A: to do that just loop your array
foreach($values as $key => $row) {
    // do something
}

then check if $last_seen_date is equal to the loop index last_seen_date $row->last_seen_date
if ($row->last_seen_date == $last_seen_date) {
   return $key;
}

if it is just return it
return $key;

so your php code would be like this
$arr = array(
    0 =>
        (object)array(
        "countries" => "HK",
        "last_seen_date" => "2016-09-17",
        "ad_uid"=> "157d5908a1ca83"
    ),
    1 =>
        (object)array(
        "countries" => "HK",
        "last_seen_date" => "2016-09-20",
        "ad_uid" => "157d7978513bc3"
    ),
    2 =>
        (object)array(
        "countries" => "HK",
        "last_seen_date" => "2016-09-26",
        "ad_uid" => "157ea7239824e9"
    )
);
function getAd_uid($last_seen_date, $values){
    foreach($values as $key => $row) {
        if ($row->last_seen_date == $last_seen_date) {
           return $key;
        }
    }
}

echo '2016-09-17 is on index => '.getAd_uid('2016-09-17', $arr).'
';
echo '2016-09-20 is on index => '.getAd_uid('2016-09-20', $arr).'
';
echo '2016-09-26 is on index => '.getAd_uid('2016-09-26', $arr).'
';

RESULT

Working Demo


text:
Q: Safari CSS Transition flickering I have a problem with a webpage I'm working on. On Firefox it doesn't seem to have any problems.
I have 2 elements, horizontal scrolling, with background images and the transition between those 2 is made using CSS3, transformX(). At first these 2 elements overlay (so that you can see the background image of the 2nd element), when you click the right arrow the second element slides from right to left in front. When you click right the first element slides from left to right
When I go back to the first element, the second element flickers, like rearranging its position.
.first-container.first-container1 {
    background: transparent url('../img/backgrounds/first1-background.jpg') no-repeat center center;
    background-size: cover;
    left: 0;
}
.first-container.first-container2 {
    background: transparent url('../img/backgrounds/first2-background.jpg') no-repeat center center;
    background-size: cover;
    left: 100%;
}

.bs-first .first1 .first-container.first-container2 {
    -webkit-transform: translateX(-8.5%);
    -moz-transform: translateX(-8.5%);
    -o-transform: translateX(-8.5%);
    -ms-transform: translateX(-8.5%);
    transform: translateX(-8.5%);
}

.first2 .first-container.first-container1 {
    -webkit-transform: translateX(8.5%);
    -moz-transform: translateX(8.5%);
    -o-transform: translateX(8.5%);
    -ms-transform: translateX(8.5%);
    transform: translateX(8.5%);
    z-index: 9;
}

I could really use a few hints on how i could solve this. Thank you!

A: You can try -webkit-backface-visibility: hidden; applied to the element that has applied the css transform.
In your case if you are using background images that it won't work so just create a class and apply it like:
.stop-flickering {-webkit-transform:translate3d(0,0,0);}

Also you can try:
-webkit-transform-style: preserve-3d;

A: In my case none of these methods worked :
-webkit-transform:translate3d(0,0,0);

-webkit-backface-visibility: hidden;

-webkit-transform-style: preserve-3d;

I had an animation on an empty div to create bouncing circle and the solution was to use pseudo element :before and the flicker disappeared


text:
Q: Starting application GUI on remote windows from SSH linux simply I'm using centOS and im connected to a windows VM using ssh. I want to open an app but with it's GUI. I tried "notepad" but it starts in the background. i can find notepad in taskmanager but cannot see it. I tried using psexec but i'm on centos and it's doesnt work. I tried running psexec after ssh and it starts the process but still no graphic.
please help thanks

A: Yes finally,
I created a batch file that creates a schtasks in the past, starts the task and delete it and deleting it won't stop the task . IT WORKS LIKE CHARM IM SO HAPPY.
schtasks_creater.bat:
schtasks /create /SC ONCE /TN task_name /TR notepad.exe /ST 00:00
schtasks /run /TN task_name
schtasks /delete /TN task_name /F
pause

so now from my ssh i just start the bat file and close the ssh, it continues to work even after.
big thanks to can I ssh to Windows, start a command and let it run even when I log out?


text:
Q: Is it possible to use quantifiers with proper nouns? As far as I know, we always use quantifiers before nouns. From this I would like to know if the following constructions, with PROPER NOUNS, sound grammatically correct. If not, an explanation is most welcome.
Eg:
The whole Steve Carell's acting in "The Office" sitcom was great.
Also
The whole acting of Steve Carell's in "The Office" sitcom was great. (Sounds much better to me)
And
All of Rodrigo Santoro's acting in 300 was great!

My intention in these sentences would be to emphasize the actor's set of performances.

A: To me (native speaker, American) none of these sound idiomatic or natural. Here are some possible ways to rephrase.
I enjoyed all of Steve Carrol's performance in "The Office".
Or
Every part of Steve Carrol's performance in the "The Office" was great.
"The whole Steve Carrols's acting" does not make sense, and neither does "The whole acting of".
"The whole of Steve Carrol's acting" is correct but feels excessively formal and awkward. Most people don't talk that way. "The whole of" is a very formal way to say something. "All of" is more idiomatic. But "All of Rodrigo Santoro's acting" is not idiomatic.
If you didn't add "All of" you could say "His acting was great!" But once you add "All of", it feels unnatural.
I'm not sure I could give you a good reason that adding "All of" conflicts with "acting". Maybe it's because it sounds slightly more formal, because you are taking the time to point out that you mean all of it and not just one part, but it is not as formal as "The whole of".
"His acting was great!" is VERY informal, and means all of it by implication.
"All of his performance was excellent" is a bit more formal and analytic, but not stiffly formal like "The whole of".
The words 'great' and 'acting' are both casual and informal in this context, so if you want something that is formal but not as formal as "The whole of", you could use:
"His entire performance was excellent."
If you want something informal that doesn't just imply the entire performance, you could probably do something in two sentences more effectively and idiomatically.
"His acting was great! I loved all of it!"
Informality doesn't like long sentences.
If you want something pompous, you could say something like:
"The whole of his performance was remarkable, adept, and spritely. I was terribly amused."


text:
Q: What would be complexity of computing $3^{n^n}$? Just curious, what would be the computational complexity of computing $3^{n^n}$?
I am not sure what it would be like.

A: Let $M(n)$ denote the complexity of the multiplication of two integer with $n$-digits (let say in base two).
Thanks to Schonhage and Strassen we know that $M(n) = O(n \log n \log\log n)$. Thanks to Fürer, we even know that it's a bit lower.
Let $a$ be an integer and $b$ an integer. Then $a^b$ can be computed in time $O(M(b \log_2 a))$ using fast exponentiation. This is not bad: since $a^b$ has bit-size exactly $b\log_2 a$, the cost of the computation is almost the size of the output.
So the complexity of computing $a^{b^c}$ is the cost of computing of $b^c$ plus the cost of computing $a^{b^c}$. When $a$ is at least 2, then the second operation dominate the first, and the total cost is $O(M(b^c \log_2 a))$.
We could make explicit the constant in the big-oh, and we would realize that is is not much larger than 2 or 3.

A: If I understand what it means.
The problem is it gets huge each time like the sequence is
$< 3, 81, 19683, 43046721,\ldots >$
The number of digits of the $n$th term is $\lceil n^n\log_{10}3\rceil$.
So, $5$th and $6$th term has $1492$ and $22261$ digits respectively.
The $7$th, $8$th and $9$th term has $392930$, $8004767$ and $184846559$ digits respectively.
And $10^{10}$ has $11$ digits itself.

A: For simplicity, I will first assume that you are adopting a computational model that only keeps track of the number of multiplications (and that multiplication can be done in time independent of the number of integers).
We may then compute $3,3^2,(3^2)^2,\ldots, 3^{(2^n)}$ with $0,1,\ldots, n-1$ multiplications, respectively.  As any number less than $2^{n+1}$ is a sum of terms in $\{1,2,\ldots, 2^n\}$, it suffices in the calculation of $3^{n^n}$ to first calculate $3^{2^j}$ for $j \leq \lfloor n \log_2 n\rfloor$, and then take a product of at most $\lfloor n \log_2 n \rfloor +1$ of these $3^{2^j}$ terms.  To perform these preliminary calculations takes $\lfloor n \log_2 n \rfloor$ operations, and to multiply the end results requires another $\lfloor n\log_2 n \rfloor +1$ multiplications.  We then conclude in time $\sim 2n \log_2 n$.
Of course, this first answer is silly because the time required to multiply integers depends heavily on the length.  In fact, to merely output our answer requires time $O(n^n)$, as $3^{n^n}$ has $O(n^n)$-digits.
Now, let's assume it takes time at most $O(f(n))$ to square an $n$-digit number.  Then calculation of $3^{2^i} \times 3^{2^i}=3^{2^{i+1}}$ takes time $O(f(2^i))$, and so we can compute $3^{2^j}$ for $j \leq \lfloor n \log_n n\rfloor$ in time
$$ O\left(\sum_{j=1}^{\lfloor n \log_2 n \rfloor} f(2^j)\right).$$
For $f(n)= n\log n \log \log n$ (see here), this gives a total time of
$$\sum_{j=1}^{\lfloor n \log_2 n\rfloor}O(2^i \log 2^i \log \log 2^i)=\sum_{j=1}^{\lfloor n \log_2 n\rfloor}O(2^i i\log i)=O(n^{n+1}\log^2 n),$$
using comparison with an integral and some Mathematica magic.  This is quite reasonable, as we have already seen that the lower bound $O(n^n)$ must hold.
In general, one rarely obtains  "exact" growth orders for the computational complexity of even simple algorithms (e.g. multiplication).


text:
Q: Python Decorator Object Not Being Available I get
NameError: global name 'git' is not defined

for git.add(log_filename). I don't understand why since repo = Repo(ABSOLUTE_PATH) and git = repo.git is called before original_function = function(ABSOLUTE_PATH, GIT_WORKING_DIR, log_name, remove_logs). Shouldn't the git object be available to the called function?
I would like to utilize the decorator in this instance, since a separate function will be using similar functionality. How can I make this decorator work?
 def raw_git(function):
    @wraps(function)
    def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
            log_name=None, remove_logs=None):
        try:
            repo = Repo(ABSOLUTE_PATH)
            git = repo.git
        except NoSuchPathError:
            raise Exception("Error in finding local git path!")
        original_function = function(ABSOLUTE_PATH, GIT_WORKING_DIR,
                log_name, remove_logs)
        return original_function
    return wrapper

@raw_git
def git_add_log(ABSOLUTE_PATH, GIT_WORKING_DIR,
        log_name=None, remove_logs=None):
    log_name = GIT_WORKING_DIR + "/" + log_name
    try:
        git.add(log_filename)
        git.commit(message="Removing oldest logs")
        git.push()
    except GitCommandError:
        raise Exception("There was an error with git command "
                "for removing oldest log(s)")

A: git is a local name inside the wrapper function. It is not visible outside of that namespace, so not in git_add_log.
Give that function a git argument instead, and pass in the object when you call the wrapped function:
def raw_git(function):
    @wraps(function)
    def wrapper(ABSOLUTE_PATH, GIT_WORKING_DIR,
            log_name=None, remove_logs=None):
        try:
            repo = Repo(ABSOLUTE_PATH)
            git = repo.git
        except NoSuchPathError:
            raise Exception("Error in finding local git path!")
        original_function = function(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
                log_name, remove_logs)
        return original_function
    return wrapper

@raw_git
def git_add_log(git, ABSOLUTE_PATH, GIT_WORKING_DIR,
        log_name=None, remove_logs=None):
    log_name = GIT_WORKING_DIR + "/" + log_name
    try:
        git.add(log_filename)
        git.commit(message="Removing oldest logs")
        git.push()
    except GitCommandError:
        raise Exception("There was an error with git command "
                "for removing oldest log(s)")