text:
Q: Can't update language of doc file I've extracted the POIXMLProperties from my document(template created locally) and I see the language property exist with a value (the system language) but I can't modify it as the POIXMLProperties don't let you do it as described in the api doc.
Here is the full code:
public InputStream updateMetadata(String extension,
                                    InputStream source,
                                    Date created,
                                    String creator,
                                    String language) throws IOException {

File tempFile = File.createTempFile("editor-document", ".tmp");
    try (POIXMLDocument document = getDocument(source, extension);
         FileOutputStream fos = new FileOutputStream(tempFile))
    {
      POIXMLProperties props = document.getProperties();
      POIXMLProperties.CoreProperties coreProps = props.getCoreProperties();
      coreProps.setCreator(creator);
      coreProps.setCreated(metadataFormat.format(created));
      document.write(fos);
    }
}

Is there any solution to change the language property, please?
Note that I set the doc template language to none (from tools > options inside the doc)


text:
Q: Please I need help, how can I solve this heat impulsive system? Please I need your help!!
I need to solve the following system:
$$
    \left\{\begin{array}{ll}
    \partial_{t} \psi(x,t)-\Delta \psi(x,t)=0, & (x,t)\in (0,1) \times((0, 2) \backslash\{1\}) \\
    \psi(0,t)= \psi(1,t)=0, & t \in  (0, 2) \\
    \psi(x, 0)= x (1-x), & x \in (0,1) \\
    \psi(x, 1)=\psi\left(x, 1^{-}\right)+4, & x \in (0,1)
    \end{array}\right.
    $$
$1^{-}$  denotes the limit to the left!
Best regards,

A: I think that this is what you want. Mathematica 12.3 solves it in several minutes:
sol = DSolveValue[{D[u[x, t], t] ==
    D[u[x, t], {x, 2}] + DiracDelta[t - 1], u[0, t] == 0,
   u[1, t] == 0, u[x, 0] == x (1 - x)}, u[x, t], {x, t}]

Result is returned an two inactive sums:
FullSimplify[sol /. K[1] -> n, t ∈ Reals]

Inactive[Sum][-((4 (-1 + (-1)^n) E^(-n^2 π^2 t) Sin[n π x])/(n^3 π^3)), {n, 1, ∞}] +
 Inactive[Sum][-((2 (-1 + (-1)^n) E^(-n^2 π^2 (-1 + t))
     HeavisideTheta[-1 + t] Sin[n π x])/(n π)), {n, 1, ∞}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: KryoSerializer cannot find my SparkKryoRegistrator I am using Spark 2.0.2 on Amazon emr-5.2.1 in client mode. I use Kryo serialisation and register our classes in our own KryoRegistrator:
val sparkConf = new SparkConf()
    .set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
    .set("spark.kryo.registrator", classOf[de.gaf.ric.workflow.RicKryoRegistrator].getName)
    .set("spark.kryo.registrationRequired", "true")
    .set("spark.kryoserializer.buffer.max", "512m")
implicit val sc = new SparkContext(sparkConf)

The process starts fine, but after some minutes, I get the following exception on the executors:
17/02/02 16:22:34 ERROR RetryingBlockFetcher: Failed to fetch block rdd_3641_12, and will not retry (0 retries)
java.lang.RuntimeException: org.apache.spark.SparkException: Failed to register classes with Kryo
    at org.apache.spark.serializer.KryoSerializer.newKryo(KryoSerializer.scala:129)
    at org.apache.spark.serializer.KryoSerializerInstance.borrowKryo(KryoSerializer.scala:274)
    at org.apache.spark.serializer.KryoSerializerInstance.<init>(KryoSerializer.scala:259)
    at org.apache.spark.serializer.KryoSerializer.newInstance(KryoSerializer.scala:175)
    at org.apache.spark.serializer.SerializerManager.dataSerializeWithExplicitClassTag(SerializerManager.scala:141)
    at org.apache.spark.storage.BlockManager.org$apache$spark$storage$BlockManager$$doGetLocalBytes(BlockManager.scala:499)
    at org.apache.spark.storage.BlockManager$$anonfun$getLocalBytes$2.apply(BlockManager.scala:474)
    at org.apache.spark.storage.BlockManager$$anonfun$getLocalBytes$2.apply(BlockManager.scala:474)
    at scala.Option.map(Option.scala:146)
    at org.apache.spark.storage.BlockManager.getLocalBytes(BlockManager.scala:474)
    at org.apache.spark.storage.BlockManager.getBlockData(BlockManager.scala:280)
    at org.apache.spark.network.netty.NettyBlockRpcServer$$anonfun$2.apply(NettyBlockRpcServer.scala:60)
    at org.apache.spark.network.netty.NettyBlockRpcServer$$anonfun$2.apply(NettyBlockRpcServer.scala:60)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
    at org.apache.spark.network.netty.NettyBlockRpcServer.receive(NettyBlockRpcServer.scala:60)
    at org.apache.spark.network.server.TransportRequestHandler.processRpcRequest(TransportRequestHandler.java:159)
    at org.apache.spark.network.server.TransportRequestHandler.handle(TransportRequestHandler.java:107)
    at org.apache.spark.network.server.TransportChannelHandler.channelRead0(TransportChannelHandler.java:119)
    at org.apache.spark.network.server.TransportChannelHandler.channelRead0(TransportChannelHandler.java:51)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:266)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at org.apache.spark.network.util.TransportFrameDecoder.channelRead(TransportFrameDecoder.java:85)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: de.gaf.ric.workflow.RicKryoRegistrator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.serializer.KryoSerializer$$anonfun$newKryo$5.apply(KryoSerializer.scala:124)
    at org.apache.spark.serializer.KryoSerializer$$anonfun$newKryo$5.apply(KryoSerializer.scala:124)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
    at org.apache.spark.serializer.KryoSerializer.newKryo(KryoSerializer.scala:124)
    ... 43 more

    at org.apache.spark.network.client.TransportResponseHandler.handle(TransportResponseHandler.java:189)
    at org.apache.spark.network.server.TransportChannelHandler.channelRead0(TransportChannelHandler.java:121)
    at org.apache.spark.network.server.TransportChannelHandler.channelRead0(TransportChannelHandler.java:51)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at io.netty.handler.timeout.IdleStateHandler.channelRead(IdleStateHandler.java:266)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at org.apache.spark.network.util.TransportFrameDecoder.channelRead(TransportFrameDecoder.java:85)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
    at java.lang.Thread.run(Thread.java:745)

The class RicKryoRegistrator is definitively included in my uber JAR, I double checked that. It is also transferred to the executors:
17/02/02 16:19:02 INFO Executor: Fetching spark://172.31.20.106:41032/jars/app-imageprocessing-0.13.0-20170202.112920-1.jar with timestamp 1486048690879
17/02/02 16:19:02 INFO TransportClientFactory: Successfully created connection to /172.31.20.106:41032 after 23 ms (0 ms spent in bootstraps)
17/02/02 16:19:02 INFO Utils: Fetching spark://172.31.20.106:41032/jars/app-imageprocessing-0.13.0-20170202.112920-1.jar to /mnt/yarn/usercache/hadoop/appcache/application_1486039395474_0012/spark-8172edd9-d1c7-40c9-ad9b-74b2bd9dbad9/fetchFileTemp6474512860106916303.tmp
17/02/02 16:19:03 INFO Utils: Copying /mnt/yarn/usercache/hadoop/appcache/application_1486039395474_0012/spark-8172edd9-d1c7-40c9-ad9b-74b2bd9dbad9/-68603321486048690879_cache to /mnt/yarn/usercache/hadoop/appcache/application_1486039395474_0012/container_1486039395474_0012_01_000011/./app-imageprocessing-0.13.0-20170202.112920-1.jar
17/02/02 16:19:03 INFO Executor: Adding file:/mnt/yarn/usercache/hadoop/appcache/application_1486039395474_0012/container_1486039395474_0012_01_000011/./app-imageprocessing-0.13.0-20170202.112920-1.jar to class loader

Reading the source code of org.apache.spark.serializer.KryoSerializer, I see that it uses the following ClassLoader:
val classLoader = defaultClassLoader.getOrElse(Thread.currentThread.getContextClassLoader)

Could it be that the defaultClassLoader is not set and that my uber JAR is not included in the Thread.currentThread.getContextClassLoader? What else could be the reason?


text:
Q: Service Discovery Environment variables issue in Kubernetes I am using k8s 1.5 and am stuck in one issue.
I am trying to deploy 2 pods and related service. We can consider one as UI and another as DB. I have seen that using Service Discovery, we can achieve the connectivity between both the pods.
Problem 1:
While getting inside the container of UI Pod, if I am entering env then, I am getting the env variables of Kubernetes service, but I am not getting the env variables of DB Pod. And according to my knowledge, whenever we run any pod then it exposes two variable and i.e SERVICE_HOST and SERVICE_PORT and that should be available to all the pods in that namespace.
Problem 2:
Sometimes the UI Pod doesnot show its own variable also, and after retry sometimes it will come. Means it takes time show the environment variable of itself.
Can Anyone suggest me what to do in this scenario ? Does the environment variables maintain orders. If anyone have any nice example then pls let me know.
Note: Both deployment and service files are deployed on the same namespace.

A: In the examples that I've seen (https://github.com/kubernetes/kubernetes/blob/master/examples/guestbook-go/main.go, line 77), they use the service dns name instead of environment variables (just like you do when linking containers in docker). The same happens with Helm charts (https://github.com/kubernetes/charts/blob/master/stable/wordpress/templates/deployment.yaml), where in all deployments they use the service name and the port, which is something known (in the case of Helm, generated at deployment time). Would it work for you to directly use the service name and the port?


text:
Q: Has window.onload event already fired I have a small javascript util which may get preloaded, lazy loaded or loaded on demand. When it's initiated it adds some stuff to the DOM. It's low priority and if it's preloaded it can wait for the onload event to fire before running, but if it's lazy loaded it can go ahead and run immediately.
Currently It's checking to see if the ID of the footer element exists to determine if it should add an event listener to the window onload event or just run. e.g.
if ( document.getElementById("footer") ){
   Init()
} else {
   if (window.addEventListener){...}
   else if (window.attachEvent){...}
}

Although currently working, this is obviously a pretty poor solution.
Any non jQuery related suggestions on improving this gratefully received!

A: You should use document.readyState property:
if (document.readyState === 'complete') {
   //do stuff
}


text:
Q: Measure of Cauchy sequence I consider $(f_n)_{n\in \mathbb N} \in L^p(\mu)$ and $\vert|f_n-f\vert|_p \rightarrow 0 $ for $ n \rightarrow \infty$
So I can conclude: Let $ \epsilon_k =2^{-k}$
$ \forall k  \ \exists n_k: \mu(\{|f_n -f_m|>\epsilon_k \}) \leq \epsilon_k \ \forall m,n \geq n_k $
Because of the $L^p$ convergence the set has to be a null set.
I cannot imagine how you can state that in a mathematical way?

A: $\mu (|f_n-f_m| > \epsilon_k) \leq \frac 1 {\epsilon_k^{p}} \int |f_n-f_m|^{p} < \epsilon_k$ if $\int |f_n-f_m|^{p} <\epsilon_k^{p+1}$ and this is true for $n$ and $m$ are sufficiently large. So the answer is YES. [ Note that $\int |f_n-f_m|^{p} \to 0$ because $|f_n-f_m|^{p} \leq 2^{p} (|f_n-f|^{p}+|f-f_m|^{p})$].


text:
Q: Delphi Borland database engine 64 bit compilation I have my application already running in Delphi XE2 and compiled for 32 bit.
Database components used are BDE Borland database engine.
Now, I am planning to compile my application on 64 bit platform in XE2 only.
But BDE is not available in 64 bit, components are disabled.
When I try to compile the application I get error message
'[DCC Error] BDE.pas(7011): E1026 File not found: 'IDPAS32.OBJ'
Can you please help me out?

A: There is no 64 bit version of BDE. You will need to remain on BDE with a 32 bit program or replace BDE.


text:
Q: How to configure "number" of hit-highlights returned by Sharepoint Search Server? We have a sharepoint server 2016 on premise and I would like to configure the number of hit highlights that are returned.
For e.g., if my query is "all hands landscape", I get a search result that highlights the words "all" and "hands". That is,
"hitHighlightSummary": "Calendar Invitation DL: Engineering <c0>All</c0> <c0>Hands</c0> ; Future Schedule: Date <ddd/> ",

However, the same page also contains the word "landscape" somewhere in it.
Is it possible to configure sharepoint to highlight "landscape" as well?
Perhaps some configuration property to set max hit highlights to 4 instead of the apparent 2.


text:
Q: XSLT Transformation result different in Windows and Unix I have an interesting and Wierd problem. When I run the XSLT transformation programmatically using Eclipse IDE, I get the desired output as follows:
      <Schedule>
      <Date>10/13/2013</Date>
      <Amount>2000</Amount>
      </Schedule>

Whereas using the same XSLT in my Solaris box, the transformation result is:
       <Schedule>
       <Amount>2000.0</Amount>
       </Schedule>

The mystery being that now the
      <Date>10/13/2013</Date>

block is not visible in UNIX. Also the amount is now 2000.0 compared to 2000 I get in my Eclipse output.
I am pretty sure that the SAME XSLT is being picked up in both the OS. I am really perplexed as to why the transformation outputs will be deifferent in Windows ( desired) vs Solaris ( undesirable). Looking forward to unlocking the mystery from all the Gurus out there.

A: Ok. I finally figured out the reason. In Unix, the xslt was being validated against a XSD which required the Date field to be DateType, i.e YYYY-MM-DD whereas I was passing the date in MM/DD/YYYY. Ironically, when I ran it in eclipse IDE, it took the MM/DD/YYYY value without complaining. Anyways, For now, my problems are solved and thanks everyone for looking into it.


text:
Q: HTML form won't carry out correct actions, interference I have written the following website which uses a very simple form and sends that data into a mysql database. My problem is that the javascript/ajax form id="contactForm" script seems to interfere with the form action="insert.php"
Here is my basic html:
 <form action="insert.php" method="post" id="contactForm" role="form"  data-toggle="validator" class="shake">

                Voor en achternaam.
                <input name="naam" type="text" class="form-control" id="name" placeholder="Voornaam Achternaam" required data-error="Vergeet deze niet!">

 <button value="Submit" style="background-color: #75963c;" type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Submit</button>

    </form>

here is my insert.php to put the data into the mysql database:
<?php
$con = mysql_connect("mydatabaseip","mydbuser","mydbpassword");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("mydbname", $con);

$sql="INSERT INTO nametable (naam) VALUES('$_POST[naam]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }

echo "1 record added";

mysql_close($con)
?>

Here is my ajax/javascript for sending the email:
$("#contactForm").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        // handle the invalid form...
        formError();
        submitMSG(false, "Did you fill out everything correctly?");
    } else {
        // everything looks good!
        event.preventDefault();
        submitForm();
    }
});
function submitForm(){
    // Initiate Variables With Form Content
    var name = $("#name").val();

    $.ajax({
        type: "POST",
        url: "php/form-process.php",
        data: "name=" + name,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                formError();
                submitMSG(false,text);
            }}});
}
function formSuccess(){
    $("#contactForm")[0].reset();
    submitMSG(true, "Message received!")
}
function formError(){
    $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
        $(this).removeClass();
    });
}
function submitMSG(valid, msg){
    if(valid){
        var msgClasses = "h3 text-center tada animated text-success";
    } else {
        var msgClasses = "h3 text-center text-danger";
    }
    $("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}

here is my form-process.php:
<?php

$errorMSG = "";

// NAME
if (empty($_POST["name"])) {
    $errorMSG = "Name is required ";
} else {
    $name = $_POST["name"];
}

$EmailTo = "myemail@outlook.com";
$Subject = "form info.";

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$name);

// redirect to success page
if ($success && $errorMSG == ""){
   echo "success";
}else{
    if($errorMSG == ""){
        echo "Something went wrong :(";
    } else {
        echo $errorMSG;
    }

}
?>

Somehow these two files seem to interfere with each other. Probably because they both perform an action on the same element - the form element. I've been working along time to get this running but can't figure out how to do so. If I let the id="contactForm" be in there it will execute but the action="insert.php" won't.
All help is appreciated.

A: This is happening because you're trying to use the same form for two separate submissions. It's a bit of a strange design if you ask me...why not just post back all the data and then call whatever is in form-process.php directly from the insert.php postback script? That way you'll only have one post to the server and not two.
Anyway, if you want to stick with it, it's "interfering" because of this line in your submit handler:
event.preventDefault();

This prevents the "default" behaviour of the submit button, which would be to submit the form using a full postback according to the settings in the <form> tag.
If you still want to have both actions working, you'll need to wait for the ajax call to complete successfully before you can safely have the main postback occur. To do this you can add another line in to manually trigger the main submission. Within the success function of your ajax post to form-process.php, change
if (text == "success"){
  formSuccess();
}

to
if (text == "success"){
  submitMSG(true, "Message received!");

  $("#contactForm").submit(); //this will submit the form to insert.php as per the form tag using a full page postback
}


text:
Q: rails 4 redirect routes to subdomain and change path I want to create redirects for ~= 10 routes in my Rails 4 app:

*

*redirect to subdomain

*keep params even in POST/PUT (possible ?)

*change end of path

*keep locale

*keep the scheme

Example:

http://example.com/fr/cloud/signup?format=json

to:

http://services.example.com/fr/users/create?format=json

All my new routes with subdomains are already created and working.
A simple test, this is working:
get '/admin', to: redirect("http://admin.example.com", status: 301)

Now I want to build the new url with the scheme, keep params, locale...etc
I tried:
get '/app', to: redirect { |params, request| "#{request.protocol}apps.#{request.host}/#{I18n.locale.to_s}" }, status: 301

The locale is not working (tried also :locale or locale without success).
How to pass params ?
Another example with post:
post '/cloud/signup', to: redirect { |params, request| "#{request.protocol}services.#{request.host}/users/create" }, status: 301

How to transfer params ?
Thanks.


text:
Q: LLVM as base compiler for different languages I am new to LLVM compiler and infrastructure. I have the following thought.
Clang is the LLVM front end for C/C++, similarly Rustc for Rust programming language. Both can emit the LLVM IR code and the emitted code can be compiled to executable application.
My question is is it possible to link different programming languages? Example shown below -
/* Code in C */
int add(int, int);
int main()
{
  printf("%d", add(5 ,6));
}

The function defined in Rust for example
// Code in Rust
fn main()
{
  println!("{}", add(5, 6));
}

fn add (x: i32, y: i32) -> i32
{
  x + y
}

Once the IR is generated from both the source files, is it possible to link them and create a single application?
I am just curious to know if this works, please let me know.

A: Short answer: Yes.

Long answer: Yes, as long as some requirements are fulfilled.
There are two kinds of compatibility: API (Application Program Interface) and ABI (Application Binary Interface). Essentially, the API dictates whether your program compiles whereas the ABI dictates whether it links, loads and runs.
Since Rust has a C FFI, Rust can emit code that can normally interact with C (it has the proper C ABI, for the considered platform). This is evident in that a Rust binary can call a C library.
If you take the LLVM IR of that Rust binary, the LLVM IR of that C library, merge both together, and use LLVM to produce a new binary, then you'll get a single binary (no dependency).
So, the "only" requirement is that your two pieces of code must be able to link/load/run independently first.

Another way to obtain a single binary, which is independent from LLVM, is static linking; in Rust you can for example static link with the musl implementation of the C standard library. The main advantage of merging at LLVM IR, is that you can then run LLVM optimization passes on the merged IR, and therefore benefit from cross-language inlining (and other optimizations).

A: Firstly, Rust and C can talk but through Rust's FFI (Foreign Function Interface). For very basic functions, I imagine it would be possible to compile both languages to LLVM and have some sort of functionality but we're talking hello world length programs (maybe even not at that level though). In general there must be some sort of ABI to implement what you're suggesting. However, even with an ABI the implementation is done at the Front End level.
Concisely put, LLVM can't represent all language specific constructs. So you can't just link two program's LLVM IR and hope it works. There must be some work done at the front end to ensure compatibility between two languages.


text:
Q: How to override toString method in a class I am trying to generate a jList of classes.
If I do:
package test;

import javax.swing.DefaultListModel;

public class TestFrame extends javax.swing.JFrame {

    DefaultListModel jList1Model = new DefaultListModel();

    public TestFrame() {

        initComponents();

        jList1Model.addElement(TestClass.class);
        jList1.setModel(jList1Model);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList<>();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jList1.setModel(new javax.swing.AbstractListModel<String>() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public String getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JList<String> jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
}

Being my TestClass:
package test;

public class TestClass {

    public static String name = "Test Class 1";
    public int foo;
    public int bar;

}

Then I get:

So far, so good.
Now I would like to have the content of the name class attribute instead of class test.TestClass displayed in the jList1.
I have tried this:
public class TestClass {

    public static String name = "Test Class 1";
    public int foo;
    public int bar;

    public static String toString() {
        return name;
    }

}

But I can not even compile it as I get:
toString() in TestClass cannot override toString() in Object overriding mehtod is static.

A: Not an answer to overriding the toString method but a solution of how to have a list displaying something different than what is returned by toString. Add a ListCellRenderer to the list. Basically extend the default one (an extension of JLabel itself) and change what should be displayed:
class ClassRenderer extends DefaultListCellRenderer {
    @Override
    public Component getListCellRendererComponent(
            JList<?> list, Object value, int index, boolean selected, boolean focus) {
        if (value instanceof Class) {
            value = ((Class<?>) value).getSimpleName();
        }
        return super.getListCellRendererComponent(list, value, index, selected, focus);
    }
}

To use it just call (before displaying the list)
list.setCellrenderer(new ClassRenderer());

More details, better explanation can be found in official tutorial: Providing a Custom Renderer

Solution suggested by JB Nizet (my interpretation, hope I did understand it correctly): create an object to hold the Class and its label; add its instance to the list:
public class LabeledClass {

    private final String label;
    private final Class<?> theClass;

    LabeledClass(String label, Class<?> theClass) {
        this.label = Objects.requireNonNull(label);
        this.theClass = theClass;  // TODO null check?
    }

    public Class<?> getTheClass() {
        return theClass;
    }

    @Override
    public String toString() {
        return label;
    }

    // TOD hashcode, equals ?
}

used as:
model.addElement(new LabeledClass("Test", TestClass.class));

No need to change the default cell renderer for this. Advantage: is is more OO if changed to be used in your chart, very simple example, instead of LabeledClass:
public abstract class ChartEnricher {

    private final String name;

    protected ChartEnricher(String name) {
        this.name = Objects.requireNonNull(name);
    }

    public abstract void enrichChart();

    @Override
    public String toString() {
        return name;
    }
}

The enrichChart method must be implement for each possible entry, or have a generic one that uses a Class given to its constructor (as LabeledClass). Obviously this can be extended if required for more functionality depending on use case.

A: Just in case it helps someone, using inputs to original OP I finally combined accepted answer with a static method named getClassName which is invoked via reflection.
Note: I have included the final code which uses slightly different names but still shows reflection usage. My real app is obviously a bit more complex than the included simplified OP posted example as it is intended to use many classes extended from an abstract class that enforces the extended classes to implement several methods.
As a side note: the only thing I have not managed to enforce is the implementation of the static getClassName method, as apparently you can not enforce static methods implementation in Java (apparently abstract static methods are not possible).
class IndicatorsRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(JList<?> list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {

        Class<? extends BaseIndicator> baseIndicatorClass = ((Class<? extends BaseIndicator>) value);

        try {
            return super.getListCellRendererComponent(list, baseIndicatorClass.getMethod("getClassName").invoke(baseIndicatorClass), index, isSelected, cellHasFocus);
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(IndicatorsRenderer.class.getName()).log(Level.SEVERE, "No such method exception while trying to access Name of indicator. Exception {0}", ex);
            System.exit(1);
        } catch (SecurityException ex) {
            Logger.getLogger(IndicatorsRenderer.class.getName()).log(Level.SEVERE, "Security exception while trying to access Name of indicador. Exception {0}", ex);
            System.exit(1);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(IndicatorsRenderer.class.getName()).log(Level.SEVERE, "Illegal Access Exception while trying to access Name of indicator. Exception {0}", ex);
            System.exit(1);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(IndicatorsRenderer.class.getName()).log(Level.SEVERE, "Illegal Argument Exception while trying to access Name of indicator. Exception {0}", ex);
            System.exit(1);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(IndicatorsRenderer.class.getName()).log(Level.SEVERE, "Invocation Target Exception while trying to access Name of indicator. Exception {0}", ex);
            System.exit(1);
        }

        return null;

     }
 }


text:
Q: Ajax não funciona com botão específico Tenho um código que ao clicar no botão ele pede um motivo do clique. Depois de escrever o motivo ele troca o botão e deveria trocar as informações listadas em baixo. Esse código está em Ajax só que não está funcionando corretamente.
Ao clicar nesse botão, ele pede essa justificativa e troca o botão, mas não troca as informações. OBS: O mesmo código funciona com o outro botão que desabilita a imagem que eu tenho, mas com esse botão não funciona.
A parte que não está funcionando é essa:
success: function(r) {
    if(r) {
        $(t).parent().parent().next().find('.msg_SemEmi').show();
        $(t).parent().parent().next().find('.graf_laudo').show();
        $(t).parent().parent().next().find('.graf_lau').css('display','none');
        $(t).parent().parent().next().find('.img_lau_d').show();
        $(t).parent().parent().next().find('.img_lau_a').css('display','none');
        $(t).removeClass('semEmi btn-default');
        $(t).addClass('comEmi btn-warning');
        $(t).empty();
        $(t).append('<?= $this->lang->line("con_inflaud_afe_comEmi"); ?>');
    } else {
        notifica('<?= $this->lang->line("con_inflaud_msg_erro_title"); ?>', '<?= $this->lang->line("con_inflaud_msg_erro_d"); ?>', 4000);
    }
}

Aqui está o HTML que chama esse Ajax:

    <input type="hidden" id="input_semEmi<?= $l->img_id ?>" name="id_foto" value="<?= $l->img_id ?>">
    <a href="javascript:void(0);" id="semEmi<?= $l->img_id ?>"  id-foto="<?= $l->img_id ?>" class="btn btn-labeled btn-default pull-right semEmi"> <?= $this->lang->line("con_inflaud_afe_semEmi"); ?>

Meu código está em MVC


text:
Q: who's using my Go package My scenario is we have many small projects in development, and some of them have dependency on each other. and we are trying to provide some automated tests based on dependency relationship. e.g. when a package is changed, make sure all depending packages pass their own unit-test.
So the question is, in Go, is there a way/tool to list which packages (local work space) are referring to a given package?

A: Support for this is included in the go tool itself. From question: How to list installed go packages
You can use
go list -f "{{.ImportPath}} {{.Imports}}" ./...

to list packages and their dependencies (packages that a package imports). Execute it in the src folder of your Go workspace. Or
go list -f "{{.ImportPath}} {{.Deps}}" ./...

Which lists packages and their dependencies recursively.
Yes, this is not the direction you want because you want packages that import a specific package. But you can easily search in the output of the above commands for your package name. Lines where your package is listed as a dependency are the ones you are looking for; the first "token" of these lines will be the packages (with path to workspace src folder) that import your package.
On Unix systems you can use |grep to filter for these lines, e.g.
go list -f "{{.ImportPath}} {{.Imports}}" ./... |grep yourpackage

(This will also list a line containing your package and its dependencies.)
Example:
Let's say you have 2 packages: my/pack1 and my/pack2, where my/pack1 imports nothing, and my/pack2 imports fmt and my/pack1, the output of the above commands will include:
path/to/workspace/src/my/pack1
path/to/workspace/src/my/pack2 [fmt my/pack1]

And you are looking for packages that import my/pack1: you can see my/pack2 imports it because my/pack1 is listed as a dependency for my/pack2
There is also an open-source project doing just this: https://github.com/cespare/deplist


text:
Q: Run multiple functions at millisecond intervals in C++ I need to call multiple functions(200+) from different modules(5 ~ 10) for every millisecond to get value and write to a log. As of now I am using loop to call 200 functions but I am not getting the desired number of entries. What is the best way to do this? Shared below a code snippet(not exact code but my design will look like this)
std::ofstream logStream;
while (stop)
{
    for (int moduleIdx = 0; moduleIdx < moduleSize; moduleIdx++)
    {
        for (int fnIdx = 0; fnIdx < module[moduleIdx].totalFns(); fnIdx++)
        {
            std::string output;
            module[moduleIdx]->fn[fnIdx](output);
            logStream << moduleIdx << "," << fnIdx << "," << output << "\n";
        }
    }
    std::this_thread::sleep_for(1ms);
}
logStream.close();

A: If you are using Windows, the timer resolution is 15.6 ms by default, so your call to sleep_for() will take at least 15.6 ms. You can increase the timer resolution with timeGetDevCaps() and timeBeginPeriod(). See the documentation.
Another option is to remove the sleep, check the timestamp (use a timer with greater accuracy than 1 ms), and call the functions after 1 ms has elapsed.


text:
Q: What approach should I use when creating a custom WPF control? I'm about to redo an old WinForms application as a WPF application. The core of this applicaton is a custom "grid" component. I'd like some ideas on the best way to do this as a WPF component.
The application displays a grid of data for different countries/sectors. Each cell of the grid displays different information (e.g. graph, image) depending on the available data for that country/sector.
I have a domain model assembly that I want to keep clean - to maximize reuse. The structure is as follows:

*

*Table

*

*Continents

*Countries

*Sectors

*Data[country, sector]

The grid displays countries down the left and sectors across the top.
In the current application, the grid component has a (POCO) Table property and an Refresh() methods to manually redraw it. So, if the Table is updated, the parent of the grid component refreshes it. The grid component also has a number of events that are fired if a continent, country or cell is clicked - so that the parent can response with pop-up menus, etc.
This all works fine.
However, I'm wondering whether this is the correct model to use for a WPF application. Looking at many of the WPF example, they support data-binding, etc. But, it's not clear, from the simple examples, how I might bind a complex object to my components - or whether it would even be worthwhile.
Also, the WinForms component is completely custom drawn - there are no sub-controls (e.g. Labels) in use. Would it be better to use a WPF user control and build the table from a GridLayout and lots of Label, Shape, etc controls? In practice, they are maybe 20 rows and 20 columns in the grid, and the user regular removes and adds countries/sectors (rows/columnms) while using the application.
My immediate goal is to make sure my design plays well in the WPF eco-system, but I have a secondary goal of learning how to do things in a WPFy way - given this is my first WPF app. I'm pretty on top of the use of building a general WPF app - it's just the custom control stuff that remains a little fuzzy (even after reading around it a little).
Any insights/guidance would be appreciated.

A: You definitely want to adapt the MVVM approach, as outlined by Josh Smith.  Practically, this means that your custom grid component will be contained in it's own View.  Backing the view will be your ViewModel, where you will define an ObservableCollection of objects containing your data.  These objects will probably come from your Model.  This interaction is shown below:
Models:
public class TableData
{
    public string Country { get; set; }
    public string Continent { get; set; }
    public object Sector { get; set; }
}

public class TableManager : ITableManager
{
    public Collection<TableData> Rows;

    public void GetData()
    {
        this.Rows = new Collection<TableData>();
        this.Rows.Add(...
    }
}

ViewModel:
public class TableViewModel
{
    private ITableManager _tableManager;

    public TableViewModel() : base(new TableManager())
    {
    }

    // for dependency injection (recommended)
    public TableViewModel(ITableManager tableManager)
    {
        _tableManager = tableManager;
        _tableManager.GetData();
    }

    public ObservableCollection<TableData> Rows
    {
        get { return _tableManager.Rows; }
    }
}

View:
<ctrls:CustomDataGrid
    ItemsSource={Binding Rows}
    AutoGenerateColumns=True
    >
    <!-- Use AutoGenerateColumns if the # of sectors is dynamic -->
    <!-- Otherwise, define columns manually, like so: -->
    <DataGridTextColumn
         Width="*"
         Header="SectorA"
         Binding="{Binding Country}
         />
</ctrls:CustomDataGrid>

I used CustomDataGrid in the view because I assume you're going to subclass your own DataGrid.  This will allow you to override events to customize the DataGrid to your liking:
public class CustomDataGrid : DataGrid
{
    public override Event...
}


text:
Q: How to get autocomplete code and highlight syntax in Node.js on VScode I started to learn Node.js recently, and I've notice a difference between my VScode IDE vs the guides on YouTube or other places VScode IDE
for example I want to write the following code const names = require('./names')
Language mode is set to JavaScript
1. I want the the IDE will complete the code when I write require Like every IDE

2. after I write it, it's not highlighted like a normal piece of code.
My IDE:

Some instructor IDE:

A: *

*Install Node.js Extension Pack in Visual Studio Code Editor.

*Then install the Node.js Modules Intellisense plug-in in Visual Studio Code Editor.
The image below belongs to the test study I made after installing the plugins I mentioned above. You can review this article to create the test project.

Node.JS and NPM must be installed on the system for all the processes I mentioned above to work. To check:
> node --version
v14.17.6
> npm --version
v6.14.15


text:
Q: How do I deep copy an irregular 2D array threadsafely I have stumbled upon an annoyance as I was writing a Java class; I couldn't figure out how to make copying a 2 dimensional array thread safe. This is the simple version of the class:
public class Frame {
  private boolean[][] content;

  public Frame(boolean [][] content) {
    boolean[][] threadSafeCopy = deepCopy(content);
    if (!(threadSafeCopy != null)) {
      throw new NullPointerException("content must not be null");
    }
    if (!(threadSafeCopy.length > 0)) {
      throw new IllegalArgumentException("content.length must be greater than 0");
    }
    if (!(threadSafeCopy[0] != null)) {
      throw new IllegalArgumentException("content[0] must not be null");
    }
    if (!(threadSafeCopy[0].length > 0)) {
      throw new IllegalArgumentException("content[0].length must be greater than 0");
    }
    for (int i = 1, count = threadSafeCopy.length; i < count; ++i) {
      if (!(threadSafeCopy[i].length == threadSafeCopy[0].length)) {
        throw new IllegalArgumentException
            (   "content[" + i + "].length [" + threadSafeCopy[i].length
              + "] must be equal to content[0].length [" + threadSafeCopy[0].length + "]"
            );
      }
    }
    this.content = threadSafeCopy;
  }

  private boolean[][] deepCopy(boolean[][] content) {
    boolean[][] result = null;
    if (content != null) {
      synchronized(content) { //do our best to make this as multi-threaded friendly as possible
        result = new boolean[content.length][];
        for (int i = 0, count = content.length; i < count; ++ i) {
          if (content[i] != null)
          {
            synchronized(content[i]) {
              result[i] = content[i].clone();
            }
          }
        }
      }
    }
    return result;
  }

  public boolean[][] getContent() {
    boolean[][] result = new boolean[this.content.length][]; //defensive copy
    for (int i = 0, count = result.length; i < count; ++i) {
      result[i] = this.content[i].clone(); //defensive copy
    }
    return result;
  }
}

However, the above implementation for the method private boolean[][] deepCopy(boolean[][] content) isn't actually threadsafe. It's possible that the array is being actively modified by another thread while this method is attempting the copy. Granted, I have guarded against the most abusive case, using synchronized on the base array. However, that doesn't cause the set of 2nd dimension array instances to be locked. And it's possible for them to be modified during the copy.
Is there is some way to collect the Object lock for each of the base array (content) and the sub-arrays (content[0], content[1], ..., content[content.length - 1]) such that I can call something like synchronized(objectsToLockSimultaneouslyList) and it lock all the objects simultaneously and in the list's order. If so, I can thread safely copy the contents of the array.
If not, what other kinds of solutions are available to "block all modifications to the array" without having to go change the classes which instantiate Frame or altering Frame's constructor such that it won't take an array, but only instances of immutable collections (which itself is down another freakin rabbit hole).
Thank you for any guidance you have in this area.
UPDATE:
What I want to do is fundamentally not possible. And my understanding of locking objects via synchronized was also erred (tyvm glowcoder, Paulo and Brian). I am now going to attempt to change the interface on Frame to use List<List<Boolean>> which sure seems like it would be SO much more inefficient. Or I may use Set<XyCoordinate> where the presence of an XyCoordinate means "true". Again, that seems so freakin inefficient, but threadsafe. Ugh!

A: I think your best bet is to wrap the array in an object and provide synchronized access to it. Then you can do the deep copy with the "door shut" to the accessor method.
void deepCopy(boolean[][] orig) {
    synchronized(orig) {
        boolean[][] result = new boolean[orig.length][];
        deepCopy(orig,0);
        return result;
    }
}

/**
 * recursive method to lock all rows in an array, and then copy
 * them in (backwards, by chance)
 */
void deepCopy(boolean[][] orig, int row) {
    if(row == orig.length) return; // end condition
    synchronized(orig[row]) { // lock the row first
        deepCopy(orig,row+1); // lock the next row
        content[row] = new boolean[orig[row].length];
        for(int i = 0; i < content[row].length; i++)
            content[row][i] = orig[row][i];
        // now, do row - 1
    }
}

A: You seem to have some misunderstanding about object locks.
A synchronized block (or method) on some object does not avoid any modifications on this object. It only avoids that other threads at the same time are in synchronized blocks or methods of the same object (with the exception on ones in wait() of the same object).
So, to be thread-safe here, you have to make sure all your accesses on the array synchronize on the same lock object.

A: I'd recommend that you look into using the java.util.concurrent package. It has a bunch of useful classes that might help you.
For your specific example, you can write a simple ThreadSafe2DArray class:
public class ThreadSafe2DArray {
    private ReadWriteLock readWriteLock;
    private Lock readLock;
    private Lock writeLock;
    private boolean[][] data;

    public ThreadSafe2DArray(int rows, int cols) {
        this.data = new boolean[rows][cols];
        this.readWriteLock = new ReentrantReadWriteLock();
        this.readLock = readWriteLock.readLock();
        this.writeLock = readWriteLock.writeLock();
    }

    public boolean get(int row, int col) {
        try {
            readLock.lock();
            return data[row][col];
        }
        finally {
            readLock.unlock();
        }
    }

    public void set(int row, int col, boolean b) {
        try {
            writeLock.lock();
            data[row][col] = b;
        }
        finally {
            writeLock.unlock();
        }
    }

    public boolean[][] copyData() {
        try {
            readLock.lock();
            // Do the actual copy
            ...
        }
        finally {
            readLock.unlock();
        }
    }
}

You can also expose the raw data array and the read/write locks if you want to allow clients to do their own locking, for example if clients could be reading or updating large numbers of entries in one chunk.
This approach is a lot more flexible than using raw synchronized blocks and may be faster or better for your case, although a lot depends on what sort of contention you expect in practice. The added benefit of this is that you don't need to force anything to be immutable.
Fundamentally, if two threads are ever going to be contending for a resource they must agree on some kind of locking mechanism. If the thread that populates the data array does not play nicely then the only option is to have a wrapper that forces locking. If the other thread is well-behaved then you could also synchronize on the top-level array object in both threads, or you can use the expose-locks-and-data approach, or just use the class as presented above and call copyData in your Frame class.
This answer got a lot longer than I intended. Hopefully it makes sense.
EDIT: Note that it's important to put the unlock call inside a finally block in case an unexpected RuntimeException (or an Error) gets thrown somewhere inside the try. In this case the code is pretty simple so it's probably overkill, but it will make the code more maintainable if this safety net is already in place.
EDIT2: I note that you specifically mentioned an irregular array. I've left the example as a regular array in the interests of brevity :)

A: I really think you're not grasping some core concepts of multithreading.
If some other thread has a reference to the array you're passing into the Frame constructor, nothing you do in Frame can help you. That other thread can modify it at will.


text:
Q: Web API ignores non-model body parameters; should throw error In Web API v2 when you supply data in the POST body that are not part of the model, they are ignored by the framework. This is fine in most cases, but I need to check this and return an error response, so the user doesn't get unexpected results (he expects these wrong parameters to do something...).
So how do I check for this? The model will be null, but when the framework has parsed the data and returned a null-model, I can no longer access the body through Request.Content. So what options are there?

A: One way is to derive your DTO class from DynamicObject. Check out my blog post: http://lbadri.wordpress.com/2014/01/28/detecting-extra-fields-in-asp-net-web-api-request/


text:
Q: What's the name of this methodology? Complete specification: I want to to this, this, and this
Infinite iterations:
1. Design a task, module or little piece of software.
2. Implement.
3. Test.
The design and implementation stages occurs practically at the same time.
Does this methodology exist?

A: I think we'd call it iterative or agile with a complete specification prior to starting iterations.


text:
Q: jQuery: two dropdownlists building an image-url and show the picture On my website I would like to compare two companies with an image-chart/-graph. Each company (and there are a few hundreds) has an ID like "000000" (6 digits). An image link for a chart could be "pic_000123_000456.peng" - that would compare the company with the id 000123 with the company 000456. I guess, that's clear? I've already built this engine, it works without problems
Now I'd like to offer an easy page for user to choose for their own two individual Comparisons. For that I'd like to display two dropdownlists. Below the Image shell appear. I've found two snippets, which are going the right way. Hopefully someone could find a solution. That would be fantastic!

*

*The following jquery-code is displaying an image immediately after changing the dropdownlist (that works great):

<select id="sel">
    <option value="">Please Select the companies the Logo</option>
    <option value="pic_000123_000456.png">Chart 1</option>
    <option value="pic_000789_000456.png">Chart 2</option>
    <option value="pic_000789_000123.png">Chart 3</option>
</select>

*The next jquery-code is displaying two text-parts from two dropdownlists and bring them togther.

<select name="image" id="image">
    <option value="pic_000123_">Company 1</option>
    <option value="pic_000789_">Company 2</option>
    <option value="pic_000789_">Company 3</option>
</select>
<select name="image" id="image">
    <option value="000456.png">Company 1</option>
    <option value="000456.png">Company 2</option>
    <option value="000123.png">Company 3</option>
</select>

So instead of the text-output in example 2 the image (like in example 1) should appear, but with the link-parts of the values of example 2.

A: If I understand you correctly, you want to combine the values from the dropdowns to create the image name.

<select name="image1" id="image1">
  <option value="pic_000123_">Company 1</option>
  <option value="pic_000789_">Company 2</option>
  <option value="pic_000789_">Company 3</option>
</select>
<select name="image2" id="image2">
  <option value="000456.png">Company 1</option>
  <option value="000456.png">Company 2</option>
  <option value="000123.png">Company 3</option>
</select>

A:

  <select name="image">
    <option value="pic_000123_">Company 1</option>
    <option value="pic_000789_">Company 2</option>
    <option value="pic_000789_">Company 3</option>
  </select>
  <select name="image">
    <option value="000456.png">Company 1</option>
    <option value="000456.png">Company 2</option>
    <option value="000123.png">Company 3</option>
  </select>


text:
Q: Use pos tagging in bag of words I'm using the bag of words for text classification.
Results aren't good enough, test set accuracy is below 70%.
One of the things I'm considering is to use POS tagging to distinguish the function of words. How is the to go approach to doing it?
I'm thinking on append the tags to the words, for example the word "love", if it's used as a noun use:
love_noun

and if it's a verb use:
love_verb

A:
One of the things I'm considering is to use POS tagging to distinguish the function of words. How is the to go approach to doing it? I'm thinking on append the tags to the words

You approach looks fine. It's unclear whether it'll help though, since the features will be more sparse. Neural networks often give better results, though the improvement isn't considerable  most of the time.


text:
Q: 2 Users in one model New to Django. I'm trying to develop a Feedback module, but designing a database structure makes me confused for various reasons:

*

*Where do I need to store feedback_score (positive/neutral/negative feedback ratio), should it be put in custom User, or somewhere else?

*How should I get the recipient of the feedback credentials, should it be passed by URL, how to link recipient to FeedbackModel in class-based-views?

*How to feedback_score to be calculated each time for every User?

models.py

User = get_user_model()
# Create your models here.

class FeedbackModel(models.Model):
    id = models.AutoField(primary_key=False, db_column='id')
    sender = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        primary_key=False, related_name='feedback_left_by')
    # recipient = models.ForeignKey(
    #    User,
    #    on_delete=models.CASCADE,
    #    primary_key=True)
    FEEDBACK_OPTION = (
        (-1, 'Negative'),
        (0, 'Neutral'),
        (+1, 'Good'),
    )
    feedback = models.IntegerField(choices=FEEDBACK_OPTION)
    opinion = models.CharField(max_length=255)

    class Meta:
        ordering = ['left_by', '-id']

urls.py

from django.urls import path
from . import views

app_name = 'feedback'
urlpatterns = [
    path('leave_feedback/<str:left_to>/',
         views.leave_feedback.as_view(), name='leavefeedback'),

]

views.py

from django.shortcuts import render, reverse
from django.views.generic import TemplateView, CreateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from .models import FeedbackModel
decorators = [login_required]

@method_decorator(decorators, name='dispatch')
class leave_feedback(CreateView):
    model = FeedbackModel
    fields = ['feedback', 'opinion']
    success_url = '/'
    #template_name = "feedback/leave_feedback.html"

    def form_valid(self, form):
        form.instance.sender = self.request.user
        # ?
        return super().form_valid(form)

custom user

class User(AbstractUser):
    (...)
    @property
    def feedback_score(self)
        return ???

A:
Where do I need to store feedback_score (positive/neutral/negative feedback ratio), should it be put in custom User, or somewhere else?

I think you current Model design is okay with the requirement. Just fix the ordering in class Meta.
BTW, if you want the user to have only one feedback, then consider using OneToOneField. If you want ratio of Feedback, just do like this:
    feedbacks = Feeback.objects.all()
    positive_feedbacks = feedbacks.filter(feedback=1).count()  # returns count of the feedback
    negative_feedbacks = feedbacks.filter(feedback=-1).count()  # returns count of the feedback
    neutral_feedbacks = feedbacks.filter(feedback=0).count()  # returns count of the feedback

    print("Ratio Positive:Negative:Neutral = {}:{}:{}".format(positive_feedbacks/negative_feedbacks, 1, neutral_feedbacks/negative_feedbacks)

How should I get the recipient of the feedback credentials, should it be passed by URL, how to link recipient to FeedbackModel in class-based-views?

You need to make the user login to the system. For example you can follow this tutorial but there are other good examples out there. Once you login into the system, the user is available via request.user. And your current implement reflects this as well.

How to feedback_score to be calculated each time for every User?

You can get the latest feedback by:
user = User.objects.get(id=1)  # or user = request.user
latest_feedback = user.feedback_left_by.last()

A: feedback_score should be a class method in FeedbackModel, not a field. In general, you do not want fields in your database that can directly be derived from other fields. For instance:
class Person(models.Model):
    name = models.CharField()
    birthdate = models.DateField()
    zodiac_sign = models.CharField()

If i have the birth date, I can easily get the zodiac sign. So, zodiac_sign should be a method. The same applies to your case. Just create a method that returns summary information on the feedback.


text:
Q: XAMARIN: Why does "TAG" work in my MainActivity, but not in another class? for debugging, I use this code in my Main Activity:
        Log.Debug(TAG, "No longer listening for location updates.");

This works totally fine, but as soon as I am in another class this line does not work anymore. It says that "TAG" does not exist in the current context. Of Course did i import the same using directives... So what could cause that?
Thanks :)


text:
Q: brightness problem in ubuntu 18.04 I have recently started using ubuntu and my brightness controls on my keyboard are not working. The brightness control in the dropdown menu of ubuntu is also not working and the screen is too bright for reading. My laptop has a ryzen 3500u processor and a radeon vega 8 graphics card. The other answers regarding similar problems are all about intel graphics cards. Please help.

A: Install the Gnome Extension Adjust Brightness Icon

After installation and setting to ON you will find a lightbulb icon on the top bar.
Left click with the mouse to reduce the brightness to that required and keep clicking to reset to default. 4 clicks completes the cycle.

Don't forget that you can also set the Night Light ON with the right most menu drop down on the top bar.

The Night Light On utility helps considerably in reducing glare from over-white background screens.


text:
Q: Determine the values of $k$ so that the following linear system has unique, infinite and no solutions. Determine the values of $k$ so that the following linear system has a unique solution, infinite solutions and no solution.
$2x + (k + 1)y + 2z = 3$
$2x + 3y + kz = 3$
$3x + 3y − 3z = 3$
I have tried to use the determinant of the matrix to solve but have got stuck.
\begin{bmatrix}
2 & k+1 & 2 \\
2 & 3 & k \\
3 & 3 & 3 \end{bmatrix}
I have found the determinant to be $3(k^2-3k+2)$ which I'm pretty sure is correct.
I start getting confused with what to do with the determinant now though. I've read a few of the questions here but I just don't get it - solving equal to $0$ gives $k=1$ and $k=2$, but how do I interpret these values?

A: Some ideas:
Let $A$ be the coefficient matrix of your system, $A = A(k)$, $\mathbf{b}$ the vector of independent terms and $\mathbf{x} = (x,y,z)^T$ the vector of unknowns. Then, you have a linear system such as:
$$ A \, \mathbf{x} = \mathbf{b}, $$ with augmented matrix $(A\vert \mathbf{b})$. Then, the Rouché-Fröbenius theorem tells us that:

*

*If $n = \mathrm{rank}(A)$, where $n = 3$ in your case, then the solution is unique.

*Otherwise, there are infinite many solutions.

If $\det{A}(k) = 0$ for those valid values of $k$ (you showed them to be $k \neq 1 \wedge 2 $), then the solution is unique and, since $A$ is invertible, is given by $\mathbf{x} = A^{-1} \mathbf{b}$. The opposite is not always valid, since for $k = 1$, for example, the first and third rows are coincident and, then, the system has infinite many solutions, given by:
$$\begin{align}
& 2x + 3y + z = 3 \\
& 3x + 3y − 3z = 3 \\
\end{align}$$ Put $x = x(z)$ and $y = y(z)$ and you will get the equations for a straight line. Let us know what happens for $k = 2$.
Cheers!

A: If the determinant is not zero then the matrix is invertible, so there is a unique solution to the system $Ax = b$ given by $x = A^{-1}b$.
If the determinant is zero then the matrix is singular it means that its kernel is not the equal to $\{0\}$. There are now two cases, if $b = (3,3,3)$ is in the image of $A$, then there is at least one solution $x_0$ and $x_0 + v$ is a solution for every $v$ in the kernel, i.e. there are infinitely many solutions (take any $v\neq 0$ then $x_0 + \lambda v$ is a solution for every $\lambda \in \mathbb{R}$ ). If $b$ is not in the image of $A$ then there is no solution.


text:
Q: Does iOS support PDF/A? As the title states does iOS support PDF/A?
I tried to open it, but mostly I get a white page with errors like
illegal character `/' encountered in hex string.
illegal character `/' encountered in hex string.
invalid stream length 557; should be 563.
FlateDecode: decoding error: invalid distance too far back.
FlateDecode: decoding error: invalid distance too far back.
invalid stream length 51645; should be 52016.
FlateDecode: decoding error: invalid bit length repeat.
FlateDecode: decoding error: invalid distance too far back.
FlateDecode: decoding error: invalid distance too far back.

Perhaps I'm doing something wrong, but I didn't found any information which types of PDF the UIWebView or QLPreviewController support.
Edit:
Now I created a Word 2007 document with a single text line and saved it as normal PDF (with Adobe Plugin). Then I openend the PDF and converted it to the different available standards with the Preflight tool:

*

*PDF/A-1a

*PDF/A-1b

*PDF/A-2a

*PDF/A-2b

*PDF/A-2u

I also checked if it is really supporting this standard with the Preflight tool. Then I displayed the PDF/A on my UIWebView and the text got displayed and I didn't get an error in the console.
Then I got it managed to get access to the problematic PDF and I also checked it with the Preflight tool. The summary for PDF/A-1a and PDF/A-1b was:

*

*File header is not compatible with PDF/A

*Syntax problem: PDF file contains data after end of file

It doesn't meet any of the standards available in the Preflight tool. So yes iOS does support PDF/A, but you have to check if your PDF is valid.

A: The short answer to your question is: yes.
The longer one is, well... a bit longer :)
PDF/A, or PDF for Archival is an ISO standard that is based on the ISO standard for PDF itself (ISO 32.000). As a consequence, any software that supports "PDF" must also necessarily support PDF/A. Or otherwise stated, all PDF/A files are PDF files, but not all PDF files are PDF/A files.
To complicate matters though... there are many different versions of PDF out there, and there are at least 8 different forms (parts and flavours together) of PDF/A. Not all software supports all versions of PDF, more advanced features (such as JPEG-2000 compression to name but one example) might not be supported by your particular platform or software of choice.
So you have two steps to go through:
1) Make sure your PDF/A is valid - there is commercial software to do this such as Adobe Acrobat or callas pdfToolbox or pdfaPilot (caution: I'm affiliated with these applications) and there is free software to do this (have a look here: http://www.pdf-tools.com/pdf/validate-pdfa-online.aspx for example).
2) If your PDF/A is valid, make sure that your software / platform supports the features in that particular PDF/A file you are looking at. PDF/A-1 for example is an older standard than PDF/A-3 and supports less features. Hence you'll have a greater chance that a PDF/A-1 file is supported than a PDF/A-3 file.


text:
Q: Removing the last object in a node in a manual linked list implementation My current implementation of the removal operation of linked lists only works when the Node to be removed is not at the end of the list. I need the previous Node to now point to null, instead of pointing to the last Node, in order for it to be deleted. Instead of throwing a NullPointerException, the remove operation for the last Node just keeps the list as is. How would I change the else if condition to reflect this?
public Book remove(Book bookToRemove){

    Node current = head; //each Node stores a Book

    if(isEmpty()){
        System.out.println("No books to remove!");
    }

    //what happens if the next next one is null?
    while(current.getNext() != null && !isEmpty()){
        if(current.getNext().getBook().equals(bookToRemove)){
            Node temp = current.getNext();
            current.setNext(temp.getNext());
            return bookToRemove;
        }

        else if(current.getNext() == null){ //
            //if the next node is null, it cannot be removed, or the previous node will have nothing to point to
            current.setNext(null);
            return bookToRemove;
        }

        current = current.getNext();
    }

    return bookToRemove;
}

A: Modified the initial suggestion, just check the head node first and if that is the one to be removed, make the change to the head and exit the function. The rest of the flow will take care of removing at any other location in the list.
public Book remove(Book bookToRemove)
{
    Node current = head; //each Node stores a Book

    if(isEmpty())
    {
        System.out.println("No books to remove!");
        return bookToRemove;   //no need to continue
    }

    if(current.getBook().equals(bookToRemove))
    {
      //found in head itself, make new head and exit
      head = current.getNext();
      return bookToRemove;
    }
    while(current.getNext() != null && !isEmpty())
    {
        if(current.getNext().getBook().equals(bookToRemove))
        {
            Node temp = current.getNext();
            current.setNext(temp.getNext());
            return bookToRemove;
        }
        current = current.getNext();
    }
    return bookToRemove;
}


text:
Q: Is a hashset needed for contains with List(of String) Vb.net Would the following:
Dim stringlist As List(Of String)
Dim stringlisthas = stringlist.Contains("thing1")

be any slower than
Dim stringlist As List(Of String)
Dim stringlisthash As New HashSet(Of String)(stringlist)
Dim stringlisthas = stringlisthash.Contains("thing1")

Is a hashset needed for contains?

A:
Is a hashset needed for contains?

Needed? No.

Would [List<T>.Contains] be any slower than [HashSet<T>.Contains]?

Probably. It depends on how List<T>.Contains is implemented (its probably a linear search).
I'll answer a question you didn't ask.

Does it matter?

It depends. You have to code up both, profile it, and see if it's a bottleneck in your application. If it's not, just stick with List<T>.Contains.


text:
Q: How to insert value of checked checkbox in array using jQuery I want select all input values that is checked and has name DisbursementUnitCodes
$('input:checked[name=DisbursementUnitCodes]').val()

This code give the first element value but i want give all input value to list or array.

A: .val() gives you value of first element in selection. If you want all values in array, you should use .map() like this:
var values = $('input:checked[name=DisbursementUnitCodes]').map(function() {
    return $(this).val();
}).get();

A: Use .each() to iterating selected elements and get value of its.

var arr = [];
$("input:checked[name=DisbursementUnitCodes]").each(function(){
    arr.push($(this).val());
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="DisbursementUnitCodes" value ="A" checked />
<input type="checkbox" name="DisbursementUnitCodes" value ="B" />
<input type="checkbox" name="DisbursementUnitCodes" value ="C" checked />
<input type="checkbox" name="other" value ="D" checked />
<input type="checkbox" name="other" value ="E" />


text:
Q: error en mi codigo: no match for 'operator>>' //Ecuacion del movimiento rectilineo uniformemente acelerado.
#include<iostream>
#include<cstdlib>
#include<math.h>

using namespace std;

    main(){

    float s, Vo, t, So, a, S;
    cout<<"Ingrese el desplazamiento en el tiempo (m): ";
    cin>>s;
    cout<<"Ingrese la Velocidad inicial (m/s): ";
    cin>>Vo;
    cout<<"Ingrese el Tiempo (s): ";
    cin>>t;
    cout>>"Ingrese el desplazamiento inicial (m): ";
    cin>>So;
    cout>>"Ingrese la aceleracion (m/s2): ";
    cin>>a;
    S=(So+Vo*t)+(1/2*a*t);
     cout<<"El resultado es: "<<S<<endl;

     system("pause");
     return 0;

    }

16    6[Error] no match for 'operator>>' (operand types are 'std::ostream {aka > std::basic_ostream}' and 'const char [40]')
  cout>>"Ingrese el desplazamiento inicial (m): ";

A: Tienes los dos últimos cout con el operador mal puesto >>


text:
Q: Use if clause in sub query to set value for update I have this table of data
id | name |  Car  |  Bike  |
------------------------------------
1  | me   |   1   |    0   |
2  | you  |   0   |    1   |

And I want to update it in my tax table from:
tax_id | name | net  |  Car | Bike | Home | Total |
---------------------------------------------------
   1   |  me  | 100  | NULL | NULL |  10  |   10  |
   2   |  you | 1000 | NULL | NULL |  100 |   100 |

to:
tax_id | name | net  | Car | Bike | Home | Total |
---------------------------------------------------
   1   |  me  | 100  |  5  |   0  |  10  |   15  |
   2   |  you | 1000 |  0  |   20 |  100 |   120 |

with rules

*

*car = net*0.5

*bike = net*0.2

*home = net*0.10

*total = car + bike + home

I tried to use:
UPDATE tax
SET
    tax.Car = (
               IF (SELECT Car FROM DATA WHERE ID = 1) > 1
                   BEGIN
                       RETURN tax.net * 0.5
                   END
               ),
     tax.Bike = (
               IF (SELECT Bike FROM DATA WHERE ID = 1) > 1
                   BEGIN
                       RETURN tax.net * 0.2
                   END
               ),
WHERE ID = 1

A: What follows is a possible solution. Points to note:

*

*Please setup any future SQL questions in this way (i.e. creating the sample data ready to use) as makes it much easier to answer and you will get more/faster assistance.

*The IF statement (in SQL Server) is for control flow only, not for conditional values in statements. Instead use CASE

*I have assumed you meant 0.05 and 0.02 respectively (as opposed to 0.5 & 0.2) as this was the only way to get the results you require.

*Note the sub-query, used to allow us to make use of intermediate results to calculate the Total column. Which is then joined onto the original table to allow us to apply the updates.

    declare @Test table (id int, [Name] varchar(32), Car bit, Bike bit);
    declare @Tax table (tax_id int, [Name] varchar(32), Net money, Car money, Bike money, Home money, Total money);

    insert into @Test (id, [Name], Car, Bike)
    values (1, 'me', 1, 0), (2, 'you', 0, 1);

    insert into @Tax (tax_id, [Name], Net, Car, Bike, Home, Total)
    values (1, 'me', 100, null,null, 10, 10), (2, 'you', 1000, null, null, 100, 100);

    --select * from @Test;
    --select * from @Tax;

    update T set
      Car = Y.Car
      , Bike = Y.Bike
      , Home = Y.Home
      , Total = Y.Total
    from @Tax T
    inner join (
    select tax_id, Car, Bike, Home,  Car + Bike + Home Total
      from (
        select tax_id
          , case when exists (select 1 from @Test T where T.id = tax_id and T.Car = 1) then Net else 0 end * 0.05 Car
          , case when exists (select 1 from @Test T where T.id = tax_id and T.Bike = 1) then Net else 0 end * 0.02 Bike
          , Net * 0.1 Home
        from @Tax
      ) X
    ) Y on Y.tax_id = T.tax_id;

    select * from @Tax;

Returns:
tax_id  Name    Net Car Bike    Home    Total
1   me  100.00  5.00    0.00    10.00   15.00
2   you 1000.00 0.00    20.00   100.00  120.00


text:
Q: Why do i need to wrap this code in a cast to short? If i have some code like the following:
short myShortA = 54;
short myShortB = 12;
short myShortC = (short)(myShortA - myShortB);

Both operands are shorts and it's going into a short so why do i have to cast it?

A: Because there's no "short - short" operator. Both operands are promoted to int.
From section 7.7.5 of the C# 3 spec:

The predefined subtraction operators
  are listed below. The operators all
  subtract y from x.

*

*Integer subtraction:
int operator –(int x, int y);
uint operator –(uint x, uint y);
long operator –(long x, long y);
ulong operator –(ulong x, ulong y);

In a checked context, if the difference is
  outside the range of the result type,
  a System.OverflowException is thrown.

(And then there's floating point subtraction.)

A: To make things a little bit easier, you could simply write an extension method like this:
public static class NumericExtensions
{
    public static short Subtract(this short target, short value)
    {
        return (short)(target - value);
    }
}

Others have answered your question... :)


text:
Q: Use different shell commands depending on the name of an input file I am trying to align RNA-seq data using Salmon, however because I work with a variety of mouse strains the genome index required will depend on the strain of mouse. I keep this information in the file name so the idea is that if the input file has a specific name then a certain index should be used, otherwise another index should be used.
This script runs perfectly and returns all the files I need, however, it will always use the shell command in the else statement, and completely ignores the if statement despite the file names technically being identical.
I've tried various things and have been unsuccessful, so I would also like to know the best way (not necessarily the most generalizable since this pipeline is only for my use) to accomplish what I would like.
Code:
rule salmon_mapping:
        input:
                fastq="data/raw_data/{sample}.fastq.gz",
                c57_index="/gpfs/data01/glasslab/home/cag104/refs/Mus_musculus/Ensemble/C57/Salmon_Index/",
                aj_index="/gpfs/data01/glasslab/home/cag104/refs/Mus_musculus/Ensemble/AJ/Salmon_Index/"
        log:
                "logs/salmon/{sample}_quant.log"
        params:
                prefix="{sample}"
        output:
                "data/processed_data/{sample}/quant.sf",
                "data/processed_data/{sample}/cmd_info.json"
        run:
                if {input.fastq} == "data/raw_data/mouse_AJ_M_Liver_Hepatocyte_RNA_notx_CG_1_VML_s20180131_GTCCGC.fastq.gz" or {input.fastq} == "data/raw_data/mouse_AJ_M_Liver_Hepatocyte_RNA_notx_CG_2_VML_s20180131_GTGAAA.fastq.gz":
                        shell("salmon quant -p 16 -i {input.aj_index} -l A -r <(gunzip -c {input.fastq}) -o data/processed_data/{wildcards.sample} &> {log}")
                else:
                        shell("salmon quant -p 16 -i {input.c57_index} -l A -r <(gunzip -c {input.fastq}) -o data/processed_data/{wildcards.sample} &> {log}"

A: Replace {input.fastq} in if statement, but not in shell statement, with input.fastq. In your example, input.fastq is a string, which is what you want, whereas {input.fastq} makes it a python set object.

A: Use a function that defines the input to your rule based on your wildcards.
def select_fastq_and_index(wildcards):
    fq = "data/raw_data/{sample}.fastq.gz".format(sample = wildcards["sample"])
    idx = ""
    if wildcards["sample"] in [
    "mouse_AJ_M_Liver_Hepatocyte_RNA_notx_CG_1_VML_s20180131_GTCCGC",
    "mouse_AJ_M_Liver_Hepatocyte_RNA_notx_CG_2_VML_s20180131_GTGAAA"
        ]:
            idx = foo
    else:
            idx = bar
    return fq, idx

Then rewrite your rule:
rule salmon_mapping:
        input:
                select_fastq_and_index
        log:
                "logs/salmon/{sample}_quant.log"
        params:
                prefix="{sample}"
        output:
                "data/processed_data/{sample}/quant.sf",
                "data/processed_data/{sample}/cmd_info.json"
        shell: """
            salmon quant -p 16 -i {input[1]} -l A \
            -r <(gunzip -c {input[0]}) \
            -o data/processed_data/{wildcards.sample} \
            &> {log}
            """


text:
Q: expo-linking: Linking back to app doesn't trigger eventListener on iOS, works fine on android I've been struggling for days trying to figure out why the Linking eventListener doesn't seem to work. I am setting up the event listener correctly:
Linking.addEventListener("url", handleStravaRedirect);
where, "handleStravaRedirect" is the callback function to be called after the user grants my app permission on the 3rd party website. The problem is, this function never gets called after the redirect back to my app. I thought I was doing something wrong, but when I tried the auth flow on android, the event handler triggered as expected.
Are there any extra steps I need to do to make Linking work on iOS? It seems like iOS handles the app being pushed to the background & the redirect differently than android handles it, almost like the Linking eventListener doesn't even know the user left the app in the first place.
Other information:
To make the Auth Request and open the web browser, I'm using: AuthSession.useAuthRequest
When I log "Linking.addEventListener" right above where it gets linked, the function is there and I receive no errors that adding the event listener failed, So I'm assuming that part is set up properly and the problem is purely on reopening of my app from the browser.
I'm having the same issue in Dev when I'm using the "exp:// " scheme and in Testflight when I use my custom "herofit://" scheme.
EDIT: This seems to be very similar to the issue I'm having
https://forums.expo.dev/t/expo-deeplinking-issue-with-addeventlistener/2254/14

A: I resolved my issue. I was unable to read the response because, I was using the "AuthSession.useAuthRequest" hook, and trying to listen to the response with "Linking.addEventListener". Instead, I needed to to listen for the response with "response", which was one of the methods returned on the useAuthRequest hook.


text:
Q: Proof verification for proving the inequality $\limsup(a_n+b_n)\ge \liminf a_n+\limsup b_n$ I want to prove that for any sequences $(a_n)$ and $(b_n)$, the following holds $$\limsup(a_n+b_n)\ge \liminf a_n+\limsup b_n \tag 1$$
I want to prove the above inequality only for the case when quantities on RHS are finite.
I'm using the following definition.
Definition: $\liminf_{n\to \infty} x_n= \lim_{n\to \infty} (\inf_{m\ge n}x_m)$, where quantity in parentheses on RHS is $\inf\{x_m: m\ge n\}$.
Now, RHS can be simplified using the definition as follows:
$\liminf a_n+\limsup b_n=\lim (\inf_{m\ge n} a_m+\sup_{m\ge n} b_m)$. Let $u_n:=\sup_{m\ge n} b_m $
For any $n$, there exists some $m'\ge n$ such that $$\inf_{m\ge n} a_m+(u_n-\frac 1n)\le a_{m'}+b_{m'}\le\sup_{m\ge n}(a_m+b_m)\tag 2$$
It follows by $(2)$ that $\inf_{m\ge n} a_m+u_n-\frac 1n\le \sup_{m\ge n}(a_m+b_m)$, which gives  $$\lim_{n\to \infty}(\inf_{m\ge n} a_m+u_n-\frac 1n)\le\lim_{n\to \infty}\sup_{m\ge n}(a_m+b_m)\tag 3$$ and LHS of $(3)$ (by limit rules and noting that $\frac 1n\to 0$) simplifies to $\liminf a_n+\lim u_n\le\limsup (a_n+b_n)$. This proves $(1)$.
Is my proof correct? Thanks.

A: You are making it too complicated.
$(a_n+b_n) \ge \inf_{m \ge n}a_m+b_n$ for all $n$.
Hence $\sup_{k \ge n} (a_k+b_k) \ge \sup_{k \ge n} (\inf_{m \ge k}a_m+b_k)$.
Note that $\inf_{m \ge n}a_m \to \liminf_n a_n = \sup_n \inf_{m \ge n}a_m$, hence taking limits we get the desired result.
(Note that if $c_n \to c$, then $\limsup_n (c_n+b_n) = c + \limsup_n b_n$.)

A: Here is a possible answer based on the properties
$$\limsup_{n \to \infty}(a_n + b_n) \leq \limsup_{n \to \infty}(a_n) + \limsup_{n \to \infty}(b_n) $$
and
$$ - \limsup_{n \to \infty} (-a_n) = \liminf_{n \to \infty} (a_n). $$
Both of these follow from the definitions. Well,
$$b_n = (b_n + a_n) - a_n $$
so that the first property implies
$$ \limsup_{n \to \infty}(b_n) \leq \limsup_{n \to \infty}(b_n + a_n)  + \limsup_{n \to \infty}(-a_n)  $$.
Now move $\limsup_{n \to \infty}(-a_n)$ to the LHS and use the second property.


text:
Q: How to trim and convert a string to integer? how could I trim and convert a string as following:
string abc = "15k34"
int x = first two characters of abc // should be 15
but if abc begins with "0"
for example - string abc = "05k34"
int x = first two characters of abc // should be 5

A: Try with following code:
            string str = "15k34";
            int val;
            if (str.Length>1)
            {
                if (int.TryParse(str.Substring(0, 2), out val))
                {
                    //val contains the integer value
                }

            }

A: string abc = "15k34";
int x = 0;
//abc = "05k34";
int val;
if (!string.IsNullOrEmpty(abc) && abc.Length > 1)
{
    bool isNum = int.TryParse(str.Substring(0, 2), out val);
    if (isNum)
    {
        x = val;
    }
}

A: I think from the pseudocode you will typically have numbers with 'k' in them representing thousands.
So...
string abc = "15k34";
string[] numbers = abc.Split('k');  //This will return a array { "15", "34" }
int myInt = Convert.ToInt32(numbers[0]);

If the string was "05k34"  the value of myInt would be 5 then.
documentation:
http://msdn.microsoft.com/en-us/library/1bwe3zdy
http://msdn.microsoft.com/en-us/library/bb397679.aspx


text:
Q: If duplicate, return the corresponding row value in Python Pandas I am trying to sort a column of excel to show duplicate Zip Codes. If there is a duplicate, I am trying to get pandas to look one column over from the duplicate zipcodes, sum the values, and create a new list with the duplicated/summed values. Currently I am able to create a list of all of the duplicates, but am lost as to what step I need to take next. Any help is appreciated as I am new to coding.
Example code below:
from collections import Counter

df = pd.read_excel(r'L:\FixedIncomeReport.xlsx')

zip_code = df['Zip']
quantity = df['Quantity']
Pair = list(zip(zip_code, quantity))
dups=[]
zipcount= list(Counter(i[0] for i in Pair).items())

#print(zipcount)
for i in zipcount:
    if i[1] > 1 :
        dups.append(i[0])

def variable(element):
    if (element in dups):
        return True
    else:
        return False

filtered = filter(variable, (i[0] for i in Pair))

for item in filtered:
    print(item)

    if item in (i[0] for i in Pair):
        print(list(i[1] for i in Pair))

A: So a way to get information about duplicates in a pandas dataframe is to use the groupby function. You can group your dataframe by zipcode and count the number of occurrences and at the same time sum the quantity field.
In the code below I've created a simple dataframe of 10 Zipcodes with their respective Quantity, some zipcodes are duplicated. The code then performs the grouping, filters for duplicated zipcodes and outputs the two lists I think you need.
    import pandas as pd

    ## create sample dataframe
    df = pd.DataFrame({'Zip':['11111','00000','00001','11001','00000','11100','11111','00110','11011','00010'],
              'Quantity':[3,6,2,6,5,8,9,0,1,4]
              })

    ## group dataframe by Zip, count the number of occurrences and sum the Quantity field
    grouped_df = df.groupby('Zip')['Quantity'].agg(['sum','count']).reset_index()

    ## output the duplicated zipcodes as a dataframe with the number of occurrences and sum of quantity
    duplicated_df = grouped_df[grouped_df['count']>1]
    duplicated_df.columns = ['DuplicateZip','SumOfQuantity','NumOfOccurrences']

    ## output the duplicated zipcodes as a list
    duplicated_zipcodes_list = list(grouped_df[grouped_df['count']>1]['Zip'])

    ## output the sum of quantities for duplicated zipcodes as a list
    duplicated_zipcodes_quantitysum_list = list(grouped_df[grouped_df['count']>1]['sum'])


text:
Q: How to style angular web component with material I have created a web component with angular and I would like to know what is the best way to use angular material making sure that the style is not overridden by those who will include the web component and vice versa.
I am evaluating shadow dom but in that case, I need to import material themes in every component inside my web component if I am right.
This web component will be included in other angular application with material and inside some WordPress site.


text:
Q: double to int conversion warning in std::accumulate How to force the gcc/clang to show a warning about converting double to int in such code (in particular when using std::accumulate for container of doubles but have result in integer):
#include <iostream>
#include <numeric>
#include <vector>

int main() {

    std::vector<double> v = { 0.5, 0.6, 0.7 };

    // gives wrong result due integer initial value
    std::cout << std::accumulate( v.begin(), v.end(), 0 ) << std::endl; // no warning

    int i = 4.2; // warning

    return 0;
}

-Wconversion does not work well. Link: http://goo.gl/efJUou
P.S. VS2013 reports about type deduction warning in template function, by which you can catch the error.

A: Warnings are disabled by default for system headers. You can use the option -Wsystem-headers to enable them, but the downside is that it will output additional irrelevant warnings.


text:
Q: Quickly find recently changed files Given a timestamp and a directory path, what would be the quickest way to find (recursively) all files changed since that time? Running an external unix tool is fine.
EDIT : People, I'm not asking how to do that, I'm looking for the quickest way to do that in a python program!
My directory trees are quite large!

A: Use the GNU find command with the -newermt {timestamp} test expression.
For example
find . -type f -newermt "2012-01-01 00:00:00"

A: import os
for root, dirs, files in os.walk('/root'):
    for basename in files:
        filename = os.path.join(root, basename)
        status = os.stat(filename)
        if status.st_mtime > timestamp:
            print filename

(Or something like that, haven't run it to test)

A:  touch -t 201201010000 REFERENCEFILE
 find /PATH -anewer REFERENCEFILE

Might work for you.


text:
Q: How would you get the names of the methods of a type in TypeScript? I'm building a wrapper to convert a callback syntax function into async/await like so:
function operation<D, M extends keyof D>(
    obj: D,
    methodName: M,
    ...args: Parameters<D[M]>
): Promise<ReturnType<D[M]>> {
    return new Promise((resolve, reject) => {
        return obj[methodName](...args, (err, result) => err ? reject(err) : resolve(result));
    });
}

This works, but the issue is that the parameters I can pass into methodName not only include the names of the methods of D but also the properties (i.e. variable properties). Is there any way I can have it so F can only be a property of D that is of type Function?
Thanks!

A: You can get the keys of an object that reference functions with something like:
type MethodNames<T extends { [K in keyof T]: any }> = {
  [K in keyof T]:
    T[K] extends Function // is this key a function?
      ? K // yes, return the key
      : never // no, return never
}[keyof T] // get union of all values (which are now the keys) that are not never

interface A {
  value: string
  fn1(): void
  fn2(): void
}

type B = MethodNames<A> // "fn1" | "fn2"

Playground
You should now be able to declare the generic parameter for the method name M using this helper:
M extends MethodNames<D>

Now typescript will ensure that M is a key of D that a type of Function.


text:
Q: Select rows from DataFrame based on value from one of the column DataFrame named "result"
**I am trying to get rows with the values == 0 from a DataFrame (named "result" that you see in the image attached).
The SQL Query for something like this will be like:
SELECT * FROM RESULT WHERE column_name equal to some_value
My DataFrame has 2 columns. the 1st one is i think named 'Index' and the 2nd one is named '0' (the names are by default -- didn't bother to change)
Because the 2nd column is a binary: based on whether the restaurant review (1st column) was positive or negative (1 or 0). I want to get only the rows (of the two columns based on the negative reviews).
when I try the code:
df.loc[df['column_name'].isin(some_values)]     or in my case
result.loc[result['0'].isin(0)]
I get the error: KeyError: '0'
Can anybody please help? **

A: If you want to select rows, whose value of column '0' is 0, it should be as simple as :
result[result[0] == 0]

However, as sacul has pointed out, you should check whether the name of your column is of type 'str' or 'int'.


text:
Q: App Rejected because of same name in iTunes? In iTunes store an App has same name like my App. So I want to change my app name. I have changed my App name in XCode. Should I have to change all the folder too ?
Should I have to change bundle ID also ?

A: YOu have to change it at two places :

*

*The name of you product app

*The name of your app in iTunes

That's all


text:
Q: Magento 2 : Add Button to Order View I want to add custom button to the order view, which should print the package slip.
How can I do that?
Thanks!

A: As per your requirement. I think following extension is full file your requirement.

https://marketplace.magento.com/fooman-printorderpdf-m2.html

And yes, it's free extension.
Hope that'll help you.


text:
Q: actionButton not working in XCODE I have this block of code in my xcode project. I am having trouble being able to click the button and to make this work. The button displays in my simulator but does not work when I click it. Does anyone have any ideas on what is going on here? It was working at one point but now seems to have failed. Maybe I accidentally changed a build setting? Or simulator setting? Any thoughts would be appreciated!!
Code for the button
-(void)viewDidLoad{
[super viewDidLoad];

UIBarButtonItem *actionButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                  target:self action:@selector(openWebLink)];
NSArray *items = [NSArray arrayWithObjects: actionButton,  nil];
[self.toolbar setItems:items animated:NO];

[actionButton release]; }

Here is the code for the action:
-(void)openWebLink{
// open a dialog with an OK and cancel button
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Do you want to apply for this job?"
                                                         delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"OK" otherButtonTitles:nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showFromToolbar:_toolbar];
[actionSheet release];  }


text:
Q: Making an animated taskbar app I have a HP notebook (running XP).
I have seen on IBM computers, that they have a power-meter (it looks like a bar). It displays percentage of power left in battery. It is displayed in the taskbar. Not in the systemtray.
Either on the left side or the right side of the potential language toolbar.
The application is animated, since the percentage of power (0-100%) chances. It fills up the bar with a green color according to the percentage. So half would be colored green if the power is down to 50%.
Now, since it is an IBM application for IBM notebooks, I want/need to make a copy of it.
My real question is though, how do I make an animated taskbar application?

A: What you are looking for is creating an Application Desktop Toolbar (also known as AppBar). The main function you use to register your application window as an AppBar is SHAppBarMessage.
To get you started, you can look at this old appbar example with C++. If you want to do it in C#, there's a thread that discusses some details on how to do it in WPF. I am not aware of examples of how to do it with WinForms, but a quick search on the web should bring something.
Update: Actually, if you want a toolbar that sits on the taskbar, you need to implement a Deskband. Here's a sample DeskBand in C++ and here's a DeskBand in C#.
That's what happens when you don't touch a topic in a while. :-)
Source:
This is actually an already answered question.