text:
Q: Maximum related to Nonnegative Matrix Suppose $A$ is a fixed nonnegative $n\times n$ real matrix (i.e. $A_{ij}\geq0$ for all $i,j$). Then for any arbitrary $n$ positive real numbers $x_1,\ldots,x_n$, we denote:
$$F(x_1,\ldots,x_n)=\min_i\frac{1}{x_i}\sum_{j=1}^n x_jA_{ij}$$
Frobenius Theorem tells us that there's always an inequality
$$F(x_1,\ldots,x_n)\leq\rho(A)$$
where $\rho(A)$ is the spectral radius of $A$.
Here my question is, what is the maximum of $F(x_1,\ldots,x_n)$ ? Is it just $\rho(A)$ ? Or there's no maximum but a supremum?
Thanks a lot for your help.

A: You are essentially looking at collatz-weilandt formula. If your matrix $A$ is strictly positive or irreducible, then the maximum is the spectral radius.

A: This might not lead to a full solution you want, but it is worth rewriting the desired optimization as $$\sup_{t\geq 0,\mathbf{x}> \mathbf{0}} t\\
\text{subject to }(\mathbf{A}-t\mathbf{I})\mathbf{x}\geq \mathbf{0}.$$
Update: Let $t_0 = \frac{1}{2}\lambda_{\max}\left(\mathbf{A}+\mathbf{A}^T\right)$. For any $t>t_0$ and all $\mathbf{x}\ne \mathbf{0}$ we have $\mathbf{x}(\mathbf{A}-t\mathbf{I})\mathbf{x}^T<0$. Therefore, $(\mathbf{A}-t\mathbf{I})\mathbf{x}\geq \mathbf{0}$ cannot hold for any $\mathbf{x}>0$. So your optimal $t$ should be less than or equal to $t_0$.
Furthermore, for positive $A$ the maximum is the Perron-Frobenius eigenvalue (see here item #6).


text:
Q: How to add a prefix to all files and folders in a folder? (windows) The following command only changes the name of the files but not the folders.
for %a in (*) do ren "%a" "00_%a"

A: The following command only changes the name of the files but not the folders.
for %a in (*) do ren "%a" "00_%a"

Notes:

*

*Using for as above is not advised.

*There is a possibility that files can be renamed multiple times.

*See below for the reason why.

Use the following in a cmd shell:
for /f "tokens=*" %a in ('dir /b') do ren "%a" "00_%a"

In a batch file (replace % with %%):
for /f "tokens=*" %%a in ('dir /b') do ren "%%a" "00_%%a"

Note:

It is critical that you use FOR /F and not the simple FOR.
The FOR /F gathers the entire result of the DIR command before it begins iterating, whereas the simple FOR begins iterating after the internal buffer is full, which adds a risk of renaming the same file multiple times.

as advised by dbenham in his answer to add "text" to end of multiple filenames:

Further Reading

*

*An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.

*dir - Display a list of files and subfolders.

*for /f - Loop command against the results of another command.

A: To perform this For loop on folders (directories) instead of files, simply include the /D switch.
for /D %a in (*) do ren "%a" "00_%a"
From for /?:

FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple item sync from sqlite to sql server I have built an android app which allows for users to save data to an offline sqlite database. Upon saving the data to the local sqlite database, the information is added to a listview. This data can then be pushed to a remote sql database hosted on xampp when a 'sync' button is clicked using AsyncTasks.
Currently I can only push one sqlite row at a time to the remote database - which is obviously not efficient. I would like to be able to have a method that would select all loans created today, and push these multiple rows to the online server.
What would be the best method to implement this?


text:
Q: Error when using GGally::ggpairs: "object 'ContinuousRange' not found" I run ggpairs on my data and get this error:
 library(GGally)
 ggpairs(mix[, c("soc", "neg", "b")])
 # Error in structure(list(call = match.call(), aesthetics = aesthetics,  :
 # object 'ContinuousRange' not found

Here's my data
 structure(list(soc = c(-10.31, 14, 4, 1.5, 1.56), neg = c(-1.66,
-10.75, -0.63, -1.24, -0.9), b = c("2", "2", "3", "3", "2")), .Names =  c("soc",
"neg", "b"), row.names = c(1L, 2L, 4L, 5L, 6L), class = "data.frame")

The same issue happened when I applied it on a different set of data.


text:
Q: Calculating standard error of estimate, Wald-Chi Square statistic, p-value with logistic regression in Spark I was trying to build Logistic regression model on a sample data.
The output from the model we can get are the weights of features used to build the model.
I could not find Spark API for standard error of estimate, Wald-Chi Square statistic, p-value etc.
I am pasting my codes below as an example
import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS
import org.apache.spark.mllib.evaluation.{BinaryClassificationMetrics, MulticlassMetrics}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.RandomForest
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

    val sc = new SparkContext(new SparkConf().setAppName("SparkTest").setMaster("local[*]"))

    val sqlContext = new org.apache.spark.sql.SQLContext(sc);

    val data: RDD[String] = sc.textFile("C:/Users/user/Documents/spark-1.5.1-bin-hadoop2.4/data/mllib/credit_approval_2_attr.csv")

    val parsedData = data.map { line =>
      val parts = line.split(',').map(_.toDouble)
      LabeledPoint(parts(0), Vectors.dense(parts.tail))
    }

    //Splitting the data
    val splits: Array[RDD[LabeledPoint]] = parsedData.randomSplit(Array(0.7, 0.3), seed = 11L)
    val training: RDD[LabeledPoint] = splits(0).cache()
    val test: RDD[LabeledPoint] = splits(1)

    // Run training algorithm to build the model
    val model = new LogisticRegressionWithLBFGS()
      .setNumClasses(2)
      .run(training)
    // Clear the prediction threshold so the model will return probabilities
    model.clearThreshold
    print(model.weights)

The model weight output is
[-0.03335987643613915,0.025215092730373874,0.22617842810253946,0.29415985532104943,-0.0025559467210279694,4.5242237280512646E-4]

just an array of weights.
Although I was able to calculate Precision, Recall, Accuracy, Sensitivity and other model diagnostics.
Is there a way I can calculate standard error of estimate, Wald-Chi Square statistic, p-value in Spark?
I am concerned since there is a standard output in R or SAS.
Does this have to do something with the optimization method we are using in Spark?
Here we use L-BFGS or SGD.
May be I am not aware of the evaluation  methodology.
Any suggestion will be highly appreciated.

A: Following method will provide details of chi square test -
Statistics.chiSqTest(data)
Input data
val obs: RDD[LabeledPoint] =
      sc.parallelize(
        Seq(
          LabeledPoint(1.0, Vectors.dense(1.0, 0.0, 3.0)),
          LabeledPoint(1.0, Vectors.dense(1.0, 2.0, 0.0)),
          LabeledPoint(-1.0, Vectors.dense(-1.0, 0.0, -0.5)
          )
        )
      )
val featureTestResults: Array[ChiSqTestResult] = Statistics.chiSqTest(obs)

Returns an array containing the ChiSquaredTestResult for every feature against the label.
summary of the test including the p-value, degrees of freedom, test statistic, the method used, and the null hypothesis.


text:
Q: How to handle updates in the right way using signalr? I have a client application Angular and a signalR hub, and also I have a service that take a timestamp as a parameter.
I want to invoke a method in the hub when I press on a start button in the client, and when the method is invoked I want to keep listing to all the changes (create a timer) until the client press on the stop button then I will stop the timer.
So I want to ask which is better:
1- Call the invoked method from the client with time stamp and then create a setInterval to call the method in it and when the stop button is pressed I can stop it.
Pros:
It is easy to start and stop the timer.
Cons:
I am invoking the method each 1 sec, and then I am checking on the client if there are response to update the UI.
2- Invoke the method once and then create a timer for each client on the server and when the client press on stop button I can invoke another method to stop the timer for that client.
Pros:
I am checking the timestamp in the hub and I will send the data to the client only if the timeStamp from the service > timeStamp locally
Cons:
I actually don't know how to create a timer for each client, so if this is the right way please help me

A: You are using SignalR for real time data communication. Invoking a method every second is just joking on the SignalR face... So this is not a solution.
The best solution would be using the group feature.
Example:

*

*You start button will add the user to an group.

*While your user is on the group it will receive all the data you need. await this.Clients.Group("someGroup").BroadcastMessage(message);

*Your stop button will remove the user from the group so it will not receive data anymore.

Some code example on the hub:
public async Task Start()
{
    // Add user to the data group

    await this.Groups.AddToGroupAsync(this.Context.ConnectionId, "dataGroup");
}

public async Task Stop()
{
    // Add user to the data group

    await this.Groups.RemoveFromGroupAsync(this.Context.ConnectionId, "dataGroup");
}

Worker example that sends data to the users that pressed start and receive real time data.
private readonly IHubContext<SignalRHub, ISignalRHub> hub;

private readonly IServiceProvider serviceProvider;

public Worker(IServiceProvider serviceProvider, IHubContext<SignalRHub, ISignalRHub> hub)
{
    this.serviceProvider = serviceProvider;
    this.hub = hub;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        await this.hub.Clients.Group("dataGroup").BroadcastMessage(DataManager.GetData());

        this.Logger.LogDebug("Sent data to all users at {0}", DateTime.UtcNow);

        await Task.Delay(1000, stoppingToken);
    }
}

PS: Where you have the worker, I assume you have some manager that gets the data or something to be sent to the user.
Edit: If you don't want to user worker, you can always just the timer like:
public class TimerManager
{
    private Timer _timer;
    private AutoResetEvent _autoResetEvent;
    private Action _action;
    public DateTime TimerStarted { get; }

    public TimerManager(Action action)
    {
        _action = action;
        _autoResetEvent = new AutoResetEvent(false);
        _timer = new Timer(Execute, _autoResetEvent, 1000, 2000);
        TimerStarted = DateTime.Now;
    }

    public void Execute(object stateInfo)
    {
        _action();
        if((DateTime.Now - TimerStarted).Seconds > 60)
        {
            _timer.Dispose();
        }
    }
}

And then use it somewhere like:
 var timerManager = new TimerManager(() => this.hub.Clients.Group("dataGroup").BroadcastMessage(DataManager.GetData()));

A: Option #1 isn't available since SignalR exists to remove the need for polling. Frequent polling doesn't scale either. If every client polled the server every 1 second, the web site would end up paying a lot of CPU and bandwidth for nothing. Business people don't like frequent polling either, as all hosters and cloud providers charge for egress.
The SignalR streaming examples use timed notifications as a simple example of streaming notifications using IAsyncEnumerable<T>. In the simplest example, a counter increments every delay milliseconds :
public class AsyncEnumerableHub : Hub
{
    public async IAsyncEnumerable<int> Counter(
        int count,
        int delay,
        [EnumeratorCancellation]
        CancellationToken cancellationToken)
    {
        for (var i = 0; i < count; i++)
        {
            // Check the cancellation token regularly so that the server will stop
            // producing items if the client disconnects.
            cancellationToken.ThrowIfCancellationRequested();

            yield return i;

            // Use the cancellationToken in other APIs that accept cancellation
            // tokens so the cancellation can flow down to them.
            await Task.Delay(delay, cancellationToken);
        }
    }
}

The client can call this action passing the desired delay and just start receiving notifications. SignalR knows this is a stream of notifications because it returns IAsyncEnumerable.
The next, more advanced example uses Channels to allow the publisher method WriteItemsAsync to send a stream of notifications to the hub.
The action itself is simpler, it just returns the Channel's reader:
public ChannelReader<int> Counter(
    int count,
    int delay,
    CancellationToken cancellationToken)
{
    var channel = Channel.CreateUnbounded<int>();

    // We don't want to await WriteItemsAsync, otherwise we'd end up waiting
    // for all the items to be written before returning the channel back to
    // the client.
    _ = WriteItemsAsync(channel.Writer, count, delay, cancellationToken);

    return channel.Reader;
}

The publisher method writes to the ChannelWriter instead of returning an IAsyncEnumerable :
private async Task WriteItemsAsync(
    ChannelWriter<int> writer,
    int count,
    int delay,
    CancellationToken cancellationToken)
{
    Exception localException = null;
    try
    {
        for (var i = 0; i < count; i++)
        {
            await writer.WriteAsync(i, cancellationToken);

            // Use the cancellationToken in other APIs that accept cancellation
            // tokens so the cancellation can flow down to them.
            await Task.Delay(delay, cancellationToken);
        }
    }
    catch (Exception ex)
    {
        localException = ex;
    }

    writer.Complete(localException);
}

This method can easily be in a different class. All that's needed is to pass ChannelWriter to the publisher.


text:
Q: Replacing numbers with letters in string I have an ID column with names like "155AB3EA157A3466887D8F4B99BABC35". I want to replace the numbers in these strings with letters. I've tried using gsub, but it produces an "invalid text argument" error. My code looks like this:
as.character(df$ID)
gsub("1", "A", df$ID)

I should add that I'm working with the ff package, because the data is very large.

A: IF we are replacing numbers 1-9 with LETTERS 'A' to 'I', then chartr is an option
chartr('123456789', 'ABCDEFGHI', v1)
#[1] "AEEABCEAAEGACDFFHHGDHFDBIIBABCCE"

Update
Just noticed that the OP was probably using an ffdf object
library(ff)
library(ffbase)

In that case, applying the functions in the regular manner results in error as the OP mentioned
gsub("1", "A", d$v1)

Error in gsub("1", "A", d$v1) : invalid 'text' argument

So, we can use the specialized extraction functions like with.ffdf or within.ffdf from ffbase
with.ffdf(d, gsub("1", "A", v1))
#ff (open) integer length=1 (1) levels: A55AB3EAA57A3466887D8F4B99BABC35
#                         [1]
#A55AB3EAA57A3466887D8F4B99BABC35

For replacing the numbers 1-9, the chartr can be applied as
d$v1 <- with.ffdf(d, chartr('123456789', 'ABCDEFGHI', v1))
d
#ffdf (all open) dim=c(1,1), dimorder=c(1,2) row.names=NULL
#ffdf virtual mapping
#   PhysicalName VirtualVmode PhysicalVmode  AsIs #VirtualIsMatrix PhysicalIsMatrix PhysicalElementNo #PhysicalFirstCol PhysicalLastCol PhysicalIsOpen
#v1           v1      integer       integer FALSE           FALSE            FALSE                 1                1               #1           TRUE
#ffdf data
#                                v1
#1 AEEABCEAAEGACDFFHHGDHFDBIIBABCCE

data
v1 <- "155AB3EA157A3466887D8F4B99BABC35"
d <- as.ffdf(data.frame(v1))


text:
Q: How do we prove the existence of the instantaneous axis of rotation? Euler's theorem of rotation states that any rigid body motion with one point fixed is equivalent to a rotation about some axis passing through that fixed point. Now it is often said that Euler's theorem of rotations implies the existence of an instantaneous axis of rotation.  My question is, how can we prove that the instantaneous axis of rotation exists?
Consider a rigid body which is undergoing some motion with one point fixed.  For any given times $t_1$ and $t_2$, let $\hat{u}(t_1,t_2)$ denote the unit vector parallel to the axis of the rotation that's equivalent to the motion of the the rigid body between time $t_1$ and time $t_2$.  Then how can we prove that the limit of $\hat{u}(t_1,t_2)$ as $t_2$ goes to $t_1$ exists?
Also, having proved the limit does exist, how can we prove that unit vector we get points in the direction of the angular velocity vector of the rigid body?
This would all be much easier to prove if the angular velocity vector were the derivative of the angular displacement vector, but things don't work out so smoothly because rotations don't commute; see this journal paper for details.
EDIT: I just posted a follow-up question here.

A: Find the locus of points with no motion on a rigid body, if point A is fixed.
Without loss of generality place a coordinate system on A. Rigid body motion is defined if an arbitrary point maintains constant distance from A $$d = \sqrt{x^2+y^2+z^2}$$
This is found by setting $\frac{{\rm d}d}{{\rm d}t}=0$ which by the chain rule (with time derivative of $\frac{1}{2}d^2$) implies $$ x \frac{{\rm d}x}{{\rm d}t} +  y \frac{{\rm d}y}{{\rm d}t}+ z \frac{{\rm d}z}{{\rm d}t} = 0$$
In vector form the above is $$\vec{r} \cdot \vec{v} =0$$ with $\vec{r}=(x,y,z)$ and $\vec{v} = \frac{{\rm d}\vec{r}}{{\rm d}t}$.
So the velocity field has to be perpendicular to the location vector. An obvious solution to the above is
$$ \vec{v} = \vec{\omega} \times \vec{r}$$
$$ \vec{r} \cdot (\vec{\omega} \times \vec{r}) \equiv 0 $$
So we have established that vector a velocity field of the form $\vec{v} = \vec{\omega} \times \vec{r}$ describes rigid body motion. This also imposes the limitation that $\vec{\omega}$ is constant throughout the body because otherwise the above expression wouldn't be zero. Try it.
Now let's look at the points parallel to $\vec{\omega}$ with $\vec{r} = \lambda \,\vec{\omega}$. The velocities are
$$\vec{v}_\parallel =  \vec{\omega} \times (\vec{r}) = \vec{\omega} \times \lambda \,\vec{\omega} \equiv 0$$
Now let's look at points perpendicular to the direction of $\vec{\omega}$ with a distance $d$
$$\vec{r} = \lambda \vec{\omega} + d \vec{n}$$ with the properties $\| \vec{n} \|=1$ and $\vec{n}\cdot\vec{\omega}=0$
$$\vec{v} = \vec{\omega} \times (\vec{r}) = \vec{\omega} \times ( \lambda \,\vec{\omega} + d \,\vec{n}) = d\,(\vec{\omega} \times  \vec{n})$$
which is a vector perpendicular to both $\vec{\omega}$ and $\vec{n}$. This implies a tangential (hoop) direction for the velocity with the magnitude increasing linearly with distance.
We call this motion rotation.

Here is an interesting fact. If at some arbitrary point located at $\vec{r}$ the velocity vector is $\vec{v}$ and the body is rotating with $\vec{\omega}$ then the instant axis of rotation is located at
$$\vec{q} = \vec{r} + \frac{\vec{\omega} \times \vec{v}}{\| \vec{\omega} \|^2}$$
The proof is that $\vec{v} = \vec{\omega} \times (\vec{r}-\vec{q}) \rightarrow$
$$\require{cancel}
\begin{align}
  \vec{v} & = \vec{\omega} \times \left(\vec{r}-\left(\vec{r} + \frac{\vec{\omega} \times \vec{v}}{\| \vec{\omega} \|^2}\right) \right) \\
& =  -\frac{\vec{\omega} \times(\vec{\omega} \times \vec{v})}{\| \vec{\omega} \|^2} = -\frac{ \vec{\omega}( \vec{\omega} \cdot \vec{v} ) - \vec{v} (\vec{\omega} \cdot \vec{\omega})}{\| \vec{\omega} \|^2} =  \frac{ \vec{v} \| \vec{\omega}\|^2}{\| \vec{\omega} \|^2} - \frac{\vec{\omega}(\vec{\omega}\cdot\vec{v})}{\| \vec{\omega} \|^2} \\
\vec{v} &= \vec{v} -\frac{\vec{\omega}(\cancel{\vec{\omega}\cdot\vec{v}})}{\| \vec{\omega} \|^2} & \vec{v} \equiv \vec{v}
\end{align}$$


text:
Q: Banach subsequence converges Show that every sequence in a Banach space such that $\{x_n\} \rightarrow 0$ has a subsequence $\{x_{n_p}\}$ such that $\sum_{p=1}^{\infty} x_{n_p} $ converges by showing $S_N = \sum_{p=1}^{N} x_{n_p}$ is a Cauchy sequence.
The convergent to the zero vector is what is confusing -- typically it is just to some other element? How do I incorporate this?

A: Hint: Since $\lim\limits_{n\to\infty}x_n=0$, then there exist subsequence $\{n_p:p\in\mathbb{N}\}\subset\mathbb{N}$ such that $\Vert x_{n_p}\Vert\leq 2^{-p}$.


text:
Q: Why is this jQuery .find() not selecting ALL the elements? I'm not sure why jquery isn't selecting all the elements with an id starting with "widhet_slot" or with the class "widget slot".

I'm loading this selection via ajax, and sending it to jquery. I'm logging the output:
$.get "#{durl}/layouts/#{lname}/#{version}/html", (data) ->
    console.log data
    console.log $ data
    console.log $(data).find '[id^=widget_slot]'
    console.log $(data).find '.widget_slot'

The outputs are:

The Problem
As you can see, the header and footer are not selected by "[id^=widget_slot]" while nothing is selected by '.widget_slot'
Is this to be expected? I've also tried "*[id^=widget_slot]" with the same result.
EDIT:
I updated the logging for the class part. I made a mistake, though in correcting it, bizarrely, I still don't get the output I expected.


text:
Q: How to isolate worker dynos from web dynos on heroku? We have developed a Rails app in Heroku, we have around 3 web dynos, and 2-3 worker dynos. We have some exporting and importing functionalities that use a lot of our worker dynos, when that happens, everything crashes, and we get an App error un the website.
Sentry tells us that it is due to a Timeout. We are trying to find out which functionality of our software is taking so much worker time. The problem is that it affects all of our users, some of them only using web layer functionalities.
But I was wondering, is there a way to isolate our worker dyno problems from the web dynos work? I mean, Is there a way that our site does not crash when one user exports a big amount of data and saturates the workers?
Thanks in advance!
Regards,
Gonzalo

A: thank you for the answers, let me give you some related info:
- We use delayed_job for the workers, which is async.
- We used to have a DB connection before, it supported 120 connections, and we never saw it completely busy. The current AWS RDS only reached 24% of its use and we only saw 28 concurrent connections on the day of the crash.
- New Relic did not indicate delay in the DB.
- The web dynos start to generate timeout in many functionalities, if the crash is not related to the workers, it may be because of some functionality that is not in jobs.
Update:
- We have set some limits in our exports, even when those are in jobs, this was affecting our web and giving some App Errors. When we set the limit, the App Errors were dramatically reduced.
- We are still searching for any other unoptimized functionality.


text:
Q: Visual Studio & GDI++ I tried to find a similar question here, but found something different. I prefer to use display fonts smoothing in Windows, but I don't like the way how Windows XP smoothes the display font edges. Currently I use GDI++ that smoothes the display fonts making them look very similar to text rendered in Safari browser for Windows (as far as I know, not a Mac user, it's a native approach to MacOS). Great, GDI++ really renders the fonts very similar to Safari almost for all application I use, but I'm disappointed knowing that GDI++ does not (and can't?) support Visual Studio and Google Chrome. I guess these applications use somewhat another way to render the display fonts (just GDI O_o; and I guess they take into consideration Windows font edges smoothing settings [no smoothing, Standard or ClearType]), but I'm not sure and I'm not familiar with it. :(
Please clarify this to me. I'd really like to use GDI++ in Visual Studio and Google Chrome. Probably, someone uses some workarounds (sure, if it's possible). Thank you.

A: This blog post by our esteemed benefactor is relevant.  GDI+ indeed does things the Apple way, it uses true resolution independent rendering.  It was pretty widely panned for this, so much so that it was replaced in .NET 2.0 with the TextRenderer class.  Which uses the GDI DrawTextEx() function to draw text.  To give an example of how GDI+ can suck, try running this sample Windows Forms form:
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
    }
    protected override void OnPaint(PaintEventArgs e) {
      e.Graphics.DrawString("Hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii!", this.Font, Brushes.Black, 0, 0);
    }
  }

YMMV, but I haven't yet had a machine where that didn't look completely awful.  TextRenderer saved the day.
Until .NET 3.0 when WPF was introduced.  Back to resolution independent rendering.  The amount of hate that generated was stunning.
Long story short, the majority of users like GDI text rendering.  Or at least they get very vocal when they don't get it.  Visual Studio and Chrome no doubt use GDI for text output.  This is not something you can easily change yourself, although Chrome is open source afaik.
Just wait for the next version.  Visual Studio 2010 will use WPF.  Beta 1 generated a lot of hate for blurry text.  But WPF has been tweaked to limit the fuzzies so it might not fit your taste anymore.


text:
Q: How to create SqlDataConnection for db with table 'System'? I want to create a SqlDataConnection type provider for a database with a table, which name is exactly 'System'.
During compilation I get an error:

The type provider 'Microsoft.FSharp.Data.TypeProviders.DesignTime.DataProviders' reported     an error:
      tmpB600.cs(12,7): warning CS0437: The type 'System' in     'c:\Users\krajewa1\AppData\Local\Temp\tmpB600.cs' conflicts with the imported namespace     'System' in 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Configuration.dll'. Using     the type defined in 'c:\Users\krajewa1\AppData\Local\Temp\tmpB600.cs'.
      [...] (hundreds of errors following)

To workaround it I've tried :

*

*Using LocalSchemaFile with dbml file which does not contain 'System'
table. It did not help, still the same error.

*Using ContextTypeName parameter (which I hoped would put types in another namespace). It did not help, still the same error.

*Creating a synonym for System table. Of course original table was still there, so I got the same error.

*Obviously, changing table name to '_System' does help, but is not feasible in practice in my case.

My problem is exactly the same as the one asked in this question:
SqlDataConnection type provider generates massive error with SQL Server 2008 R2.
However, in that thread users did not the find real cause of the problem and did not provide an answer.

A: I don't know F# but could you not create a SQL Server synonym for the problematic table name?
http://msdn.microsoft.com/en-gb/library/ms177544.aspx
CREATE SYNONYM [SystemTable] for [System]

And then refer to the table by the synonym instead of it's real name in your F# Code.
It might be possible to simply rename the table instead but if there are any other queries running against it they would need to be changed as well. The synonym means both names are valid


text:
Q: Is a list in dictionary values? a = {0:[[1,2,3], [1,3,4,5]]}
print([1,2,3] in a.values())

I get False. Because this list is in values I need True. Is it possible to check all lists in nested list as a value in dictionary? Maybe without loops?

A: Since you're using python3 you can do this:
[1,2,3] in list(a.values())[0]

a.values() returns a dictionary view. dictionary views
Then you can wrap the dictionary view into list but this list will contain only one element which can be accessed by index 0. However, if your dictionary contains several keys and corresponding values then list(a.values()) will contain the same number of elements (values mapped to keys) as keys in the dictionary.
Note that when you use some_value in some_collection construct and don't use loops explicitly it will still iterate through the collection.


text:
Q: Search on resume I have an application that lets the user write keyword and search videos related to that.
When I click on a video to start play it, it opens Video Activity and plays it.
The problem is when I'm pressing the back button to choose another video, I need to click search again.
I tried to use onResume method and but it's not working properly.
Any ideas?
Here is the onResume:
    @Override
protected void onResume() {
    super.onResume();
    hideKeyboard(); // a method to hide the keyboard.
    mServiceTask = new ServiceTask(SEARCH_VIDEO);
    mServiceTask.setmServerResponseListener(this);
    mServiceTask.execute(new Object[]{postKeyword}); // postKeyword is the keyword the user entered.
}

Here is the method that plays the video:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    SearchResult result = (SearchResult)parent.getItemAtPosition(position);
    VIDEO_ID = result.getId().getVideoId();
    Intent videoIntent = YouTubeStandalonePlayer.createVideoIntent(this,AppConstants.KEY,VIDEO_ID);
    startActivity(videoIntent);
}

Hope you guys could help me.
Thanks in advance and sorry for bad English.


text:
Q: How to solve in polynomial time Rat in Maze Puzzle? I was recently asked this question in an Interview:

A Maze is given as N*N binary matrix of blocks where source block is
  the upper left most block i.e., maze[0][0] and destination block is
  lower rightmost block i.e., maze[N-1][N-1].  A rat starts from source
  and has to reach destination. The rat can move only in two directions:
  forward and down. (or 4 in advanced problem). In the maze matrix, 0
  means the block is dead end and 1 means the block can be used in the
  path from source to destination.

My answer was the one mentioned in the link, which is using backtracking. High level pseudo code from the link:
If destination is reached
    print the solution matrix
Else
   a) Mark current cell in solution matrix as 1.
   b) Move forward in horizontal direction and recursively check if this
       move leads to a solution.
   c) If the move chosen in the above step doesn't lead to a solution
       then move down and check if  this move leads to a solution.
   d) If none of the above solutions work then unmark this cell as 0
       (BACKTRACK) and return false.

The interviewer was quite surprised by my response , and was apparently expecting a polynomial time solution.
Does there exist a polynomial time solution for this problem?

A: This can be solved in linear time using BFS.
The problem is actually a graph, where all cells are vertices and a possible move from cells is the edges. You are looking for the shortest path from some source to the destination, which is exactly what BFS does.
(Note that in simplified problem with only "down" and "right" allowed, valid path has the same length. This is not true though for the more complex problem with 4 allowed directions)
To generate the actual path, you need to keep track of the path by "remembering" the parent of each node explored. This is discussed in the question: How can I find the actual path found by BFS?


text:
Q: Raycast is firing just one ray Unity I'm actually working on a word search like game.
But i'm having issues when i want to select instantiate gameObjects on a grid.
as i saw on unity doc, i used raycast to check which collider has been hit, and do some logic.
So i wrote this:
void Update(){

    if (Input.GetMouseButtonDown(0))
    {
        Ray ray;
        RaycastHit hit;
        GameObject current;

        ray = Camera.main.ScreenPointToRay (Input.mousePosition);

        if (Physics.Raycast (ray, out hit))
        {
            if (hit.collider.tag == "tile")
            {
                //Do some logic
            }
        }
    }

After that, i used this:
Vector3 forward = transform.TransformDirection(Vector3.forward) * 50;
Debug.DrawRay(transform.position, forward, Color.green);

to display raycasts when i run the game.
So when i click with my mouse, a single ray is fired.
Normally it should fire a lot more. But i don't know why it's shooting just one ray.
Also,

Input.mousePosition

does not seem to work. the ray just fires at the center of my screen.
How can i fix that? Is there other method than raycast?
Thanks a lot.


text: Q: MultiSelect - After entering first value the filter is auto closing In my kendo grid i have 8 columns it consists kendo multiselect filter option. 7 columns working well but in one column when entering the first value the filter is auto closing


text:
Q: Controlling client terminal (linux) In my university I have a server (CLUB Server) but the university local network is closed I mean I can not access the server from outside (from my house for example) but the server have the ability to access another server on the internet so in order to control the server I decided to make my home computer a server and buy a Fix-IP and configure the server to connect to my home server and in that way I will be able to control the University server from my home server
So it's easy to do that for example I can make an IRC server at home and when the university server connect to my home server I will send him command in on the chat space but this is not enough because I want to control the university server terminal so is there any existing application that have the ability to do such a thing or I have to program the control of my IRC chat commands one by one , please post any information you have ?

A: you can daisy chain ssh from machine to machine. log onto the the server you can get to from the outside with user@ip once logged in there ssh through the LAN with user@ lan ip for that server.

A: The solution is to use the Reverse SSH and it's to make the server connect to the client and make an SSH port forwarding from client computer to the server so anyone  will be able to connect to the server just by connecting to the client computer
For more informations -> https://www.howtoforge.com/reverse-ssh-tunneling


text:
Q: Memory allocation/deallocation for pointer I have simple socket communicate function:
int communicate( const char * tx, char * rx, int bufSize , char * inetAddr, int port )
{
    if (!sockInitialised) initSock();

    if (sockInitialised)
    {
        SOCKET s;
        struct sockaddr_in server;

        server.sin_addr.s_addr = inet_addr(inetAddr);
        server.sin_family = AF_INET;
        server.sin_port = htons( port );

        if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
        {
            BOOST_LOG_SEV(getDefLg(), debug) << "Could not create socket : " << WSAGetLastError();
        } else
        {
            if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0)
            {
                puts("connect error");
                return 1;
            } else
            {
                int l =strlen(tx)+strlen("DATA ");

                char* dtx ;
                dtx = (char*) calloc(sizeof(char),strlen(tx)+strlen("DATA "));

                sprintf(dtx,"DATA %s",tx);

                if( send(s , dtx , strlen(dtx) , 0) < 0)
                {
                    puts("Send failed");
                    return 1;
                } else
                {

                    int recv_size = 0;
                    if((recv_size = recv(s , rx , bufSize , 0)) == SOCKET_ERROR)
                    {
                        puts("recv failed");
                    } else
                    {
                        rx[recv_size] = '\0';
                    }
                }
                free(dtx);
            }
        }
    } else return 1;

}

I have error on line
free(dtx);

Error:
---------------------------
Microsoft Visual C++ Debug Library
---------------------------
Debug Error!

    HEAP CORRUPTION DETECTED: after Normal block (#1497) at 0x057D26F8.
    CRT detected that the application wrote to memory after end of heap buffer.

    (Press Retry to debug the application)
    ---------------------------
    Abort   Retry   Ignore
    ---------------------------

What is wrong with calloc and free in this code?

A: You allocate strlen(tx)+strlen("DATA ") bytes for concatenation of those two strings - where is the byte for zero terminator? Use strlen(tx)+strlen("DATA ")+1.


text:
Q: In wxpython, how to select a particular text and set its font style selected I've created a text editor in wxpython but I can't get the selected text.
I guess I'm using the function GetSelectedString() function wrong
def OnSelectFont(self,e):
    dialog = wx.FontDialog(None, wx.FontData())
    if dialog.ShowModal() == wx.ID_OK:
        data=dialog.GetFontData()

        self.text.GetSelectedString.SetFont(font)

    dialog.Destroy()

A: Assuming you have a wx.TextCtrl of style wx.TE_RICH as in:
self.text = wx.TextCtrl(self.button, style=wx.TE_RICH)
Then, for instance for setting the selection bold, you would do:
    font = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD, False)
    style = self.text.GetDefaultStyle()
    style.SetFont(font)
    (begin, end) = self.text.GetSelection()
    self.text.SetStyle(begin, end, style)

Having wx.TE_RICH is crucial here, as otherwise you wouldn't be able to SetStyle.


text:
Q: IOS sythesize - when to declare an internal variable? I'm following along with Apple's "Hello" tutorial on iOS, and I'd like to know why it's necessary to declare the "userName" variable (to be accessed in code later). Isn't it generated by the synthesize statement?
@interface HelloWorldViewController : UIViewController {
    NSString *userName;
}

- (IBAction)changeGreeting:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UITextField *testField;
@property (nonatomic, copy) NSString *userName;

And here's the implementation of synthesize:
@synthesize label=_label;
@synthesize testField=_testField;
@synthesize userName=_userName;

A: It wasn't always generated by the property/synthesize. That's a relatively new addition to Objective-C. The tutorial was probably written before this was the case.


text:
Q: Utilizing radix sort to sort both negative and positive numbers I am attempting to utilize radix sort in order to sort a list of unordered integers, both positive and negative. I have the ability to sort a list of positive numbers, but I am confused on how to use radix sort with negative numbers. I was wondering if someone could help me out with coding and explaining the part about how radix sort works with negative numbers. After some googling I understand that you have to treat the negative sign as a special character but I'm still on the confused train. Below you can see the implementation I have of radix sort at the moment, taken from https://gist.github.com/rizkyabdilah/1740053.
def radix_sort(random_list):
len_random_list = len(random_list)
modulus = 10
div = 1
while True:
    # empty array, [[] for i in range(10)]
    new_list = [[], [], [], [], [], [], [], [], [], []]
    for value in random_list:
        least_digit = value % modulus
        least_digit /= div
        new_list[least_digit].append(value)
    modulus = modulus * 10
    div = div * 10

    if len(new_list[0]) == len_random_list:
        return new_list[0]

    random_list = []
    rd_list_append = random_list.append
    for x in new_list:
        for y in x:
            rd_list_append(y)

random_data = [13, 8, 1992, 31, 3, 1993, 1, 0, -1]
print radix_sort(random_data)

Thanks for helping!

A: The simplest method is to complement the sign bit of the most significant field for the count (histogram) generation and for the indexing during the radix sort. Assuming near random data, the process is memory bandwidth limited due to the random writes, so the overhead of complementing the sign bit won't have much impact on overall performance.
This is assuming ones or twos complement integers.
If I remember correctly, sign + magnitude, which is how IEEE floating point values are effectively implemented (if radix sorting them as if they were integers), requires complementing the sign bit for positive numbers, and negation of the entire number for negative numbers.


text:
Q: Uniqueness of the morphism in the universal property If we want to define a product of objects in a category (cf. Wikipedia Page), we need to find a morphism and it must be unique.
In our notes, the professor gives some examples such as the product of groups in the category of groups. In these examples, he explicitly constructs the morphism (needed in the universal property) but he does not prove the uniqueness. Do we always have the uniqueness of the morphism in the universal property for free? Or we have to prove it by some way?
Thanks for help.

A: No, uniqueness of the morphism in the definition of a universal property does not come for free. It has to be proven.
You mention the direct product of groups. If $f : T \to A$, $g : T \to B$ are homomorphisms of groups, we need to provide a unique homomorphism $h : T \to A \times B$ with $p_1 \circ h = f$ and $p_2 \circ h = g$. Writing down what these equations mean, we get $h(t) = (f(t),g(t))$. Thus, uniqueness follows. We only have to verify that the map which is defined by $h(t) := (f(t),g(t))$ is actually a group homomorphism $-$ which easily follows from $f$ and $g$ having this property.
If we omit uniqueness, we get more groups satisfying the (non-)universal property of product. Take any group $P$ which admits a split epimorphism $P \twoheadrightarrow A \times B$ (for example $A \times A \times B$). Then we have $p'_1 : P \twoheadrightarrow A \times B \to A$, $p'_2 : P \twoheadrightarrow A \times B \to B$, and for all $f,g$ as above we can find $h' : T \to P$ with $p'_1 \circ h' = f$ and $p'_2 \circ h' = g$, namely the composition of $h : T \to A \times B$ (as defined above) and the section $A \times B \hookrightarrow P$.
This is connected to the notion of a weak limit, which modifies the notion of a limit by omitting uniqueness of the morphism. For example, a weakly terminal object is an object $T$ such that every object $A$ admits a morphism $A \to T$ (which is not necessarily unique). In the category of groups, every object is weakly terminal. A more interesting example is the category of algebraic extensions of a field $K$. Any algebraic closure of $K$ is a weakly terminal object, but it is not terminal since embeddings of algebraic extensions into the algebraic closure are not unique. Also, $\mathrm{Aut}_K(\overline{K})$ is not trivial, it is the absolute Galois group of $K$. The category of algebraic extensions of $K$ has no terminal object.


text:
Q: Ссылка на скачивание файла .txt и .pdf Как сделать, чтобы скачивался а не открывался в браузере?
A: грубо говоря так:
header('Content-type: application/pdf');
header("Content-Disposition: attachment; filename=\"1.pdf\"");
$x = fread(fopen("1.pdf", "rb"), filesize("1.pdf"));
echo $x;

Еще есть такой совет для вебсерверов с поддержкой .htaccess, но я не пробовал:
  htaccess - простой файл конфигурации, который позволяет изменять конфигурацию веб-сервера на стороне веб мастера. Именно он помогает обходить те запреты, которые устанавливает хостер, так как сам конфигурационный файл хостер не предоставляет в редактирование, но зато дает возможность управлять параметрами веб сервера при помощи .htaccess
В который необходимо добавить запись в виде.
AddType application/download .pdf
или в зависимости от того как будет происходить сохранение файла
AddType application/octet-stream .pdf
или
AddType application/force-download  .pdf

После этого все файлы в формате pdf будут именно скачиваться на ваш компьютер, а не открываться в браузере.
либо странный способ:
Так же можно в ссылку вставить download=""

Скачать PDF

A: Создаем файл download.php туда вставляем код ниже, сохраняем, закидываем в папку где у нас страница и на странице пишем:
    Файл который можно скачать

Код в dowloads.php:
if (file_exists($filename)) {
    header("Content-type: application/x-download");
    header("Content-Disposition: attachment; filename=$filename");
    readfile($filename);
} else { header("HTTP/1.1 404 Not Found"); echo '404 Not Found'; }
?>

Как то так.

A: Насколько я помню, то через HTML - никак. Но вообще со стороны сервера можно content-type поменять, чтобы файл наверняка скачивался...


text:
Q: Encrypt/Decrypt String Kotlin I've created this two extensions in Kotlin to Encrypt/Decrypt strings:
fun String.encrypt(seed : String): String {
    val keyGenerator = KeyGenerator.getInstance("AES")
    val secureRandom = SecureRandom.getInstance("SHA1PRNG")
    secureRandom.setSeed(seed.toByteArray())

    keyGenerator.init(128, secureRandom)
    val skey = keyGenerator.generateKey()
    val rawKey : ByteArray = skey.encoded

    val skeySpec = SecretKeySpec(rawKey, "AES")
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
    val byteArray = cipher.doFinal(this.toByteArray())

    return byteArray.toString()
}

fun String.decrypt(seed : String): String {
    val keyGenerator = KeyGenerator.getInstance("AES")
    val secureRandom = SecureRandom.getInstance("SHA1PRNG")
    secureRandom.setSeed(seed.toByteArray())

    keyGenerator.init(128, secureRandom)
    val skey = keyGenerator.generateKey()
    val rawKey : ByteArray = skey.encoded

    val skeySpec = SecretKeySpec(rawKey, "AES")
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, skeySpec)
    val byteArray = cipher.doFinal(this.toByteArray())

    return byteArray.toString()
}

for some reason I'm getting the following exception:
javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

What I'm doing wrong?

A: Following Maarten Bodews guides I fix the issues as:
fun String.encrypt(password: String): String {
    val secretKeySpec = SecretKeySpec(password.toByteArray(), "AES")
    val iv = ByteArray(16)
    val charArray = password.toCharArray()
    for (i in 0 until charArray.size){
        iv[i] = charArray[i].toByte()
    }
    val ivParameterSpec = IvParameterSpec(iv)

    val cipher = Cipher.getInstance("AES/GCM/NoPadding")
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)

    val encryptedValue = cipher.doFinal(this.toByteArray())
    return Base64.encodeToString(encryptedValue, Base64.DEFAULT)
}

fun String.decrypt(password: String): String {
    val secretKeySpec = SecretKeySpec(password.toByteArray(), "AES")
    val iv = ByteArray(16)
    val charArray = password.toCharArray()
    for (i in 0 until charArray.size){
        iv[i] = charArray[i].toByte()
    }
    val ivParameterSpec = IvParameterSpec(iv)

    val cipher = Cipher.getInstance("AES/GCM/NoPadding")
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)

    val decryptedByteValue = cipher.doFinal(Base64.decode(this, Base64.DEFAULT))
    return String(decryptedByteValue)
}

A: To encode your ciphertext use base 64 or hexadecimals. The Java API contains a Base64 class, so you're probably best off using that.
byte[]#toString doesn't do what you expect it to do; it simply returns a representation of the byte array reference, not the contents of the byte array.

Besides that:

*

*don't use SecureRandom to derive a key, try and lookup PBKDF2;

*explicitly use a mode of operation such as "AES/GCM/NoPadding";

*use a unique IV, and a random IV if you decide to use CBC (usually insecure);

*don't use toByteArray without explicitly selecting a character encoding for the message.

A: The easiest way of implementing AES Encryption and Decryption in Android is to copy this class in your projects.
Encrypt Strings
Please copy the AESUtils class in your project first and then you can use it like this.
String encrypted = "";
String sourceStr = "This is any source string";
try {
    encrypted = AESUtils.encrypt(sourceStr);
    Log.d("TEST", "encrypted:" + encrypted);
} catch (Exception e) {
    e.printStackTrace();
}

Decrypt Strings
String encrypted = "ANY_ENCRYPTED_STRING_HERE";
String decrypted = "";
try {
    decrypted = AESUtils.decrypt(encrypted);
    Log.d("TEST", "decrypted:" + decrypted);
} catch (Exception e) {
    e.printStackTrace();
}

AESUtils Class
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils
{

    private static final byte[] keyValue =
            new byte[]{'c', 'o', 'd', 'i', 'n', 'g', 'a', 'f', 'f', 'a', 'i', 'r', 's', 'c', 'o', 'm'};

    public static String encrypt(String cleartext)
            throws Exception {
        byte[] rawKey = getRawKey();
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }

    public static String decrypt(String encrypted)
            throws Exception {

        byte[] enc = toByte(encrypted);
        byte[] result = decrypt(enc);
        return new String(result);
    }

    private static byte[] getRawKey() throws Exception {
        SecretKey key = new SecretKeySpec(keyValue, "AES");
        byte[] raw = key.getEncoded();
        return raw;
    }

    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKey skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] encrypted)
            throws Exception {
        SecretKey skeySpec = new SecretKeySpec(keyValue, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                    16).byteValue();
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private final static String HEX = "0123456789ABCDEF";

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }
}

A: You can Encrypt and Decrypt in Kotlin like this
first you need:
val SECRET_KEY = "secretKey"
val SECRET_IV = "secretIV"

after that
Encrypt:
private fun String.encryptCBC(): String {
    val iv = IvParameterSpec(SECRET_IV.toByteArray())
    val keySpec = SecretKeySpec(SECRET_KEY.toByteArray(), "AES")
    val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv)
    val crypted = cipher.doFinal(this.toByteArray())
    val encodedByte = Base64.encode(crypted, Base64.DEFAULT)
    return String(encodedByte)
}

and Decrypt:
private fun String.decryptCBC(): String {
    val decodedByte: ByteArray = Base64.decode(this, Base64.DEFAULT)
    val iv = IvParameterSpec(SECRET_IV.toByteArray())
    val keySpec = SecretKeySpec(SECRET_KEY.toByteArray(), "AES")
    val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
    cipher.init(Cipher.DECRYPT_MODE, keySpec, iv)
    val output = cipher.doFinal(decodedByte)
    return String(output)
}

after that you can use it like this:
val strEncrypt = edt.text.toString().encryptCBC()
val strDecrypted = strEncrypt?.decryptCBC()

A: AES Encryption / Decryption using base64 key, salt and iv (Initialization Vector).
object AESEncyption {

const val secretKey = "tK5UTui+DPh8lIlBxya5XVsmeDCoUl6vHhdIESMB6sQ="
const val salt = "QWlGNHNhMTJTQWZ2bGhpV3U=" // base64 decode => AiF4sa12SAfvlhiWu
const val iv = "bVQzNFNhRkQ1Njc4UUFaWA==" // base64 decode => mT34SaFD5678QAZX

fun encrypt(strToEncrypt: String) :  String?
{
    try
    {
        val ivParameterSpec = IvParameterSpec(Base64.decode(iv, Base64.DEFAULT))

        val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
        val spec =  PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256)
        val tmp = factory.generateSecret(spec)
        val secretKey =  SecretKeySpec(tmp.encoded, "AES")

        val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec)
        return Base64.encodeToString(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8)), Base64.DEFAULT)
    }
    catch (e: Exception)
    {
        println("Error while encrypting: $e")
    }
    return null
}

fun decrypt(strToDecrypt : String) : String? {
    try
    {

        val ivParameterSpec =  IvParameterSpec(Base64.decode(iv, Base64.DEFAULT))

        val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
        val spec =  PBEKeySpec(secretKey.toCharArray(), Base64.decode(salt, Base64.DEFAULT), 10000, 256)
        val tmp = factory.generateSecret(spec);
        val secretKey =  SecretKeySpec(tmp.encoded, "AES")

        val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        return  String(cipher.doFinal(Base64.decode(strToDecrypt, Base64.DEFAULT)))
    }
    catch (e : Exception) {
        println("Error while decrypting: $e");
    }
    return null
  }
}

iOS swift

A: Following  MarcForn guide I reduce it like this this:
const val encryptionKey = "ENCRYPTION_KEY"

fun String.cipherEncrypt(encryptionKey: String): String? {
    try {
        val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), "AES")
        val iv = encryptionKey.toByteArray()
        val ivParameterSpec = IvParameterSpec(iv)

        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec)

        val encryptedValue = cipher.doFinal(this.toByteArray())
        return Base64.encodeToString(encryptedValue, Base64.DEFAULT)
    } catch (e: Exception) {
        e.message?.let{ Log.e("encryptor", it) }
    }
    return null
}

fun String.cipherDecrypt(encryptionKey: String): String? {
    try {
        val secretKeySpec = SecretKeySpec(encryptionKey.toByteArray(), "AES")
        val iv = encryptionKey.toByteArray()
        val ivParameterSpec = IvParameterSpec(iv)

        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)

        val decodedValue = Base64.decode(this, Base64.DEFAULT)
        val decryptedValue = cipher.doFinal(decodedValue)
        return String(decryptedValue)
    } catch (e: Exception) {
        e.message?.let{ Log.e("decryptor", it) }
    }
    return null
}


text:
Q: CakePHP 3 : returns true even if data is not fetched from database I'm working in CakePHP 3.2. There is a table user_addresses from which I'm trying to fetch all records of an user
public function myFun()
{
    $this->loadModel('UserAddresses');
    $user_id = $this->Auth->user('id');
    $userAddresses = $this->UserAddresses->find('all', [
       'conditions' => [
           'user_id' => $user_id
       ]
    ]);
    if (empty($userAddresses)) {
       echo 'Hello';               // for testing only
    } else {
       echo 'World';
    }
}

To check it, I added myFun to controller's beforeFilter
$this->Auth->allow(['myFun']);

and this prints World instead of Hello since there is no data retrieved from database because if user is not logged in then $user_id must be empty.

A: First of all check if $user_id is available then and then call find() method.
public function myFun()
{
    $this->loadModel('UserAddresses');
    $user_id = $this->Auth->user('id');
    if(empty($user_id)){
        echo "Not able to access this method";
        die();
    }
    $userAddresses = $this->UserAddresses->find('all', [
       'conditions' => [
           'user_id' => $user_id
       ]
    ]);
    if (empty($userAddresses)) {
       echo 'Hello';               // for testing only
    } else {
       echo 'World';
    }
}


text:
Q: Java - which function is called when inheritance, polymorphism, overloading and overriding are all involved? I have this question involving inheritance, polymorphism, overloading and overriding. I understand all these terms but not sure how they work here. Here's the code:
class A {
    public String show(D obj) {return "A and D";}
    public String show(A obj) {return "A and A";}
}
class B extends A {
    public String show(B obj) {return "B and B";}
    public String show(A obj) {return "B and A";}
}
class C extends B{}
class D extends B{}
public class whatever {
    public static void main(String[] args) {
        A a = new B(); // note the B here
        B b = new B();
        C c = new C();
        D d = new D();
        System.out.println(a.show(a)); // B and A
        System.out.println(a.show(b)); // B and A
        System.out.println(a.show(c)); // B and A
        System.out.println(a.show(d)); // A and D
    }
}

So the task here is to find the output. I have the answers already, those are the comments I put.
I understand the first one, because Java automatically does dynamic binding so a.show() calls the show() from the B class and a is of type A so B.show(A obj) is called.
The last one makes sense too, the show() method is overloaded and since d is of type D, A.show(D obj) is called which is inherited from the A class.
The other two I'm having trouble with. Well I understand that it makes sense because b and c are both A type objects technically, but why does it go with "B and A" over "B and B"?

A: The declared type of a is A.
A has only two methods: one takes an A (and both b and c are instances of A), and the other takes a D (and neither b nor c are instances of D).
So the first method matches, and the second doesn't. So the first method is selected by the compiler.
This method is overridden in B, and the concrete type of a is B, so "B and A" is printed.
The method B.show(B) does not override the method A.show(A), since it doesn't take the same type as argument.

A: Here there is two concepts one is of overloading and other is for overriding . When you create A a = new B(); it mean a is object of B and having a type of A . So when a.show(a) is executed it first encounters show(A obj) and show(B obj) method of class A and then matches the parameter with A type but 'a' is instance of B so the method show(A obj) of class B is executed.
Now when a.show(c) is executed it first encounters show(A obj) and show(B obj) methods of class A and then doesn't finds any match with the parameter of C type inside class A but still it is executed because class C extends B and B extends A.
To summarize it in short ,we can say that
        a.show(a) is equivalent to a.show(b) and is equivalent to a.show(c).


text:
Q: I created 2 threads but I don't get result I am working on .NET CORE 3.1 applications. I have record object of two types which call same method to process data and in return add to same list. I modify code from classic loop to thread. so I created two threads and objective that I can improve performance however if I run both threads I don't get result but if I do just one thread then it do work and get result... not sure what I am missing from puzzle.
Thread processThreadA = new Thread(async () =>
{
    var processedNonInbound= await MethodX(data);

    returnList.AddRange(processedNonInbound);
});

Thread processThreadB = new Thread(async () =>
{
    var processInbound = await MethodX(data);

    returnList.AddRange(processInbound);
});

processThreadA.Start();
processThreadB.Start();

processThreadA.Join();
processThreadB.Join();

Method that called by thread:
private async Task<List<Customers>> MethodX(Record r){
    //.....
}

A: Try this code:
Thread processThreadA = new Thread(async () =>
{
    await Task.Delay(TimeSpan.FromSeconds(5.0));
    Console.WriteLine($"{DateTime.Now} A");
});

Thread processThreadB = new Thread(async () =>
{
    await Task.Delay(TimeSpan.FromSeconds(5.0));
    Console.WriteLine($"{DateTime.Now} B");
});

processThreadA.Start();
processThreadB.Start();

Console.WriteLine($"{DateTime.Now} Started");

processThreadA.Join();
processThreadB.Join();

Console.WriteLine($"{DateTime.Now} Joined");

It outputs:
2022/03/22 18:37:32 Started
2022/03/22 18:37:32 Joined
2022/03/22 18:37:37 B
2022/03/22 18:37:37 A

Effectively the threads start and as soon as they hit an await they return control to the calling code - hence the Join completes - and after the delay is completed the code then continues.
Now try the same thing, but with tasks:
Task processTaskA = Task.Run(async () =>
{
    await Task.Delay(TimeSpan.FromSeconds(5.0));
    Console.WriteLine($"{DateTime.Now} A");
});

Task processTaskB = Task.Run(async () =>
{
    await Task.Delay(TimeSpan.FromSeconds(5.0));
    Console.WriteLine($"{DateTime.Now} B");
});

Console.WriteLine($"{DateTime.Now} Started");

Task.WaitAll(processTaskA, processTaskB);

Console.WriteLine($"{DateTime.Now} Joined");

That gives:
2022/03/22 18:40:33 Started
2022/03/22 18:40:38 A
2022/03/22 18:40:38 B
2022/03/22 18:40:38 Joined


text:
Q: VNC into an existing X2Go LXDE session I'm trying to VNC into an already running LXDE session, started through X2Go.
This is a remote VM, running Debian.
I'm usually using X2Go client for Windows but sometimes need to log on through Android (which doesn't have a native client) or another machine that doesn't have X2Go but usually has some sort of VNC viewer.
I've already set up X11vnc and can connect normally to the currently running session.
The problem is that it only works while the X2Go client connected too.
If it's just the VNC viewer, it gets one screen update but never refreshes.
I'm pretty sure it has to do with the specific session getting suspended when X2Go disconnects, but don't know where to go from there.


text:
Q: Cannot find Aptana Preview button in Eclipse I cannot find out aptana preview in my eclipse,
after installing aptana plugin to my eclipse.
Eclipse version is Luna.
In every tutorial sites, show preview button between terminal and apatana start page. But I cannot find it. Can anybody tell me how to solve it.

A: I think it's displayed only if the current opened file is a html or a webpage


text:
Q: Conflict with Local and Domain Policy for Remote Desktop I am running Windows Server 2003 domain and implementing the Remote Desktop Users group without any problems to manage who has access to remote into the Domain Controller.
I recently set up a virtual machine running Windows XP for users to remote into to work from home.  Right now only domain administrators can log in.  For other users, even those that are members of the Remote Desktop Users group, I get
"The local policy of this system does not permit you to logon interactively"
I know that I can get edit the local policy to add users but is there a way I can get it to use AD to allow logons based on the user group I already have?

A: It sounds like you've got a GPO linked in your domain that is altering the "Allow logon through Terminal Services" user right. A quick inspection of the "User Rights Assignment" settings under "Local Policies" under "Security Settings" in the "Windows Settings" node of "Computer Configuration" in a "Resultant Set of Policy" would confirm if this is the case.
Generally I don't recommend playing around with this user right for exactly the reasons you're seeing-- it "breaks" the default behavior of the "Remote Desktop Users" group.
Once you know if this is what's happening you can make an informed decision about changing the GPO to prevent what you're seeing from happening.


text:
Q: How can I use comparison operators in PowerShell to compare values in cells I would like to compare the values of adjacent cells in two columns (wind Speed and Gust) in a CSV file and if the value of the cell in the Gust column is less than the value of the adjacent cell in the Speed column, replace the value of the cell in the Gust column with that of the Speed. For example, my file might look like:
Time    Speed   Gust
22:06   6.1 12.7
22:07   6.3 5.2
22:08   7.2 6.9
22:09   11.1    10.3
22:10   5.9 6.9
22:11   6   16.1
22:12   6.3 12.7

For the times of 22:07, 22:08, and 22:09, the wind Gust is less than the wind Speed and they are the only Gusts that should be changed. However, for the times of 22:06, 22:11 and 22:12 in which the gust is greater than 10, those Gusts are changed to be equal to the Speed resulting in:
Time    Speed   Gust
22:05   6.1 8.1
22:06   6.1 6.1
22:07   6.3 6.3
22:08   7.2 7.2
22:09   11.1    11.1
22:10   5.9 6.9
22:11   6   6
22:12   6.3 6.3

My code is:
$data = Import-Csv 'C:\customfiles\speed.csv'

foreach ($datum in $data) {
    if ($datum.Gust -le $datum.Speed) {$datum.Gust = $datum.Speed}
    }

$data | Export-Csv 'C:\customfiles\speed-new.csv' -NoTypeInformation

I would expect that using the -le comparison operator would result in only values of Gusts less than or equal to the Speed being changed to match the speed, but if the Gust is greater than 10, the code identifies that cell as less than or equal to the Speed, even if the Gust is greater than the Speed, and then it changes the correct Gust to that of the Speed. Is there a different way to use the comparison operator to avoid this issue?

A: The type of objects you are comparing is string, so you're getting results based on alphabetic order.
You need to convert it into some numeric type, e.g. decimal:
if ([decimal]$datum.Gust -le [decimal]$datum.Speed) {$datum.Gust = $datum.Speed}


text:
Q: Init a 3 dimensional array with 2 dimensional arrays Sorry if this may seem like a stupid question.
I had this code:
char array1[2];
char array2[2];
char array3[2];

char *array[] = {
array1,
array2,
array3,
}

Now I changed array1,array2,array3 to be a 2 dimensional array:
char array1[2][2];
char array2[2][2];
char array3[2][2];

And I get the following error:
error: cannot convert 'char (*)[2]' to 'char*' in initialization
How can I init array with 2 dimensional array?
I also tried the following which didn't work:
char *array[2][2] = {
    array1,
    array2,
    array3,
    }

char array[][2][2] = {
    array1,
    array2,
    array3,
    }

Thanks!

A: C++11 makes this easy:
char array1[2][2];
char array2[2][2];
char array3[2][2];

std::decay<decltype(array1)>::type array[] = {
  array1,
  array2,
  array3,
};

which is the equivalent of the (unreadable in my opinion) syntax
char (* array [])[2] = {
  array1,
  array2,
  array3,
};

The rules, as usual, are the same you can find in every decent C++ book:

*

*Operator precedence

*Type decaying


text:
Q: How to add Main Menu and Retry menu in pygame I am working in Python and developing a game using the popular library Pygame. I have developed it completely but but now I want to add a menu which contains a picture behind it and has 3 buttons 'Play', 'Instructions' and 'Credits'. I want the game to start on pressing 'Play' and some text to appear on clicking 'Instructions' & 'Credits'. After that I want a 'Retry' button to appear on my game over display. If you know how to do so, please tell me.

A: This is easy to do
First make sure your game is in a function like
def startgame():
   content.....

This is necessary to do and a after that define a function for a button and in the button function write:
def button(x,y,w,h):
    pos = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if pos[0] > x and pos[0] < x + w and pos[1] > y and pos[1] < y + h:
       if click[0] == 1:
         startgame()
    pygame.draw.rect(screen, color, (x,y,w,h))

In this way you can create a button,
Next create a menu function like:
def menu():

 while True:

    surface.blit(background, (0, 0))

    button(x,y,w,h)

    for event in pygame.event.get():
       if event.type == pygame.QUIT:
           pygame.quit()
           sys.exit()
    pygame.display.update()

menu()


text:
Q: Alamofire GET request with parameters, -> "extra argument in call" I am trying to make a GET request using Alamofire with parameters to a backend written in python.
I tried several ways of doing this with no success and i read somewhere that i should remove parameters in order to get a clean GET request and it worked.
I still need to use parameters so i saw this post:  Get JSON result with GET request and parameters with Alamofire
Trying the solution there, Xcode gives me an instant error: extra argument in call
This is how it looks like when i get my error:
 Alamofire.request(.GET, urlString, parameters: ["test":"te"]).responseJSON {
            (responseObject) -> Void in

            print(responseObject)

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                success(resJson)
            }
            if responseObject.result.isFailure {
                let error: NSError = responseObject.result.error!
                failure(error)
            }
        }

A: You just have wrong order of parameters and for parameter method you forgot to write parameter name.
Change this
Alamofire.request(.GET, urlString, parameters: ["test":"te"]).responseJSON {

to this
Alamofire.request(urlString, method: .get, parameters: ["test":"te"]).responseJSON {

You can anytime check function parameters when you jump to its definition. Just hold Command and click to function and select Jump to Definition

now you can see request method parameters


text:
Q: [TimePicker][React] Material UI - How to add simple HH:MM above the clock face? I try add simple text of selected hour "HH:MM" like in design in picture:

My code looks like:
              <LocalizationProvider dateAdapter={AdapterDayjs}>
                <TimePicker
                  className={classes.timePicker}
                  value={minHour}
                  ampm={false}
                  openTo="hours"
                  showTodayButton
                  inputVariant="outlined"
                  onChange={(newHour) => {
                    setMinHour(newHour);
                  }}
                  renderInput={(params) =>


text:
Q: Set up the jobs of CI in a VM server instead of docker image GitLab CI is highly integrated with Docker. But in some cases the applications need some interactions with some app (which cannot be deployed in docker)
so i want to make my jobs (on gitlab-ci.yml) be running on a Linux VM Server.
how can i set up that in Gitlab? i searched in many website but i didn't find the answer.
thanks you

A: You can use different executors with Gitlab. For your case, you should set up Gitlab Runner as shell executor and register it (provide it with token obtained from repo)
https://docs.gitlab.com/runner/install/linux-repository.html


text:
Q: C# Streamreader problems I'm building a program that has you input a number and remembers it when you re-open the program. It uses a text file to save the number in. I'm using streamreader to read the text file to get the number you entered last, but it always throws an exception. Where should I put the text file or change my code so it can read and edit the text? Here is my code:
namespace Cookie_Clicker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void tb_TextBox(object sender, RoutedEventArgs e)
        {

        }

        private void add_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (StreamReader sr = new StreamReader("cookies.txt"))
                {
                    int data = Convert.ToInt16(sr.ReadToEnd());
                    tb.Text = Convert.ToString(data + 1);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Your cookie text file is missing!");
            }
        }

        private void reset_Click(object sender, RoutedEventArgs e)
        {

        }
    }

}

A: To answer your question:

Where should I put the text file...?

You haven't specified a path to cookies.txt so the program will look for it in the same directory where it's running. If you change cookies.txt to include a path, for example C:\dev\cookies.txt, then you can store the file wherever you like.
That will allow you to get past the file not found error and address any other problems you have in there.

A:
Every time it says "Your cookie text file is missing!"

Problem 1: You are not specifying proper path of your input file.
Solution 1: You need to get the Currentpath of your application from where it is running and then combine it with the filename using Path.Combine() method.
Try This:
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cookies.txt");
using (StreamReader sr = new StreamReader(path))
{
    int data = Convert.ToInt16(sr.ReadToEnd());
    tb.Text = Convert.ToString(data + 1);
}

Suggestion : You need to always display the Error message in Catch block to identify the problem.
You can call ToString() on  Exception object to get the complete exception info.
catch (Exception ex)
{
    MessageBox.Show(ex.ToSTring();
}


text:
Q: Reading specific excel sheet into Python pandas dataframe without loading the whole workbook pd.read_excel(filepath, sheetname) and openpyxl.Workbook(filepath) load the whole workbook. I have a 30MB file on a server and it takes a long time to load. I was wondering if there was a method to load a specific sheet as a pandas dataframe without opening the whole workbook.
I have looked into a couple of methods. Most recently, converting the workbook to a .zip and reading the .xml files. I know that people have suggested using lxml. I'm not sure how to go from here.
Is there a better way of doing this?


text:
Q: Why is this combination of HTML and CSS to set font color and style failing? I am trying to put some red, italicized text (label) on a page:
HTML
Enter numeric values only

CSS
.reditalic {
  color: "red";
  font-style: "italic";
}

...but it fails, with:
"Uncaught SyntaxError: Unexpected token YInfoReceiver.doXhr.xo.onfinish @ sockjs-0.3.4.js:2018EventEmitter.emit @ sockjs-0.3.4.js:151AbstractXHRObject._start.that.xhr.onread"
and, "Uncaught SyntaxError: Unexpected token Y"
in the Browser (Chrome) Console, and "Your application has errors. Waiting for file change." in the console when running "meteor" in the directory of the app.
I also tried this (no quotes around "italic"):
.reditalic {
  color: "red";
  font-style: italic;
}

...and this ("oblique" instead of "italic"):
.reditalic {
  color: "red";
  font-style: oblique;
}

...and this ("font-color" instead of "font"):
.reditalic {
  font-color: "red";
  font-style: italic;
}

...and this (no quotes around "red"):
.reditalic {
  font-color: red;
  font-style: italic;
}

It runs fine when I remove the HTML and the CSS shown above.
UPDATE
The problem was that the HTML was in "limbo":

Enter numeric values only

I changed it to this:

Enter numeric values only

...and the errors disappeared. It's still not displaying on the page, though, for some reason, even after saving the changes in the HTML file and refreshing the page.
Whether I use this:
color: red;

...or this:
color: "red";

...in the CSS, it makes no difference - the label does not display. For "full disclosure" here is the pertinent CSS:
.reditalic {
  color: red;
  font-style: italic;
}

..and HTML:

    <title>Duckbilled Platypi R People 2!</title>

. . .
Enter numeric values only

What may or may not be a problem is that when I modify and save the HTML or CSS, I see this in the console:
Client modified -- refreshing

...but it never gets to the:
App running at: http://locohost:3000/
Type Control-C twice to stop.

...message...and yet it is really refreshing - I made a test change to the title, and it did change, so...???

A: There is no font-color attribute in css. It's just color.
The quotes around italic and red are also optional but not the source of your problem.


text:
Q: convert all image into separate video using moviepy python I have 10 images in a folder under current directory of where my python script is stored. I want to convert all my 10 images into 10 videos with the same file name (or) existing filename+suffix(somename).mp4   .   The problem is the below script is converting either all images into one video or erroring out. Need help to fix my problem .
Error :
Traceback (most recent call last):
File "1.py", line 17, in
video.write_videofile(filename, prefix+".mp4", fps=24)
TypeError: write_videofile() got multiple values for argument 'fps'
    import os
    from moviepy.editor import *
    base_dir = os.path.realpath(".")
    print(base_dir)
    directory=sorted(os.listdir('.'))
    print(directory)
    clips = []
    for filename in directory:
      if filename.endswith(".jpg"):
        prefix = filename.split(".jpg")[0]
        clips.append(ImageClip(filename).set_duration(1))
    print(clips)
    video = concatenate(clips, method="compose")
    video.write_videofile(filename, prefix+".mp4", fps=24)

A: The error is complaining that it is receiving to many arguments.
Try running the write_videofile without the filename argument. The signature only accepts one positional argument which should be the file you are writing to.
video.write_videofile(prefix+".mp4", fps=24)

docs


text:
Q: How to use Apollo Client with AppSync? AppSync uses MQTT over WebSockets for its subscription, yet Apollo uses WebSockets. Neither Subscription component or subscribeForMore in Query component works for me when using apollo with AppSync.

One AppSync feature that generated a lot of buzz is its emphasis on
  real-time data. Under the hood, AppSync's real-time feature is powered
  by GraphQL subscriptions. While Apollo bases its subscriptions on
  WebSockets via subscriptions-transport-ws, subscriptions in GraphQL
  are actually flexible enough for you to base them on another messaging
  technology. Instead of WebSockets, AppSync's subscriptions use MQTT as
  the transport layer.

Is there any way to make use of AppSync while still using Apollo?

A: Just to add a note about the authentication as it took me a while to work this out:
If the authenticationType is "API_KEY" then you have to pass the apiKey as shown in @C.Lee's answer.
  auth: {
    type: config.aws_appsync_authenticationType,
    apiKey: config.aws_appsync_apiKey,
  }

If the authenticationType is "AMAZON_COGNITO_USER_POOLS" then you need the jwkToken, and
if you're using Amplify you can do this as
  auth: {
    type: config.aws_appsync_authenticationType,
    jwtToken: async () => {
      const session = await Auth.currentSession();
      return session.getIdToken().getJwtToken();
    }
  }

But if your authenticationType is "AWS_IAM" then you need the following:
  auth: {
    type: AUTH_TYPE.AWS_IAM,
    credentials: () => Auth.currentCredentials()
  }

A: Ok, here is how it worked for me. You'll need to use aws-appsync SDK (https://github.com/awslabs/aws-mobile-appsync-sdk-js) to use Apollo with AppSync. Didn't have to make any other change to make subscription work with AppSync.
Configure ApolloProvider and client:
    // App.js
    import React from 'react';
    import { Platform, StatusBar, StyleSheet, View } from 'react-native';
    import { AppLoading, Asset, Font, Icon } from 'expo';
    import AWSAppSyncClient from 'aws-appsync' // <--------- use this instead of Apollo Client
    import {ApolloProvider} from 'react-apollo'
    import { Rehydrated } from 'aws-appsync-react' // <--------- Rehydrated is required to work with Apollo

    import config from './aws-exports'
    import { SERVER_ENDPOINT, CHAIN_ID } from 'react-native-dotenv'
    import AppNavigator from './navigation/AppNavigator';

    const client = new AWSAppSyncClient({
      url: config.aws_appsync_graphqlEndpoint,
      region: config.aws_appsync_region,
      auth: {
        type: config.aws_appsync_authenticationType,
        apiKey: config.aws_appsync_apiKey,
        // jwtToken: async () => token, // Required when you use Cognito UserPools OR OpenID Connect. token object is obtained previously
      }
    })

    export default class App extends React.Component {
      render() {
        return <ApolloProvider client={client}>
          <Rehydrated>
            <View style={styles.container}>
              <AppNavigator />
            </View>
          </Rehydrated>
        </ApolloProvider>
    }

Here is how the subscription in a component looks like:
    <Subscription subscription={gql(onCreateBlog)}>
      {({data, loading})=>{
        return <Text>New Item: {JSON.stringify(data)}</Text>
      }}
    </Subscription>


text:
Q: Python3 : Print returned values from the function in another file I am working on a Jupyterhub project and beginner Python user. I would like to print returned values from the function in another py file for dubug.
a.py:
class TestSpawner(SlurmSpawner):
    def _options_form_default(self):
        return """
        node type
        <select name="queue">
          <option value="standard">standard</option>
          <option value="dev-test">TEST</option>
        </select>
        Job duration
        <select name="runtime">
          <option value="1:00:00">1 hour</option>
          <option value="2:00:00">2 hours</option>
        </select>
        """
    def options_from_form(self, formdata):
        print ( formdata.get('queue', [''])[0].strip())
        options = {}
        options['queue'] = formdata.get('queue', [''])[0].strip()
        options['runtime'] = formdata.get('runtime', [''])[0].strip()
        print (options)
        return options

b.py:
import sys
from a import *
print (options)
print (queue)

I can see the queue and options values using print (options) in a.py, but I am not sure how I can print the values in b.py and make sure it gets correct values from a.py. Please help me and Thanks.

A: Import your module, make an instance, and call the method in b.py:
import a

spawner = a.TestSpawner()

formdata = 'my form data'  # add your data here
print(options_from_form(formdata))


text:
Q: How to concatenate two column in talend tMap I have two column SalesID (Long 10 digit) and ItemID(Varchar 6) Now I want to concatenate these two column to make a 16 digit.
For example-  SalesID = 1234567899
              ItemID  = 32X9

  Desired concatenated value should be:- 12345678990032X9

How can I achieve about output through tMap in talend?

A: Using Java syntax, you can easily concatenate your input data in the Tmap component:

A: Hi you can do it using tJavaRow component
put below logic into it
output_row.SALESID = input_row.SALESID;
output_row.ITEMID = input_row.ITEMID;
output_row.ITEMID_ZERO = String.format("%6s",input_row.ITEMID).replace(' ','0');

output_row.CONCATENATE = output_row.SALESID+""+output_row.ITEMID_ZERO;


text:
Q: Where is /system/bin/linker from NDK toolchain when cross compiling I am attempting to build an autoconf project against the NDK toolchain on a CentOS host, so I can use the shared objects generated as part of a native-lib android application.
While compiling, I am receiving errors about a missing /system/bin/linker64 file. (bad ELF interpreter: No such file or directory)
Is this part of the NDK toolchain, and I can just sym-link /system/bin/linker64 to something in the toolchain, or to my CentOS dynamic linker, or what?
I set up my environment with:
$NDK/build/tools/make_standalone_toolchain.py \
  --arch x86_64\
  --api 26 \
  --install-dir=my-toolchain

and I have sourced this file to set my environment:
# Add the standalone toolchain to the search path.
export PATH=$PATH:`pwd`/my-toolchain/bin

# Tell configure what tools to use.
target_host=x86_64-linux-android
export AR=$target_host-ar
export AS=$target_host-clang
export CC=$target_host-clang
export CXX=$target_host-clang++
export LD=$target_host-ld
export STRIP=$target_host-strip

# Tell configure what flags Android requires.
export CFLAGS="-fPIE -fPIC"
export LDFLAGS="-pie

I have run run my configure script with
./configure --host=$target_host ....

A: Nowhere. That's not a part of the toolchain.
If you're seeing that as part of your build, it means something tried to run an Android binary on your host. That shouldn't have happened.
My guess: your autoconf project is set up to run the "does the compiler work" test binary, and doesn't understand that x86_64 Android is not the same as x86_64 GNU/Linux. I've seen this problem in other projects (gdbserver is the one that comes to mind).
You'll need to look closer at what is being run and why; there isn't enough information here to say with certainty what you need to fix.


text:
Q: ORDER BY before WHERE - alternatives? I'm using a PostgreSQL database (12.8).
Given events sorted by start_time, I would like to retrieve the next 10 events after the event with id = 10.
My first idea was something like this:
SELECT *
FROM events
ORDER BY start_time
WHERE id > 10
LIMIT 10;

However, this does not work because the WHERE-clause is always applied before the ORDER BY-clause. In other words, first all events are selected which have an id > 10, and only the remaining events are then ordered by start_time.
Next, I came up with a CTE expression. If the record with ID 10 has row_number 3:
WITH ordered_events AS (
  SELECT id, ROW_NUMBER() OVER (ORDER BY start_time DESC) AS row_number
  FROM events
)
SELECT *
FROM ordered_events
WHERE row_number > 3
LIMIT 10;

This works as desired, if I would know the row_number beforehand. However, I only know the ID, i.e. id = 10.
a) Ideally, I would do something like this (however, I don't know if there is any way to write such an expression):
WITH ordered_events AS (
  SELECT id, ROW_NUMBER() OVER (ORDER BY start_time DESC) AS row_number
  FROM events
)
SELECT *
FROM ordered_events
WHERE row_number > (row_number of row where the ID is 10) # <------
LIMIT 10;

b) The only alternative I came up with is to first retrieve the row_number for all records and then make a second query.
First query:
SELECT id, ROW_NUMBER() OVER (ORDER BY start_time DESC) AS row_number
FROM events;

Now I know that the row_number for the record with ID 10 is 3. Thus, I have enough information to make the query with the CTE expression as described above. However, the performance is bad because I need to retrieve all records from events in the first query.
I would really appreciate it, if you could help me to figure out a (performant) way of doing this.

A: You only want rows with a start time less than ID 10's start time. Use a WHERE clause for this.
select *
from events where start_time < (select start_time from events where id = 10)
order by start_time desc
limit 10;

This query may benefit from an index on start_time. (I take it for granted that there already is an index on ID to find the row with ID 10 quickly.)


text:
Q: How do you fix the grub rescue I deleted the Ubuntu partition via Windows and was going to use an USB to re download and install it. But when I restarted the computer the unknown file system and grub rescue screen came up.
Now, I can't even start up Windows. I'm just stuck on the grub rescue screen and I have no idea how to fix it and I'm a complete beginner.

A: You can use Super Grub2 Disk to repair the boot section (in case that you deleted or corrupted grub when you deleted Ubuntu partition) as the description specifies:

The primary purpose of Super GRUB2 Disk is to help you boot into an OS
  whose bootloader is broken. Second, and almost as important, is to be
  a tool to learn more about GRUB2 and the booting process.

http://www.supergrubdisk.org/super-grub2-disk/
Else, you can use a Windows Repair Disk if something more is broken in the Windows boot sequence.

A: You can either:

*

*Use a Windows Repair Disk to restore MBR.

*Use a LiveUSB of Ubuntu to install it again.

If you do not have any of them but there is another computer available, you may use that one to create a Windows Repair disk or an Ubuntu LiveUSB (or both).
Good luck.


text:
Q: java sed command not producing response SED command is not executing when I'm trying it to execute with Java, while it is getting executed successfully manually. No response & no error is seen in output.
My SED Command:
Manually:
sed -i 's/abc/xyz/' /home/tmp.txt

In java file:
String[] cmdtest = {"sed ", "-i","'s/abc/xyz/'"," /home/tmp.txt"};

Process:
StringBuffer output = new StringBuffer();
Process p = null;
try {
    p = Runtime.getRuntime().exec(cmdtest);
    p.waitFor();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
    }

} catch (Exception e) {
        e.printStackTrace();
}

A: You first waitFor the process to end, then proceed to read its output. You must take the output while the process is running; otherwise its output buffer will fill up and then the process will block until you  drain it. So just remove waitFor and it will start working.
Further, beyond the Java aspect of this question, I see problems in how you have constructed the command line:
{"sed " + "-i","'s/abc/xyz/'"," /home/tmp.txt"}

*

*the first element is "sed -i"—obviously you meant for -i to be the first argument, not a part of the command name.

*you have '...' around the second argument: this will be passed literally to sed, making it an invalid command specification. Quotes are only needed at the shell prompt.

*The last argument has an extra space in front, which could lead to problems as well.

*Calling sed with -i orders it to make changes to the file in-place, producing no output at all.

So probably you wanted instead
{"sed", "s/abc/xyz/", "/home/tmp.txt"}

A: The line
 String[] cmdtest = {"sed " + "-i","'s/abc/xyz/'"," /home/tmp.txt"};

is faulty.

*

*The name of the program you want to runs is sed, not sed-i.

*The SED script you want to run is s/abc/xyz/, not 's/abc/xyz/' (note the quotes).

*The path-name of teh file you want to edit is /home/tmp.txt, not /home/tmp.txt (note the extra space).

Try this:
 String[] cmdtest = {"sed", "-i","s/abc/xyz/","/home/tmp.txt"};

A: raedwald & marko gave correct answers. use
String[] cmdtest = {"sed", "-i","s/abc/xyz/","/home/tmp.txt"};

thanks


text:
Q: Setting up expression for distance of random point to origin
Problem Statement:
Suppose that the coordinates of a point $(X, Y)$ are such that
  $X ∼ U[0, 1)$ and $Y ∼ U[0, 1)$
  Compute the probability that the distance
  from this point to the origin is less than or equal to L. You should consider the two cases when
$0 \leq L \leq 1$ and $1 \leq L \leq \sqrt{2}$

I'm having troubles just trying to set up the density function here because there are so many inequalities. I'm new to stats so this might just be an easy problem that I didn't see


text:
Q: curl a url and get only body back not entire html file I have the url mydomain.com/get
At that url I serve an index.html.
That index.html looks like this:
<!DOCTYPE html>
    <body>
        12345
    </body>
</html>

I'd like to use bash to return 12345. I'm doing this via jenkins so I can't install specific things. I was thinking grep?
curl mydomain.com/get | grep ???

A: Note: your HTML doesn't look like valid XML. I have changed it to this:
<!DOCTYPE html>
<html>
    <body>
        12345
    </body>
</html>

Using XMLstarlet (xml) you can now extract the value of the body element with
$ curl mydomain.com/get | xml select -t -v /html/body

        12345

A: With a shell that supports process substitution (such as bash) and if you have xmllint you can write something like:
echo 'cat //*[local-name()="body"]/text()' | xmllint --shell <(curl mydomain.com/get) | grep -v '^/ >'

Please note this will only return the text value in the <body> tag. If you have a more complex page you'll need a more advanced command.

A: Try
sed -n '/<body>/,/<\/body>/p'. This should find the text between the starting and end body tags.


text:
Q: How to read columns of .txt data with pandas and feed to TF I have a file birth_life_data.txt with the format as:
Country fertiliy_rate Life_span
India 5.7 52
USA 10.2 70
...
...

I want to store the fertiliy_rate data in the variable X, and life_span similarly in Y as 1-d arrays, to fed as training data in my TF graph.
How do i use pandas to parse this data and store it in the form of a python array?

A: You can use the read_table() function in pandas to read a text file.
df = pd.read_table('birth_life_data.txt', delim_whitespace=True)

You can then use the inbuilt list() function to convert them to python arrays.
X = list(df['Country'])
Y = list(df['Life_span'])


text:
Q: How can I create a view that could hold either an image or a video? In my app, users can either take a picture or record a video. The file is then saved and its path is passed through an intent to the next activity, which displays it for editing.
My question is, how can I easily use the same view for either a video or an image?
I tried dynamically adding a view at runtime when I know what the file type is, but it turned out to be too hard to configure, not to mention the issues that VideoViews have with being rotated.
Edit:
I forgot to mention that using the same view would be preferable, since I'm not actually going to do anything to the contents that's specific to each kind of view.

A: Add both the ImageView and VideoView in your layout. Then set the visibility to GONE or VISIBLE for the one you want.

A: You can create two child views, one for the image and one for the video. And depending on the type of your view you can hide/show your child views.

A: You can also use FrameLayout for this

A: By using frame layout / Relative layout you can place a view on top of another view. After creating the views like i mention and using the visibility Gone & Visible you can manage to handle it..
 <FrameLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content">

 <ImageView
    android:id="@+id/ImageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_drawable"
    android:scaleType="fitCenter"
    android:visibility="gone"/>

   <VideoView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="bottom|center"
      android:padding="5dp"
      android:id="@+id/VideoView"
      android:visibility="gone"/>

</FrameLayout>

Then based on your usage you can control it dynamically like below
   // register the views
   ImageView mImageView= (ImageView)findViewById(R.id.ImageView);
   VideoView mVideoView= (VideoView)findViewById(R.id.VideoView);

 // check your conditions like show video view r image view here

 if(VideoView)
 {
   mVideoView.setVisibility(View.VISIBLE);
   mImageView.setVisibility(View.GONE);
 }
 else if(ImageView)
 {
   mImageView.setVisibility(View.VISIBLE);
   mVideoView.setVisibility(View.GONE);
 }

Hope it will work for you :)


text:
Q: Qt Designer how to design/create custom Widget? I mean how to design custom Widget in Qt Designer?
Not "Creating Custom Widgets for Qt Designer" or "Integrating Custom Widgets with Qt Designer".
E.g. I want to design a custom Widget as the following picture, and it is a subclass of QWidget, so I can dynamically insert this custom Widget directly to my Window later on.

But Qt Designer generate a ui_Form(object) class:
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
    QMetaObject, QObject, QPoint, QRect,
    QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
    QFont, QFontDatabase, QGradient, QIcon,
    QImage, QKeySequence, QLinearGradient, QPainter,
    QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QHBoxLayout, QLabel, QLineEdit,
    QSizePolicy, QSpacerItem, QWidget)

class Ui_Form(object):
    def setupUi(self, Form):
        if not Form.objectName():
            Form.setObjectName(u"Form")
        Form.resize(400, 300)
        self.horizontalLayout = QHBoxLayout(Form)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.label = QLabel(Form)
        self.label.setObjectName(u"label")

        self.horizontalLayout.addWidget(self.label)

        self.label_2 = QLabel(Form)
        self.label_2.setObjectName(u"label_2")

        self.horizontalLayout.addWidget(self.label_2)

        self.label_3 = QLabel(Form)
        self.label_3.setObjectName(u"label_3")

        self.horizontalLayout.addWidget(self.label_3)

        self.lineEdit = QLineEdit(Form)
        self.lineEdit.setObjectName(u"lineEdit")
        self.lineEdit.setReadOnly(True)

        self.horizontalLayout.addWidget(self.lineEdit)

        self.horizontalSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.horizontalLayout.addItem(self.horizontalSpacer)

        self.retranslateUi(Form)

        QMetaObject.connectSlotsByName(Form)
    # setupUi

    def retranslateUi(self, Form):
        Form.setWindowTitle(QCoreApplication.translate("Form", u"Form", None))
        self.label.setText(QCoreApplication.translate("Form", u"TextLabel", None))
        self.label_2.setText(QCoreApplication.translate("Form", u"TextLabel", None))
        self.label_3.setText(QCoreApplication.translate("Form", u"TextLabel", None))
    # retranslateUi

In order to use this generated file ui_Form.py, I have to create a separated MyWidget(QWidget) class to load the ui:
from PySide6.QtWidgets import QWidget

from ui_Form import Ui_Form

class MyWidget(QWidget):

    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)


text:
Q: Retrive data from array & Store as variable using php Actually I can't understand how I will explain my problem. I am trying to give an example. In my php code I got a array like this:
Array ( [0] => E-mail [1] => Newsletter )
I want to retrieve all the value from this array & want to store it in $result. I tried with foreach function. But I can't store all the result in $result as because it's changing each time & printing separate value. Anyone can help me please. Thanks in advance.

A: foreach ($array as $k => $v) {
    $result .= $v;
}

echo $result;