text:
Q: How to get azure blob storage content in FileInputStream in Java? I am working on an API (spring boot). In which i need to return FileInputStream in Response body of get method.
Expected -
When front end call the get-files API, a file download prompt should be open on browser.
Problem - We can't use blob.downloadToFile method, because it will download the file on local machine(or where APIs are hosted) and we need something using which we can send the File directly to front-end on API call.
However there is another method blob.download(), which returns OutputStream which can't be returned on API call.
So is there any way that we can convert that OutputStream to FileInputStream without saving to a actual file on our device.
Example code -
public ByteArrayOutputStream downloadBlob() throws URISyntaxException, InvalidKeyException, StorageException, IOException {
        String storageConnectionString = "DefaultEndpointsProtocol=https;" + "AccountName=" + accountName + ";"
                + "AccountKey=" + accountKey;

        CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

        CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

        final CloudBlobContainer container = blobClient.getContainerReference("container name");

        CloudBlockBlob blob = container.getBlockBlobReference("image.PNG");
        ByteArrayOutputStream outputStream =new ByteArrayOutputStream();
        blob.download(outputStream);
        System.out.println("file downloaded");

        return outputStream;
    }

Note- the file can be of any type.

A: Here is the solution - After hitting the API in browser, your file will be downloaded in browser -
package com.example.demo.controllers;

import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

@RestController
public class FileDownload {
    @GetMapping(path="/download-file")
    public ResponseEntity<Resource> getFile(){
        String fileName = "Can not find symbol.docx";
        //azure credentials
        String connection_string = "Connection String of storage account on azure";

        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(connection_string).buildClient();

        BlobContainerClient containerClient= blobServiceClient.getBlobContainerClient("Container name");
        System.out.println(containerClient.getBlobContainerName());

        BlobClient blob = containerClient.getBlobClient(fileName);

        //creating an object of output stream to recieve the file's content from azure blob.
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        blob.download(outputStream);

        //converting it to the inputStream to return
        final byte[] bytes = outputStream.toByteArray();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ByteArrayResource resource = new ByteArrayResource(bytes);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

        return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
                .headers(headers)
                .body(resource);
    }

}


text:
Q: Could not parse the remainder: '(audio_only=True)' in my templates/videos.html,

    {% for vid in videos.streams.filter(audio_only=True) %}
        {{vid.resolution}}
    {% endfor %}

Error is,
Could not parse the remainder: '(audio_only=True)' from 'videos.streams.filter(audio_only=True)'

I can solve this when i pass all_videos = videos.streams.filter(audio_only=True) from my views.py as context, and in templates/videos.html i replace videos.streams.filter(audio_only=True) with all_videos,
but I want to know that is there any other method to solve this

A:
but I want to know that is there any other method to solve this.

You could add an extra property/method with no parameters to the Video model and call that property to obtain the filtered queryset.
For example:
class Video(models.Model):
    # …

    @property
    def audio_streams(self):
        return self.streams.filter(audio_only=True)
and then thus use {% for video in videos.audio_streams %}. But regardless, the Django template language has been deliberately restricted to prevent people from writing this: a template should implement rendering logic, not business logic: business logic belongs in the models and the views. So the only clean solution is to filter in the view, not the template.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run an ABCL code that uses cl-cppre With reference to my previous question,
Executing a lisp function from Java
I was able to call lisp code from Java using ABCL.
But the problem is, the already existing lisp code uses CL-PPCRE package.
I can not compile the code as it says 'CL-PPCRE not found'.
I have tried different approaches to add that package,
including
1) how does one compile a clisp program which uses cl-ppcre?
2)https://groups.google.com/forum/#!topic/cl-ppcre/juSfOhEDa1k
Doesnot work!
Other thing is, that executing (compile-file aima.asd) works perfectly fine although it does also require cl-pprce
(defpackage #:aima-asd
(:use :cl :asdf))

(in-package :aima-asd)

(defsystem aima
  :name "aima"
  :version "0.1"
  :components ((:file "defpackage")
           (:file "main" :depends-on ("defpackage")))
   :depends-on (:cl-ppcre))

The final java code is
interpreter.eval("(load \"aima/asdf.lisp\")");
interpreter.eval("(compile-file \"aima/aima.asd\")");
interpreter.eval("(compile-file \"aima/defpackage.lisp\")");
interpreter.eval("(in-package :aima)");
interpreter.eval("(load \"aima/aima.lisp\")");
interpreter.eval("(aima-load 'all)");

The error message is
Error loading C:/Users/Administrator.NUIG-1Z7HN12/workspace/aima/probability/domains/edit-nets.lisp at line 376 (offset 16389)
#<THREAD "main" {3A188AF2}>: Debugger invoked on condition of type READER-ERROR
  The package "CL-PPCRE" can't be found.
[1] AIMA(1):

Can anyone help me?

A: You need to load cl-ppcre before you can use it.  You can do that by using (asdf:load-system :aima), provided that you put both aima and cl-ppcre into locations that your ASDF searches.

A: I used QuickLisp to add cl-ppcre (because nothing else worked for me).
Here is what I did
(load \"~/QuickLisp.lisp\")")
(quicklisp-quickstart:install)
(load "~/quicklisp/setup.lisp")
(ql:quickload :cl-ppcre)

First 2 lines are only a one time things. Once quickLisp is installed you can start from line 3.


text:
Q: How to check if gcc has failed, returned a warning, or succeeded in Bash? How would I go about checking whether gcc has succeeded in compiling a program, failed, or succeeded but with a warning?
#!/bin/sh

string=$(gcc helloworld.c -o helloworld)

if [ string -n ]; then
    echo "Failure"
else
    echo "Success!"
fi

This only checks whether it has succeeded or (failed or compiled with warnings).
-n means "is not null".
Thanks!
EDIT If it's not clear, this isn't working.

A: Your condition should be:
if [ $? -ne 0 ]

GCC will return zero on success, or something else on failure.  That line says "if the last command returned something other than zero."

A: if gcc helloworld.c -o helloworld; then
echo "Success!";
else
echo "Failure";
fi

You want bash to test the return code, not the output. Your code captures stdout, but ignores the value returned by GCC (ie the value returned by main()).

A: To tell the difference between compiling completely cleanly and compiling with errors, first compile normally and test $?. If non-zero, compiling failed. Next, compile with the -Werror (warnings are treated as errors) option. Test $? - if 0, it compiled without warnings. If non-zero, it compiled with warnings.
Ex:
gcc -Wall -o foo foo.c
if [ $? -ne 0 ]
then
    echo "Compile failed!"
    exit 1
fi

gcc -Wall -Werror -o foo foo.c
if [ $? -ne 0 ]
then
    echo "Compile succeeded, but with warnings"
    exit 2
else
    echo "Compile succeeded without warnings"
fi


text:
Q: Avoiding many nested callbacks when animating multiple objects I need to animate opacity of 3 images one by one in a loop ... I write the code below and its working fine but is this code good or we can optimise it. Any sugessions please.
function animateit(play){
            if(play==false){
                $(".img2", obj).stop(true, true).fadeTo('800', 0);
                $(".img3", obj).stop(true, true).fadeTo('800', 0);
                $(".img4", obj).stop(true, true).fadeTo('800', 0);
            }
            if(play==true){
                $(".img2", obj).animate({opacity:"1"}, s, e,
                    function(){
                        $(".img3", obj).delay(p).animate({opacity:"1"}, s, e,
                            function(){
                                $(".img2").css({opacity:"0"});

                                $(".img4", obj).delay(p).animate({opacity:"1"}, s, e,
                                    function(){
                                        $(".img3").css({opacity:"0"});
                                        $(".img4", obj).delay(p).animate({opacity:"0"}, s, e,
                                            function(){
                                                $(".img4", obj).delay(p).animate({opacity:"0"}, s, e,
                                                    function(){
                                                        if(play==true)animateit(true);
                                                    });

                                            });
                                    });
                                });
                        });
                }
            }

A: For a version that's easier to read and maintain, you can use the jquery-fxQueues plugin which overloads the $.animate() function to support global animation queues. This means that your code can be written simply as:
function animation() {
    var o2 = $(".img2", obj),
        o3 = $(".img3", obj),
        o4 = $(".img4", obj);
    o2.animate({opacity: "1"}, {duration:s, queue: "global", postDelay:p});
    o3.animate({opacity: "1"}, {duration:s, queue: "global"});
    o2.animate({opacity: "0"}, {duration:0, queue: "global", postDelay:p});
    o4.animate({opacity: "1"}, {duration:s, queue: "global"});
    o3.animate({opacity: "0"}, {duration:0, queue: "global", postDelay:p});
    o4.animate({opacity: "0"}, {duration:s, queue: "global", postDelay:p,
                                complete:animation}); // repeat when done
}

Demo to show this in action: http://jsfiddle.net/RMVtU/2/
For a reference, here's your version as  a fiddle as well: http://jsfiddle.net/dEfY7/
Important Note: There is a potentially huge drawback to this plugin though. As far as I know, the latest version of fxQueues (2.0.3) only works with jQuery 1.3.x.

Update (non-plugin version)
If the limitations of fxQueues is a deal breaker, it is still possible to roll your own global animation queue using $.queue() and $.dequeue() on a proxy object.
Here's an example: http://jsfiddle.net/mAfFW/
/* functions to emulate a global queue */
var Q = $({}); // empty object to store global queue
var enQ = function(func) { Q.queue("global", func); } // add to queue
var deQ = function() { Q.dequeue("global"); }  // pop next animate
var stopQ = function() { Q.clearQueue("global"); }  // clear animation

function animate() {
    enQ(function() {
        o2.animate({opacity: "1"}, s, e, deQ);
    });
    enQ(function() {
        o3.delay(p).animate({opacity: "1"}, s, e, deQ);
    });
    enQ(function() {
        o2.css("opacity", "0");
        o4.delay(p).animate({opacity: "1"}, s, e, deQ);
    });
    enQ(function() {
        o3.css("opacity", "0");
        o4.delay(p).animate({opacity: "0"}, s, e, deQ);
    });
    enQ(function() {
        o3.css("opacity", "0");
        o4.delay(p).animate({opacity: "0"}, s, e, deQ);
    });
    enQ(animate); // repeat when done
    deQ();  // start the animation by dequeueing an entry
}

It's not as clean as using fxQueues, but it's certainly more readable than a series of nested callbacks.
For a comprehensive explanation of $.queue() and $.dequeue() with examples, check out this answer: What are queues in jQuery?


text:
Q: Angular 2 don't dectect change on an Observable I develop an application with Angular 2.
I have a problem with dectection change in Angular.
I explain :
I have a component:
test.component.ts
@Component({
  selector: 'test',
  template: `
  <h1> Observable </h1>
  <p *ngFor="let exam of listeExamen"> {{exam.patient.name}}</p>
  <button (click)="test()">push</button>
  `
})
export class TestComponent implements OnInit{
  listeExamen: Examen[];

  constructor(public rechercheService: RechercheService){
    this.listeExamen = [];
  }
  ngOnInit(){
    this.rechercheService.retrieveStudies()
      .subscribe((resultat) => {
        let patient = this.getPatient(resultat);
        let study = this.getStudy(resultat);
        this.listeExamen = this.listeExamen.concat([new Examen(patient, study)]);
      });
  }
  test(){
    console.log(this.listeExamen);
  }
}

This component call a service method who request a server to get result with an observable :
recherche.service.ts
@Injectable()
export class RechercheService{
  private champ;
  private resultatRecherche;
  private dicom;
  private client;
  private services;

  constructor(){
      this.champ = infoRecherche;
      this.dicom = require("./app/dicomRequest/dicom.js");
      this.client = this.dicom.loadClient('localhost',
      11112, 'FINDSCU', 'DCM4CHEE');
      this.services = this.dicom.loadServices();
      this.client.on('error', () => {
        console.log("erreur de connexion");
      });
  }
  retrieveStudies(): Observable<any>{
    return new Observable<any>(observer => {
      this.client.connect( () => {
        let cfind = new this.services.CFind();
        this.client.addService(cfind);
          let studyIds = [];
          cfind.retrieveStudies(this.champ,
          [(result) => {
            observer.next(result);
          }]);
        });
    });
}

The retrieveStudies method stack the result and component convert and stack this result in a listeExamen. This tab is bind to template of component.
The Observable make his job and stack well all results in tab.
The problem is Angular don't update the view.
Result after observable do his job:
enter image description here

Result after click on "appuie" :
enter image description here
Result appear in view after emit user's event.
How update view automaticaly?
Thanks.


text:
Q: Visual Studio 2015 Windows Phone Emulator not deploying 6 I have been facing the same issue as asked in this other post
Visual Studio 2015 Windows Phone Emulator not deploying
but the solution worked here is not working for me.
Windows 10 pro upgraded from home version
Visual Studio 2015
Apache Cordova "Sample" app.
In Emulator it is showing as "Starting
in the behind "Hyper-V" "Summary" it is visible but if double click the the Hyper-V "instance" it is not visible there but only in "Summary"
What am I missing here?
For the developer sake and investment, MS must make sure that the solutions are tested everywhere before releasing them.
This link will direct you to print screen of the error. https://prnt.sc/cykrgg
in the VS output we get the following last message.
My OS is 64 bit.
2>The build configuration was changed to x86 for x86-based emulator deployment.
could this be impact of 64 to 86 bit version difference or anything else?
I have Norton antivirus
I am getting
Hyper-v administrator pop up every time I try to run the app.

A: This case is resolved by Microsoft Support Team over a Ticket and Rohit, support engg from MS did really helped me a lot.
The reason why it was not coming up.....
My machine has a AdWareAntiVirus from Lavasoft by Name WebCompanion that was not allowing it work.
I removed it then it started working.
if any body have any problem with VS 2015 Emulator definitely focus on the Antivirus and include the Emulator XDE into exception list and also include in Firewall.
Thanks,
Ekambar


text:
Q: Dynamically fetching property of Node Neo4j This is my Neo4jRepository method
@Query("match (pofr:NODE) where pofr.param1= {param1} return pofr.{param2}, pofr.param3")
    List<Node> getPropertiesOfNode(@Param("param1") String param1, @Param("param2") String param2);

ExceptionLogs:
    Error executing Cypher; Code: Neo.ClientError.Statement.SyntaxError; Description: Invalid input '{': expected an identifier, whitespace, a function name or a property key name (line 1, column 64 (offset: 63))
"match (pofr:NODE) where pofr.param1 = {param1} return pofr.{param2}, pofr.param3"
                                                                ^; nested exception is org.neo4j.ogm.exception.CypherException: Error executing Cypher; Code: Neo.ClientError.Statement.SyntaxError; Description: Invalid input '{': expected an identifier, whitespace, a function name or a property key name (line 1, column 64 (offset: 63))

I'm facing issue while attempted to populate property data dynamically. Do we have any other approach to achieve this?

A: Since Cypher does not support placeholders at those positions it is unfortunately not possible to solve this in Spring Data Neo4j.


text:
Q: What does sendmail need to specifically see in order to determine if a remote MTA supports 8-bit MIME transport? I'm troubleshooting an intermittent issue where some international characters appear to be malformed after going through sendmail.
I recently came across this article which describes the F=7 delivery agent flag.  Specifically, the article mentions that

Beginning with V8.7, the F=7 delivery agent flag can be used to
  suppress certain kinds of MIME conversions. For example, if the
  EightBitMode option (EightBitMode on page 1025) is set to p (pass 8)
  and if the message contains 8-bit MIME data in its body, this F=7
  delivery agent flag will force sendmail to bounce the message with the
  following SMTP error, and to exit with EX_DATAERR:

My question is: what does sendmail specifically look for to determine if the downstream MTA supports 8-bit mime?  In response to a EHLO, the downstream server is advertising:
250-PIPELINING
250-SIZE 200000000
250-VRFY
250-STARTTLS
250-ENHANCEDSTATUSCODES
250 8BITMIME

Note that it's 250 8BITMIME and not 250-8BITMIME (with the dash). Would this be enough for sendmail to consider that the remote source doesn't support 8bitmime?

A:
Note that it's 250 8BITMIME and not 250-8BITMIME (with the dash).
  Would this be enough for sendmail to consider that the remote source doesn't support 8bitmime?

No. This is called continuation and it only signifies that the line is the last line of the SMTP reply.
And generally 8BITMIME should be the only thing required to show that the MTA on the other side is able to handle 8 bit messages. (This is the externsion marker of the relevant RFC6152.)


text:
Q: Replace value in the same column based on ID number EXCEL Does anyone have an idea how to solve this problem using Excel? I have this table. As you can see there is false information in the data, as the "Customer_since" column has different values for the same customer (column "cust_id"). "Customer since" column defines the year of the customer's first purchase. Here is the table:

In fact, the year of the first purchase must be the same in all rows for the same client. In my solution, I would like to keep the earliest year (of the first purchase) for all clients. As you can see one client can appear in many rows, for example, client 275250 had 8 purchases (means 8 rows in a data set) and client 275246 had only 4 purchases. I cannot change it manually as the data set contains over 7000 rows. The desired solution would be to get the same year of their first purchase for the same customer in all rows (for example, correct data is for 275252 and 275233 customers).

A: MINIFS will get you there. https://support.microsoft.com/en-us/office/minifs-function-6ca1ddaa-079b-4e74-80cc-72eef32e6599
Below, I'm using formula =MINIFS(C:C,B:B,B2) where C:C would be the range of your transaction dates, B:B is the range of customer IDs, and B2 is the current customer ID.

A: I would do the following:

*

*Create a new table with unique cust_id and the corresponding min(Customer_since). A PivotTable would do it easily.

*Change the column Customer_since to use XLOOKUP() to find the correct value on the new table.
If needed, you can do it on another worksheet and Paste Values back into this.


text:
Q: Error in for loop - attempt to select less than one element in integerOneIndex I'm trying to translate a C routine from an old sound synthesis program into R, but have indexing issues which I'm struggling to understand (I'm a beginner when it comes to using loops).
The routine creates an exponential lookup table - the vector exptab:
# Define parameters
sinetabsize <- 8192
prop <- 0.8
BP <- 10
BD <- -5
BA <- -1

# Create output vector
exptab <- vector("double", sinetabsize)

# Loop
while(abs(BD) > 0.00001){
  BY = (exp(BP) -1) / (exp(BP*prop)-1)
  if (BY > 2){
    BS = -1
  }
  else{
    BS = 1
  }
  if (BA != BS){
    BD = BD * -0.5
    BA = BS
    BP = BP + BD
  }
  if (BP <= 0){
    BP = 0.001
  }
  BQ = 1 / (exp(BP) - 1)
  incr = 1 / sinetabsize
  x = 0
  stabsize = sinetabsize + 1
  for (i in (1:(stabsize-1))){
  x = x + incr
  exptab [[sinetabsize-i]] = 1 - (BQ * (exp(BP * x) - 1))
  }
}

Running the code gives the error:
Error in exptab[[sinetabsize - i]] <- 1 - (BQ * (exp(BP * x) - 1)) :
  attempt to select less than one element in integerOneIndex

Which, I understand from looking at other posts, indicates an indexing problem. But, I'm finding it difficult to work out the exact issue.
I suspect the error may lie in my translation. The original C code for the last few lines is:
for (i=1; i < stabsize;i++){
  x += incr;
  exptab[sinetabsize-i] =  1.0 - (float) (BQ*(exp(BP*x) - 1.0));
}

I had thought the R code for (i in (1:(stabsize-1))) was equivalent to the C code for (i=1; i< stabsize;i++) (i.e. the initial value of i is i = 1, the test is whether i < stabsize, and the increment is +1). But now I'm not so sure.
Any suggestions as to where I'm going wrong would be greatly appreciated!

A: As you say, array indexing in R starts at 1.  In C it starts at zero.  I reckon that's your problem.  Can sinetabsize-i ever get to zero?


text:
Q: Problem/Answer Counter I'm writing solutions to some problems in lecture notes and have run into the issue of problem and answer counters not being synchronized. Here's what I mean:

To get around this issue (of it saying Answer 1.2 rather than 1.3), I've just added the extra line
\setcounter{answer}{2}

, but this is somewhat burdensome when I rearrange problems and have to manually set many answer numberings. Is there a solution to this? For reference, here is my LaTeX code:
\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{thmtools}

\theoremstyle{definition}
\declaretheorem[name=Problem,numberwithin=section]{prob}
\declaretheorem[name=Answer,numberwithin=section]{answer}
\newenvironment{solution}{\begin{trivlist}\item[]{\textbf{Solution.}}}{\qed \end{trivlist}}

\begin{document}
\section{Section Title}

\begin{prob}
Problem text.
\end{prob}

\begin{answer}
Answer.
\end{answer}

\begin{solution}
Solution text.
\end{solution}

\begin{prob}
This is a proof problem.
\end{prob}

\begin{proof}
Proof text.
\end{proof}

\begin{prob}
Problem text.
\end{prob}

\begin{answer}
Oh no, the answer numbering is bad.
\end{answer}
\end{document}

A: Here's a solution using amsthm's environments, but defining other environments from them to adjust the counters when problems and answers are called.

\documentclass{article}
\usepackage{amsmath,amsthm}
\theoremstyle{definition}
\newtheorem{prob}{Problem}
\newtheorem{ans}{Answer}
\numberwithin{prob}{section}
\numberwithin{ans}{section}
\newenvironment{problem}{%
    \addtocounter{ans}{1}
    \begin{prob}
    }{%
    \end{prob}
}
\newenvironment{answer}{%
    \addtocounter{ans}{-1}
    \begin{ans}
    }{%
    \end{ans}
}
\begin{document}
\section{First section}
\begin{problem}
Problem text.
\end{problem}
\begin{answer}
Answer.
\end{answer}
\begin{problem}
Proof problem without answer.
\end{problem}
\begin{problem}
Problem text.
\end{problem}
\begin{answer}
Yeah, the answer number is right!
\end{answer}
\end{document}


text:
Q: Can't use string as a value for _id in Elasticsearch Heyo,
We have a document object with property Id (that we know auto maps to the _id field) and we can get it to work as an int and a System.Guid.
However when we change it to a string, which would better fit our use case, we get the following exception when trying to index:
mapper_parsing_exception Reason: failed to parse [id] CausedBy: Type: illegal_argument_exception Reason: For input string: "R700"
Not really sure what to try here. We want to have a string _id and according to online resources we should be able to, however we get this exception.
Any help much appreciated!
EDIT: we are inferring the Id from a property named Id on the POCO, I should have clarified.
Example:
public class MyDocument {
    public string Id { get; set; }
    ...
}

A: If you have already created the index with an int or a guid as the Id field, you will need to recreate the index with the new POCO that has the string as the Id field before you can store that type in the index.

A: Another option will be to create proper mappings for all your fields so auto-inference will be disabled.


text:
Q: How to change layout by pressing the button? I am trying to bring a new layout by pressing a button in my android app. Here is the code piece:
Button button = (Button)findViewById(R.id.btnAccept);
button.setOnClickListener(new View.OnClickListener() {
    LayoutInflater layoutInflater = LayoutInflater.from(getBaseContext());
    View promptView = layoutInflater.inflate(R.layout.empty_layout, null);

    public void onClick(View v) {

        // What should I write here to prompt empty_layout?
    }
}

I dont know how to use "promptView". Can you give me some insight please?
Thank you guys!

A: If its the whole view of your screen then use
setContentView(prompView);

If its only a portion of a view then use
yourPortionViewContainer.addView(prompView);

Or may be you could use Fragment.

A: you should create Intent to open new Activity or create Fragment and let FragmentManager show it.

A: I don't know if i understand your question correctly but what I would do to add a layout when a button is pressed is to do it programmatically like this:
    LinearLayout mainLayout;
    mainLayout = (LinearLayout)findViewById(R.id.mainLayout)//assuming u gave the main layout an id of mainLayout in your XML file
    public void onClick(View v) {
          LinearLayout layout = new LinearLayout(this);
          LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);//create variable to store layout parameters
          layout.setOrientation(LinearLayout.VERTICAL);//set orientation of layout
          layout.setLayoutParams(params);//set layout parameters
          mainLayout.addView(layout);//add the newly created layout to the already existing layout
}


text:
Q: Having trouble implementing quicksort in c# I'm having a bit of trouble trying to get this quicksort algorithm to work 100%. As of now, it's getting hung up a bit when it tries to swap 2 numbers that are the same (tried to remedy that as you'll see in the code).
The darn thing is almost there. I'm just not sure what I'm missing. I spent a few hours trying to figure it out to no avail.
I am doing this for class, unfortunately my teacher said he can't help me, since I'm doing generics (for extra credit) and he can only pull of strings or integers in C# (he's mainly a java/c++ teacher....he hasn't been working with c# for very long).
Quicksort static class
class QuickSort<T> where T : IComparable<T>
{
    //No variables or properties, more of a helper class

    //This is the method that will be called by the user.
    //It ties the internal methods into one to sort the
    //array. It needs an array passed into it, As well as
    //the size of the array.
    public static void  QSort(T[] array,int size)
    {
        //If array is empty, or has 1 element, it is sorted.
        //Return immediatly.
        if (size == 1 || size == 0)
        { return; }
        else
        {
            //Time to sort, pass in the array, the left bounds of 0,
            //and the right bounds of high - 1 (the last element).
            Partition(array, 0, size);
        }
    }

    //This method splits the work area in half, putting lower
    //values left of the pivot, and greater values right of
    //the pivot.
    private static void Partition(T[] array, int lower, int upper)
    {
        //If upper is less 1, then there is no
        //sorting that can be done.
        if ((upper - lower) < 2)
        { return; }

        //Get the right bound -1, to make sure it stays
        //within actual array bounds
        int left = lower;
        int right = upper-1;

        //Set pivot to equal the middle most array. I used this
        //expression because wikipedia mentions it will stop
        //overflow and invalid pivot position that can come
        //with exceptionally large arrays using the basic
        //(a+b)/2 equation.
        int pivot_index = left + (right - left) / 2;
        T pivot = array[pivot_index];

        while (left < right)
        {
            //array[left] < pivot
            while ((array[left].CompareTo(pivot) <= 0) && (left < right))
            {
                left++;
            }
            //array[right] > pivot
            while ((array[right].CompareTo(pivot) >= 0)&& (left < right))
            {
                right--;
            }

            if (left != right)
            {
                Swap(array, left, right);
                left++;
                right--;
            }
        }

            //Send in the lower bound, and the pivot point.
            Partition(array, lower, right);

            //Send in the pivot point as lower bound, and upper
            Partition(array, right+1, upper);

    }

    //This method simply swaps the first position with the second.
    private static void Swap(T[] array, int position1, int position2)
    {
        T tempHolder = array[position1];
        array[position1] = array[position2];
        array[position2] = tempHolder;
    }

}

Main class
class Tester
{
    static void Main(string[] args)
    {

        ContiguousList<int> tester = new ContiguousList<int>(100);
        Random rand = new Random(5433);
        for (int ii = 0; ii < tester.Size; ii++)
        {
            tester.SetElement(ii, rand.Next(0, 100));
        }

        for (int ii = 0; ii < tester.Size; ii++)
        {
            Console.WriteLine(tester.GetElement(ii).ToString());
        }
        Console.WriteLine();

        tester.Sort();
        for (int ii = 0; ii < tester.Size; ii++)
        {
            Console.WriteLine(tester.GetElement(ii).ToString());
        }

    }
}

It's proving rather difficult for me since the only online implementations that I can follow are either for c++ (found a good psuedocode explanation that would work if I could use pointers >.<) or their only for sorting integers.
I'm thinking maybe a swap is missing, or my logic for dealing with if array[left] == array[right]  is faulty.
(Oh, and don't mind the ContiguousList thing in main...our teacher had us code our own smart array and told us to use that, so we can see how smart arrays work.)
Thanks for any help folks. My brain is really stumped on this one.
--Edit
I changed the loops, so one checks >= 0, the other < 0 to get rid of a non-needed check.
--Edit
I tweaked it a bit again, now it seems it's almost sorted still,but not quite, my first 10 elements are  1,1,2,3,2,3,6,5,4,5 so somehow someway something is not getting swapped right when the values are the same.
Edit--
Just re-read the quicksort explanation/pseudocode I was using, and noticed a little "this version will only work on arrays with unique elements" warning...so I'm right, in that it has to do when 2 elements hold the same value, something is not working... Stumped on how to fix it atm though >.<

A: The left element can't be less than the pivot, because of the first loop. And the right element can't be more than the pivot, because of the second loop. So if they are equal, then they must both equal the pivot, and therefore it doesn't matter which half of the array they end up in.
Anyway, I think all you need to do to fix your code is to tweak these lines slightly:
        if (array[left].CompareTo(array[right]) == 0)
        {
            left++;
            right--;
        }
        else if (left != right)
        {
            Swap(array, left, right);
            left++;
            right--;
        }

But there are a couple of simplifications:

*

*Because left == right implies array[left].CompareTo(array[right]) == 0), your left != right test is superfluous.

*As a corollary, you always end up incrementing left and decrementing right. So you can move that outside the conditional.

Thus the resulting code looks like this:
        if (array[left].CompareTo(array[right]) != 0)
        {
            Swap(array, left, right);
        }
        left++;
        right--;

A: You should change your swap method to swap the actual data, instead of accessing the arrays. In C# you need 'ref' so any data is send along as reference:
    private static void Swap(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }


text:
Q: Get Handle on last worksheet copied by Worksheet.Copy I'm trying to get a handle to the worksheet that was created by a copy operation. following code used to work:
Dim wsTempl As Worksheet, pageCount as Long
Set wsTempl = Sheets("Template")
For pageCount = 1 To 5
   wsTempl.Copy After:=Sheets(Sheets.Count)
   Set ws = Sheets(Sheets.Count)
   ws.Name = "p" & pageCount
Next

But stopped when adding VeryHidden worksheets to the workbook. now my Sheets(Sheets.Count) is getting the VeryHidden sheet instead of the sheet I added last.
Of course I could use
Set ws = Sheets(wsTempl.Name & " (2)")
ws.Name = "p" & pageCount

But that seems so ugly, is this really the only way? Can somebody think of another way?
to replicate the issue:

*

*Open a New workbook, Name the first Sheet 'Template' & delete the other sheets

*alt-f11 - insert code module & paste the above code

*F5 should show you that it works.

*insert a worksheet, using the worksheet tabs drag it to the end of collection

*set it to VeryHidden in VBA IDE

*F5 again, the first code listing should fail

Reason seems to be that the Copy After:= does not copy after VeryHidden Sheets, thus the part of the code to rename the sheet always renames the VeryHidden Sheet

A: The Copy method of a worksheet makes the newly created sheet active so you should be able to do this.

Dim wsTempl As Worksheet, i as int
Set wsTempl = Sheets("Template")
For i = 1 To 5
   wsTempl.Copy After:=Sheets(Sheets.Count)
   Set ws = ThisWorkbook.ActiveSheet
   ws.Name = "p" & pageCount
Next


text:
Q: Laravel Form and Submitting to DB, is there anothe rway for this function I am creating a vehicle inspection with approx 54 different checks, the form has Red, Amber, Green for the checks and if Red is selected it opens a repeater form where the user can select various defects from a select form.
I have no issues with the form updating the DB but I am just wondering if there is an  easier way to create this function.
Currently I am using this in the InspectionsController
public function StoreInspection(Request $request, $id) {
    $data = Inspection::find($id);

    $data->external_lights_result = $request->external_lights_result;
    $data->external_lights = $request->external_lights;

    for($i = 0; $i < count($request->external_lights); $i++){}

    $data->dash_lights_result = $request->dash_lights_result;
    $data->dash_lights = $request->dash_lights;

    for($i = 0; $i < count($request->dash_lights); $i++){}

    $data->update();

    $notification = array(
        'message' => 'Inspection Added Successfully',
        'alert-type' => 'success'
    );

    return redirect()->route('frontend.vehicle.view')->with($notification);
}

So the question is: do I have to repeat this process 54 times or is there a shortcut or other way I could approach this to reduce the amount of code I will have to write for this single function?
A bit more insight into my code: This is where the user has selected red, amber or green
$data->external_lights_result = $request->external_lights_result;

And obviously this is the Repeater form selections
$data->external_lights = $request->external_lights;

for($i = 0; $i < count($request->external_lights); $i++){}

Any help on this one would be grealty appreicated and if it is the case that I have to repeat this step 54 times then so be it
Thanks


text:
Q: How can I create a timeline in Access? In Access I have an MachinesList and ActionsList. A Machine can be set to Active and set to Inactive several times per year. Each change of status has its own ActionID and ActionDate.
In VBA I added some code to get the first and last date the Machine is Active. As this can happen more than once I now can create a list with start- and enddates each time the Machine is Active.
Two questions:
1) Can this be done with a query instead of VBA?
2) Is it possible to display these dates in some sort of timeline in Access?
This is what I have to create my list of dates:
SELECT DISTINCT Requests.RequestNumber, Requests.MachineID, Actions.Assignee, Actions.Action, Actions.TRDate FROM SelectedIDs LEFT JOIN (Requests LEFT JOIN Actions ON Requests.RequestNumber = Actions.RequestNumber) ON SelectedIDs.MachineID = Requests.MachineID ORDER BY Requests.MachineID, Actions.TRDate;

I do need the RequestNumber and the Assignee (in case of Activation) for further use. And since the RequestNumber for Activation and Deactivation differ I cannot use the MIN(date) and MAX(date) functionality because of the GROUP BY clause.
The list produced in VBA looks somewhat like this:
2325          ID1234     29-11-2016    16-3-2017
2323          ID1234     28-3-2017     27-4-2017
2203          ID9999     25-1-2017     27-2-2017

This list I want to see in some sort of timeline in Access.
Something like this:
ID | wk01 | wk02 | wk03 | etc
88 | N | N | Y | Y | Y | N
99 | N | Y | Y | N  | N | Y
But any timeline is fine. Suggestions anyone?
Thanks, Karin

A: It is possible to do, yes. Your resulting recordset will not be tabular, it will be more like { Week, MachineID, Active } and it will be up to you to format it for reporting purposes. It may take a few subqueries, for example an obvious one is max of activation date before the week's end, and min de-activation date after that activation date. If that deactivation date is before the week's start the machine was not active. The actual SQL depends on how your Week table is defined. If you don't have a week table things get a bit more complicated as you also need a sub-query that replaces the week table.


text:
Q: How to return an array from an express node api I am trying out json-rules-engine and I thought of making an extremely simple express api to try it out. But, it turns out it's giving me a tough time.
The array I am trying to return in the body is always an empty one, even if I do console.log in the map it actually logs the messages.
I have this controller:
'use strict';

var rulesEngine = require('./rulesEngine');

exports.run = function(req, res) {
  var outcome = rulesEngine.run(req.params.numberOfFaults);
  res.json({outcome: outcome});
}

And the rulesEngine run method would be this one:
exports.run = function(numberOfFaults) {
  var facts = {
    personalFoulCount: numberOfFaults,
    gameDuration: 40
  },
  outcome = [];
  rulesEngine
    .run(facts)
    .then(events => { // run() returns events with truthy conditions
      events.map(event => outcome.push(event.params.message))
  })
  return outcome;
};

Thanks!

A: You need to wait for the promise to complete before you return the outcome variable. Right now you're calling rulesEngine and return outcome right after, which in an asynchronous language like Javascript gets run immediately after one another.
Place the 'return outcome' inside the .then like so:
exports.run = function(numberOfFaults) {
  var facts = {
    personalFoulCount: numberOfFaults,
    gameDuration: 40
  },
  outcome = [];
  return rulesEngine
    .run(facts)
    .then(events => { // run() returns events with truthy conditions
      events.map(event => outcome.push(event.params.message))

      return outcome;
  })
};

A: You are dealing with rulesEngine.run() like it was synchronous, but it is asynchronous.
You gotta wait for it to finish in order to quit your run function.
For example :
      exports.run = function (req, res) {
          rulesEngine.run(req.params.numberOfFaults)
            .then((ret) => {
              res.json({
                outcome: ret,
              });
            })
            .catch((err) => {
              // Deal with error
            });
        }

     exports.run = function (numberOfFaults) {
      return new Promise((resolve, reject) => {
        const facts = {
          personalFoulCount: numberOfFaults,
          gameDuration: 40
        };

        rulesEngine
          .run(facts)
          .then(events => resolve(events.map(event => event.params.message)))
          .catch(reject);
      });
    }


text:
Q: Mapping lakes in an area I am working on a project and the very first requirement is to map all the lakes near a location and get their lat/lng. Google map shows lots of lakes but it is tough to zoom and search for several lakes/ponds and note its coordinate manually. How would i use google maps and find all the lakes near a county, location or coordinate.  Help would be very much appreciated.
Thank you!
Vinay

A: You can create a 1-bit (black and white) image from the map and separate the lakes and the land. Then find the lakes hull.


text:
Q: How to get absolute value by where condition in laravel?                public function getList(Request $request)
              {
                 $keyword = $request->keyword;
                 $status = $request->status;
                 $userId = $request->userId;
                 $list = DB::table('user')
                    ->selectRaw("user.id, user.name, user.email, user.status")
                    ->whereIn('user.id', $userId)
                    ->when(!empty($keyword), function ($query) use ($keyword) {
                        $query->where('user.name', 'like', '%' . $keyword . '%');
                        $query->orWhere('user.email', 'like', '%' . $keyword . '%');
                    })
                    ->when(!empty($status), function ($query) use ($status) {
                        $query->where('user.status', '=', $status);
                    });
                    $list->get()->toArray();
              }

In laravel i am doing search function by email, name and status.
The above code worked out..But there is a small problem:
              {
                    "id": 10,
                    "name": "jony",
                    "email": "user1@gmail.con",
                    "createdAt": "05-05-2021 08:43:05",
                    "status": "2"
                },
                {
                    "id": 11,
                    "name": "test",
                    "email": "jony@gmail.com",
                    "createdAt": "05-05-2021 08:43:05",
                    "status": "1",
                }

When I enter keyword with the keyword jony it gets 2 such items, this is correct.
BUT when I set status equal to 1 or equal to 2 the result stays the same.. Is there any way to get the result according to the correct status. Please advise me. Thanks.

A: The problem is on your orWhere clause, you may want to enclose that to a group (put the query into a parentheses, for more info go HERE).
Here's what you want to to achieve:
public function getList(Request $request)
{
    $keyword = $request->keyword;
    $status = $request->status;
    $userId = $request->userId;
    $list = DB::table('user')
    ->selectRaw("user.id, user.name, user.email, user.status")
    ->whereIn('user.id', $userId)
    ->when(!empty($keyword), function ($query) use ($keyword) {
        $query->where(function ($query) use ($keyword) {
            $query->where('user.name', 'like', '%' . $keyword . '%');
            $query->orWhere('user.email', 'like', '%' . $keyword . '%');
        });
    })
    ->when(!empty($status), function ($query) use ($status) {
        $query->where('user.status', '=', $status);
    });
    $list->get()->toArray();
}


text:
Q: Move sheet to workbook with a given variable name and variable sheet count I am trying to write a macro that will move a worksheet (order_line_list) from its workbook to a position after the last sheet of another workbook (Accrual Planning by Month 2020).
The Accrual Planning by Month workbook file name isn't constant, so I have set it up as a variable in the code. The last sheet of that workbook will also change every month as a new sheet is added.
I can get the macro to work if I use the full file name and specify a sheet position (after sheet 2). However, if I try to do it with the file name and sheets count variables, I receive a the following error:
Run-time error 1004: Move Method of Worksheet Class Failed

I tried to use the Copy method instead, but I just receive the same Method Failed error.
I have spent multiple hours researching and trying to figure this out, but have not been able to. I'm new to VBA so there is likely a much simpler way to do what I am trying to do. Below is my code. I have files but can't seem to figure out how to attach them. Your help would be greatly appreciated.
Function wbname(MatchName As String) As String

   Dim wb As Workbook

For Each wb In Workbooks

   If wb.Name Like MatchName Then

    wbname = wb.Name

    Exit Function

  End If

Next wb

   wbname = ""

End Function

Sub Macro302()

' Move Sheet to Accrual Planning by Month file

Accrual = wbname("Accrual*")

Windows("order_line_list.csv").Activate

    Sheets("order_line_list").Move After:=Workbooks(Accrual).Sheets.Count

    'Sheets("order_line_list").Copy After:=Workbooks(Accrual).Sheets.Count

'Windows("order_line_list.csv").Close SaveChanges:=False

End Sub


text:
Q: How to update(by merging) edmx without override the model classes in asp.net mvc I am developing an application in asp.net mvc. I use entity framework as ORM. I have a problem. To use javascript unobstrusive validation, I need to add annotation to model objects. For example; [Required], [EMailAddress]. But when we add something to the database and update it, all model classes are override, and all annotations disappear. Or, as soon as you open edmx, automatic model classes are automatically override. How can I solve this problem. There are dozens of screens and classes, the slightest change in edmx erases the annotation in all classes, causing huge waste of time.
// <auto-generated>

using System.ComponentModel.DataAnnotations;

namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;

public partial class Surveys
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Surveys()
    {
        this.SurveyQuestions = new HashSet<SurveyQuestions>();
        this.SurveyCustomers = new HashSet<SurveyCustomers>();
    }

    public int SurveyId { get; set; }
    [Required(ErrorMessage = "Plase enter survey name.")]
    public string SurveyName { get; set; }
    [Required(ErrorMessage = "Please enter survey description.")]
    public string SurveyDescription { get; set; }

    // [DataType(DataType.Date)]
    public System.DateTime? CreatedDate { get; set; }
    //[DataType(DataType.Date)]

    public System.DateTime? UpdatedDate { get; set; }
    public int CreatedUserId { get; set; }
    public bool IsActive { get; set; }
    public bool Status { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<SurveyQuestions> SurveyQuestions { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<SurveyCustomers> SurveyCustomers { get; set; }

    public string Token { get; set; }
}
}

Editted for
Metadata
Surveys Partial & Metadata
 //PartialClass
 [MetadataType(typeof(SurveyMetadata))]
 public partial class Surveys
{
}
//Metadata
 public partial class SurveyMetadata
{
    public int SurveyId { get; set; }
    [Required(ErrorMessage = "Lütfen anket adını giriniz.")]
    public string SurveyName { get; set; }
    [Required(ErrorMessage = "Lütfen anket açıklamasını giriniz.")]
    public string SurveyDescription { get; set; }

    // [DataType(DataType.Date)]
    public System.DateTime? CreatedDate { get; set; }
    //[DataType(DataType.Date)]

    public System.DateTime? UpdatedDate { get; set; }
    public int CreatedUserId { get; set; }
    public bool IsActive { get; set; }
    public bool Status { get; set; }

    public virtual ICollection<SurveyQuestionMetadata> SurveyQuestionMetadatas { get; set; }
    public virtual ICollection<SurveyCustomerMetadata> SurveyCustomerMetadatas { get; set; }

    public string Token { get; set; }
}

GetData Ajax Event
  // GET: Survey
    public ActionResult GetData()
    {
        using (MerinosSurveyEntities entity = new MerinosSurveyEntities())
        {
            List<Surveys> surveys = entity.Surveys.Where(x => x.IsActive && x.Status)
                .OrderBy(x => x.SurveyId).ToList();
            return Json(new { data = surveys }, JsonRequestBehavior.AllowGet);
        }
    }

How I should change my GetData event.And what list should go to the client side??

A: Best Practice is, use ViewModel[Not Entity/Model classes] to manipulate / play at Client Side.
So use ViewModel, Inherit Model classes and then use Annotations
For eg.
    Public class ViewModelClass: ModelClass
       {
         [Required("First Name is Required")]
         Public String FirstName {get; set;}
       }

A: For do such thing you can use partial classes and use "ModelMetadataType" in .net core annotation above your class.
lets do it in code:
this is your model that is created in edmx:
public partial class Student{
     public string FirstName {get; set;}
}

first of all you have to create a partial class in another file with same name as student class and be careful its name space should be same as above class. (classes must be out of edmx file)
[ModelMetadataType(typeof(StudentMetaData))]
public partial class Student{

}

and at the end you must create your metadata class like this:
public class StudentMetaData{
     [Display(name="First Name")]
     public string FirstName {get; set;}
}

now you can update your edmx file without changing the data annotations in your metadata classes.
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.metadatatypeattribute?view=netframework-4.8

A: Working from memory at the moment, but the EF classes are always partial so create another partial implementation of the same class, then add the Interface and Metadatatype binding to that.
// Entity Framework Model
public partial class User
{
    public string Email { get; set; }
    public string Password { get; set; }
}

// Your Interface with data annotations
public interface IUser
{
    [Required]
    string Email { get; set; }

    [Required]
    string Password { get; set; }
}

// Partial Model appling the interface to the entity model
[MetadataType(typeof(IUser))]
public partial class User : IUser
{
}

Under this approach, in the future, you only need to worry about updating your interface should you add new properties

A: Copy the generated CS files (the one's with your table names) that you've already added your annotations to, to another folder, then overwrite the newly generated ones, I do it this way and shall continue to until there's a more hassle-free way to do it.


text:
Q: SerialPort.Close() problem - can't shut down the application with the taskmanager! This is a major issue - I use a serial port in an application here and I poll the status of the attached device by opening and then closing the port again.
If the device fails, SOMETIMES the SerialPort.Close() - method NEVER returns and this is really a show stopper.
The worst thing is that even shutting down the application using the taskmanager fails, it doesn't work (or it is forbidden, by chance).
The attached device is a POS printer (USB) which simulates COM3, it's an Epson TM-T88IV (a very good model, btw).
Does anyone of you have experience with that?

A: Prior to .Net 4.0 a lot could go wrong with USB to SerialPort devices(crash program/system, etc.).  It was easy to test the errors by pulling the USB adapter with the port active.
Recently I ran some tests using .Net 4.0 and it is fixed(certainly improved)???  The test was a simple RX / TX through a USB SerialPort with a loopback, and pull the USB adapter while in use.  My program did not crash, and I was able to re-open the port!  This is a major improvement.

A: While it is sometimes a problem that the SerialPort.Close method deadlocks, that should not prevent Task Manager from killing your process. If you can't kill your process, this is almost certainly due to a bug in the USB serial driver. Unfortunately, your options are most likely these:

*

*don't poll for device status

*get the vendor to fix the bug

*work around the problem by figuring out a way to poll the device status without accessing the serial port

*work around the problem by accessing the device via some other method (perhaps direct USB manipulation)

A: Not possible?
I've got an idea:Put a flag inside the data recieve event that will close the serialcom from inside! Simple!
trying it my self now

A: Repeatedly opening and closing the port is not recommended.  Check the Remarks section in the MSDN Library article for SerialPort.Close().  There's a background thread that needs to shut down before a port can be opened again, that takes time.  The amount of time is not predictable.
The Close() method can easily deadlock if the DataReceived event handler is currently running.  The most typical way to get the deadlock is calling Control.Invoke() in the event handler.  Make sure you don't use any code in the event handler that blocks or requires a thread context switch.  Using BeginInvoke() is fine.
Not being able to kill the program is caused by a problem in the serial port device driver.  Start Taskmgr.exe, Process tab, View + Select Columns and tick "Handles".  If after killing the program, you see the Handles column showing 1 then the serial port driver is hanging on to an I/O request that it doesn't complete.  The process cannot terminate until all its kernel mode threads are exited.
There's little you can do about that particular problem, other than hoping for a driver update or switching to another vendor.  Especially USB serial port emulators are notorious for having lousy device drivers.  You get rid of a troublemaker like that by taking it out the parking lot and running it over with your car several times.
Another typical problem with USB emulators is that they are so easy to disconnect while they are in use.  That works about as well as jerking a flash drive out of the socket while Windows is writing to it.  It would also be a good way to get the device driver hung  .NET versions prior to version 4.0 suffer from a heart attack in a background thread when the device suddenly disappears.  Short from upgrading, a small sign next to the connector that says "Do not disconnect while in use!" is a practical workaround.  They will anyway but get bored with it after a couple of times.
Fwiw, this is otherwise why the "Safely Remove Hardware" tray icon exists.  You'll get a solid "Don't do it!" error as long as your program has the port in use.  But of course, the operating system is powerless to get users to actually use it.  Apple has a patent on a technique to make it fail-safe, detecting the user's fingers on the device :)

A: What about using BackGround thread to poll the device so that it does not stop your application from exiting?

A: you can use this :
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{

    if (_serialPort.IsOpen)
    {
        e.Cancel = true; //cancel the fom closing
        Thread CloseDown = new Thread(new ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang
        CloseDown.Start(); //close port in new thread to avoid hang
    }
}

private void CloseSerialOnExit()
{
    try
    {
        _serialPort.Close(); //close the serial port
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message); //catch any serial port closing error messages
    }
    this.Invoke(new EventHandler(NowClose)); //now close back in the main thread
}

 private void NowClose(object sender, EventArgs e)
{
    this.Close(); //now close the form
}


text:
Q: Haskell: which SOAP client lib to use? I'd like to write s simple Haskell program that connects to a SOAP service. Ideally I'd like to use the service's WSDL and get as straightforward access to the request parameters and response data as possible.
What library do I use?
So far I only found HAIFA but it seems to have stopped developing around 2006, so I'm not sure if it's the right choice.
Update 2015-08-14: As of now, a package named soap, along with protocol support packages soap-tls and soap-openssl is available on hackage and looks alive.

A: As @sclv says, the SOAP heyday was before Haskell was seriously used for web systems. As a result your options for fully-fledged SOAP libs are somewhat restricted.
Obviously, HAIFA was the biggest effort back in the day, but it isn't on Hackage, so you're mostly out of luck there. Looks like shoap was a bit of an attempt at getting something simple working as well.
For rolling your own, there are plenty of XML options to choose from on Hackage,

*

*HaXML,

*haxr

*fancy "conduit"-style xml parsing


text:
Q: How to create a mask over an image (not a clip-path, but the opposite) I'm trying to apply a mask to a div so I can see through it to a background image. Everything I'm seeing is about clip-paths, but I am looking for the opposite of this. Clip-paths show what is in the inside of the clip. I'm trying to have it be a mask, so that you see the outside of the clip.
Here is an example of what I am trying to achieve, and below is a full description of the example.
I have a div with a background image. Inside this div is another div that covers the full width and height of its parent (with the background image), and has a semitransparent (rgba) background color. I'm trying to add a mask to this overlay div (the one with the rgba background color) so that a circle is cut out of the middle that shows the full background image without the color overlay.
Here is a link to a jsfiddle that sets up what I am talking about, but without the mask (since I don't know how to do it).

.backgroundImage {
  width: 100%;
  height: 500px;
  background: url(https://upload.wikimedia.org/wikipedia/commons/4/47/New_york_times_square-terabass.jpg) no-repeat center center;
  background-size: cover
}

.backgroundOverlayWithMask {
  width: 100%;
  height: 500px;
  background-color: rgba(0, 0, 0, 0.75);
}

A: I think I have a solution using box shadow, :after, and flex.  Fiddle.  Based on web-tiki's answer here.

#inner {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  display: flex;
  justify-content: center;
}
#inner:after {
  content: '';
  border-radius: 100%;
  width: 150px;
  height: 150px;
  box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0.5);
  -webkit-box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0.5);
  -moz-box-shadow: 0px 0px 0px 2000px rgba(0, 0, 0, 0.5);
  align-self: center;
}
#container {
  background: url('http://via.placeholder.com/800x200');
  background-size: cover;
}


text:
Q: cono enviar datos a un web service para recibir datos Hola tengo dos cajas de texto su id  son  color y la otra es tamaño estas reciben datos de entrada desde una pagina pero no se como enviar mis campos a el web service para que me regrese datos  mi código es este el url es donde esta mi web service
$.ajax({
        url: '../mesas.php',
        type: 'POST',
        dataType: 'json',
        data: $(this).serialize(),
        beforeSend: function () {
            $("#color").html();
             $("#tamaño").html();
        }
    })

A: Prueba utilizando el siguiente codigo. Lo fui explicando en los comentarios. De todos modos me avisas si no se entiende algo. Saludos!

function enviar()
  $.ajax({

      //Obtengo los valores de mis campos de texto /input
      var color =$("#color").val();
      var tamaño =$("#tamaño").val();

      // En data puedes utilizar un objeto JSON, un array o un query string
      data: {"color" : +'"'+color+'"'+, "tamaño" :'"'+tamaño+'"'},
      //Cambiar a type: GET si necesario
      type: "POST",
      // Formato de datos que se espera en la respuesta
      dataType: "json",
      // URL a la que se enviará la solicitud Ajax
      url: "script.php",
  })
   .done(function( data, textStatus, jqXHR ) {
       if ( console && console.log ) {
           console.log( "La solicitud se ha completado correctamente." );
       }
   })
   .fail(function( jqXHR, textStatus, errorThrown ) {
       if ( console && console.log ) {
           console.log( "La solicitud a fallado: " +  textStatus);
       }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="color" placeholder="Color"/>
<input type="text" id="tamaño" placeholder="Tamaño"/>
<button onclick="enviar();">Enviar</button>


text:
Q: Nestjs: Error discriminator with name "Teacher" already exists I try to set discriminators with mongoose in my nestjs( application that you can find at Github project.
I want that Teacher, Student inherit from Person schema.
Example of code that show how i create Schema:

This is example that import Mongoose module defining descriminators for schemas(Employee,Teacher,Student)

But when i try to start application i have this error in terminal:

This is all nestjs version:
**

*

*@nestjs/common": "^8.0.0",

*"@nestjs/config": "^1.1.6",

*"@nestjs/core": "^8.0.0",

*"@nestjs/jwt": "^8.0.0",

*"@nestjs/mapped-types": "*",

*"@nestjs/microservices": "^8.4.2",

*"@nestjs/mongoose": "^9.0.2",

*"@nestjs/passport": "^8.1.0",

*"@nestjs/platform-express": "^8.0.0",

*"@nestjs/platform-socket.io": "^8.2.4",

*"@nestjs/swagger": "^5.2.0",

*"@nestjs/websockets": "^8.2.4**

*And "typescript": "^4.3.5"

Can i have help please.You can run project locally.


text:
Q: Factoring High School Level Olympiad Problem Factor $x^2 - 3xy + 2y^2 + x -8y - 6$
Attempt at a solution:
I have factored these and don't know how to continue...
$x^2-3xy +2y^2 = (x - y) (x-2y)$
$x^2 + x -6 = (x + 3) (x - 2)$
$2y^2 - 8y + 6 = 2 (y - 3)(y - 1)$

A: Look for in form:
$$x^2-3xy+2y^2+x-8y-6=(x+Ay+B)(x+Cy+D)
$$
Plug $y=0$:
$$x^2+x-6=(x+B)(x+D) \Rightarrow B=3; D=-2.$$
Plug $x=0$:
$$2y^2-8y-6=(Ay+3)(Cy-2) \Rightarrow \begin{cases} AC=2 \\ -2A+3C=-8 \end{cases}$$
Can you finish?
Appendix: Note that the found parameters will not be suitable. So this method may not always work.

A: you can write your equation in the form $$y^2-y\left(4+\frac{3}{2}x\right)+\frac{x^2+x-6}{2}=0$$ and solve this for $y$
you will get
$$\left(y-\frac{3}{4}x-2-\frac{1}{4}\sqrt{x^2+40x+112}\right)\left(y+\frac{3}{4}x+2-\frac{1}{4}\sqrt{x^2+40x+112}\right)=0$$

A: Since the polynomial is of degree $2$, we can use the
well established "tool-set" for the study of Quadrics
or Conic Sections.
So
$$
\eqalign{
  & Q(x,y) = x^{\,2}  - 3xy + 2y^{\,2}  + x - 8y - 6 =   \cr
  &  = \left( {x,y,1} \right)^T \left( {\matrix{
   1 & { - 3/2} & {1/2}  \cr
   { - 3/2} & 2 & { - 4}  \cr
   {1/2} & { - 4} & 6  \cr
 } } \right)\left( {\matrix{
   x  \cr
   y  \cr
   1  \cr
 } } \right) \cr}
$$
But the determinant of the matrix defining the Conic
$$
{\bf A}_{\,Q}  = \left( {\matrix{
   1 & { - 3/2} & {1/2}  \cr
   { - 3/2} & 2 & { - 4}  \cr
   {1/2} & { - 4} & 6  \cr
 } } \right)
$$
is not null, which means that the conic is not degenerate
and thus $Q(x,y)$ cannot be factored, not even in the complex field.


text:
Q: Display selected range of cells in Textbox1 I am facing an issue while trying to display a selected range of cells from Excel to a UserForm textbox, say C1:E14. The code below is giving me an Runtime error '13' Type Mismatch:
Private Sub CommandButton1_Click()
Dim ActSheet As Worksheet
Dim SelRange As Range
Set ActSheet = ActiveSheet
Set SelRange = Selection
Range("TABLE").Select
Application.Goto "TABLE"
UserForm1.TextBox1.Text = Range("C1:E14").Value
'UserForm1.TextBox1.Text = Range("C1:E14").Select
End Sub

If I use .Value it's giving the above mentioned error, but if I use .Select "True" it is printing in the UserForm text box.

A: The comments are correct. You are trying to set a range to a string.
you can turn it into a range using something like this
Public Function Join(seperator As String, rng As Variant) As String

    Dim cell As Variant
    Dim joinedString As String
    For Each cell In rng
        joinedString = joinedString & cell & seperator
    Next cell
    joinedString = Left(joinedString, Len(joinedString) - Len(seperator))
    Join = joinedString

End Function

Then
UserForm1.TextBox1.Text = Join(",",Range("C1:E14"))
or if you want to make new lines out of each cell
Dim joinedString as string
joinedString  = Join("|",Range("C1:E14"))
UserForm1.TextBox1.Text = Replace(joinedString  , "|", vbCrLf)


text:
Q: sales_order_save_after Observer is preventing the order from saving I created a module that changes a customer's group if their order is completed. I'm using magento 1.9.3.1 and my module is causing some problems when checking out as a guest.
In one example, checking out returns an error to the customer saying "Customer email is required". The order email is sent and the payment is processed but the order is not actually saved in the database. The customer is returned the error "Customer email is required" on the checkout page as if the order/payment hasn't gone through.
I've disabled the magestore onestepcheckout/giftcard extensions I'm using and the problem persists. I've disabled my template to confirm that's not related to the issue.

My setup file (app/etc/modules/EXAMPLE_ApproveCustomer.xml)

<?xml version="1.0"?>
<config>
    <modules>
        <EXAMPLE_ApproveCustomer>
            <codePool>local</codePool>
            <active>true</active>
        </EXAMPLE_ApproveCustomer>
    </modules>
</config>

My config file (app/code/local/EXAMPLE/ApproveCustomer/etc/config.xml)

<?xml version="1.0"?>
<config>
    <modules>
        <EXAMPLE_ApproveCustomer>
            <version>1.0.0</version>
        </EXAMPLE_ApproveCustomer>
    </modules>
    <global>
        <events>
            <sales_order_save_after>
                <observers>
                    <EXAMPLE_approvecustomer_model_observer>
                        <type>singleton</type>
                        <class>EXAMPLE_ApproveCustomer_Model_Observer</class>
                        <method>updateCustomers_SalesOrderSaveAfter</method>
                    </EXAMPLE_approvecustomer_model_observer>
                </observers>
            </sales_order_save_after>
        </events>
    </global>
</config>

My observer file (app/code/local/EXAMPLE/ApproveCustomer/Model/Observer.php)

<?php
class EXAMPLE_ApproveCustomer_Model_Observer {
    public function updateCustomers_SalesOrderSaveAfter(Varien_Event_Observer $observer) {
        // set group for approved customers
        $approved_group = 6;

        // load order being updated
        $order = $observer->getOrder();

        // check if order is complete
        if(($order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE) || ($order->getStatus() == "complete")){
            // get customer id
            $customer_id = $order->getCustomerId();

            // get customer
            $customer = Mage::getModel('customer/customer')->load($customer_id);

            // update group
            $customer->setGroupId($approved_group)->save();
        }
    }
}
?>

A: This will be happen if your store allow guest checkout. So you need to modify your code if customer exist then update their group.
Modify following line

if($customer->getId()) {
    // update group
    $customer->setGroupId($approved_group)->save();
}


text:
Q: Use UINavigationBar appearance "back" icon for custom button? I need to achieve a custom navigation bar's "< back" button as seen in the push segue, but on a modal.

I want to avoid too much hard-coding and found out about the property UINavigationBar.appearance().backIndicatorImage and UINavigationBar.appearance().backIndicatorTransitionMaskImage.
I want to use these to put my own text beside them for my button, since using a .png doesn't look as natural as the real thing.
I tried this but the UIImage from those properties returns as nil.
func addBackButton() {
    let backButton = UIButton(type: .custom)
    backButton.setImage(UINavigationBar.appearance().backIndicatorImage, for: .normal)
    backButton.imageView?.contentMode = .scaleAspectFit
    backButton.setTitle("Back", for: .normal)
    backButton.setTitleColor(backButton.tintColor, for: .normal)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

A: UINavigationBar.appearance().backIndicatorImage is an optional value, therefore you won't be able to get the system default chevron from this. Rather, the system will use the image provided here if not null, otherwise revert to the system default.
If targeting iOS 13+, you can make use of Apple's SF Symbols, in particular the back button icon is referred to as chevron.left. To use this, call UIImage(systemName: "chevron.left"). For earlier versions of iOS, you'll have to use an image set asset. You could target all versions of iOS using if #available(iOS 13.0, *) { ... } else { ... }, where you display the system image if on iOS 13+ for improved UI appearance.
func addBackButton() {
    let backButton = UIButton(type: .custom)
    if #available(iOS 13.0, *) {
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
    }
    else {
        backButton.setImage(UIImage(named: "backChevon"), for: .normal)
    }
    backButton.imageView?.contentMode = .scaleAspectFit
    backButton.setTitle("Back", for: .normal)
    backButton.setTitleColor(backButton.tintColor, for: .normal)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}


text:
Q: NSNumberFormatter stringFromNumber should it be able to take a Swift.Int? I noticed today that even though the documentation for NSNumberFormatter stringFromNumber says that the function declaration takes an NSNumber as its argument ...
var playerScore = 3456789
let displayScore: String = numberFormatter.stringFromNumber(NSNumber.numberWithInteger(playerScore))

it also works correctly by simply supplying a Swift.Int ...
var playerScore = 3456789
let displayScore: String = numberFormatter.stringFromNumber(playerScore)

Is this the compiler just being clever? or something that should not work. Its things like this that make Swift a little hard to follow at times, especially when its purposely aimed at simplifying things for new developers.

A: Yes, this is expected behaviour. Swift automatically bridges certain native number types, such as Int and Float, to NSNumber.
According to the Using Swift with Objective-C book, all of the following types are automatically bridged to NSNumber:

*

*Int

*UInt

*Float

*Double

*Bool


text:
Q: difference between acting >= and > over a list SELECT name, area
FROM world
WHERE area > ALL (SELECT area FROM world
                  WHERE continent="Europe" AND area IS NOT NULL)

SELECT name, area
FROM world
WHERE area >= ALL (SELECT area FROM world
                   WHERE continent="Europe" AND area IS NOT NULL)

What is the difference between these 2 queries?
Because they both give different result.

A: 2 >= 2 is true.
2 >  2 is false.
your first query simply returns all countries in world that are bigger than all of countries in Europe (if you have set their area) in another word you are getting all countries that are bigger than the biggest country in Europe, the second query just returns all countries that are bigger than or equal to the biggest country in Europe.


text:
Q: Plot matrix with GNUplot. Slow I am using GNUplot for plotting a small matrix.
The matrix is 100x100 by size. e.g.
1.23212 2.43123 -1.24312 ......
-4.23123 2.00458 5.60234 ......
......

The data is not neatly stored in the file.
So from C++ point of view, due to the lack of length per data, there is no way to load a whole number, but it has to check when the number is loading. I guess this should be the reason of the slow plotting speed.
Now I have 3 questions:
Q1: Is loading the bottle neck?
Q2: If I can make the data file neatly stored. e.g.
 1.23212  2.43123 -1.24312 ......
-4.23123  2.00458  5.60234 ......
......

Does the plotting speed get any improvement? (Maybe GNUplot can check what the pattern is. Thus improve the loading speed. Not sure.)
Q3: Any other options that I can set to make it faster?
Edit
I tried these:
-3.07826e-21 -2.63821e-20 -1.05205e-19 -3.25317e-19 -9.1551e-19

when outputting used setw to make sure there they are aligned. But I think I still need to tell GNUplot to load 13 characters at one time, then perform strtod.
I would guess, in order to fit a general case, where there is no information for the length of the number, it is safe to do it digit by digit until it there is a space.


text:
Q: How can I recover a saved account password from Yahoo! Messenger on a Mac? The Problem
I have a friend who's forgotten their Yahoo account password. They changed it recently and forgot what it was changed to. Fortunately, they have saved the password in Yahoo! Messenger 3.0.1 beta (235554) on their computer. We believe this is the only place where it has been saved. The computer runs Mac OS X 10.7.5. We would like to recover the password for the account, but we haven't found a way to do so yet.
What We've Tried

*

*Using the account recovery process on the website. They've forgotten the answer to the security question. (It's one of those security question answers that aren't actually correct, making it more secure.) No alternate e-mail address has been associated with the account.

*Viewing the saved password in Keychain. The password appears to be stored in an encrypted or hashed form. (Or perhaps it's a cookie or other unique identifier to send to the server.)

*Finding software to reveal the contents of the password text box in the Yahoo! Messenger UI. I couldn't find any software to do this.

*Using the Sign in to Yahoo! Mail link within Yahoo! Messenger. This provides access Yahoo! Mail for the account, but attempting to access the account information results in a prompt for the password.

A: I believe this is impossible because I read somewhere that the only thing that is saved on the computer is a non-password identifier to be sent to the server. (It's probably similar to a browser cookie).


text:
Q: ICBM Range vs Rotation of the Earth Wright, a physicist and technical arms control specialist, said the launch appears to show North Korea can "go considerably farther" than previous efforts. He believes this missile on a standard trajectory would have a range of 10,400 kilometers (close to 6,500 miles) before accounting for the rotation of the Earth, which extends the range of missiles fired from west to east.
However, Wright said it's still unclear if North Korea reduced the payload on this new test to get a longer range than the test on July 4.
https://www.cnbc.com/2017/07/28/half-the-continental-us-within-range-of-latest-north-korean-missile.html
Earth rotates West to East... Shouldn't the article read Missiles fired East to West extends the range?
Maybe the tangential velocity adds to the eastward trajectory (while it would subtract from the westward trajectory) having a greater net affect than the actual angular displacement of rotation?
R/ Projection Plane

A: No. We launch rockets from Florida eastward not just because of the ocean for a possible failed launch. A missile gets a substantial velocity kick due to earth rotating in an eastward direction. The article is stated correctly. You are right that earth rotates west to east. It's this rotation that adds to a missile launch.  The speed of a point on the earth surface, at the equator, moves at around 350 m/sec. The speed decreases as latitude increases. This adds to the down range velocity of the missile.


text:
Q: script to download all files from a drop down list I would like to write a script (on this webpage) to select the first county, click Generate Excel (the file will download), select the second county, click Generate Excel, and so forth for all the counties.
What I have so far:
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
driver = webdriver.Chrome('/usr/bin/chromedriver')
 driver.get("https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Origin/ExportByCounty")

driver.set_window_size(1920, 1048)
dropdown = driver.find_element(By.ID, "CountyID")
dropdown.find_element(By.XPATH, "//option[. = '[Alameda]']").click()
element = driver.find_element(By.ID, "CountyID")
actions = ActionChains(driver)
actions.move_to_element(element).click_and_hold().perform()
element = driver.find_element(By.ID, "CountyID")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
element = driver.find_element(By.ID, "CountyID")
actions = ActionChains(driver)
actions.move_to_element(element).release().perform()
driver.find_element(By.ID, "SearchButton").click()

The issue is that I need to change "//option[. = '[Alameda]']" to each county which would be time-consuming. Is there a way I can cycle through a list of the counties? Or I can select all the available counties?
THANK YOU for your time and help with this. I value any feedback/ideas/comments.

A: You can capture the option tag inside the select element and loop through it.
This should work for you (tested on Windows 10; Chrome version 100):
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome(executable_path='D://chromedriver/100/chromedriver.exe')
wait = WebDriverWait(driver, 20)

url = "https://www2.calrecycle.ca.gov/LGCentral/DisposalReporting/Origin/ExportByCounty"

driver.get(url)

select_el = wait.until(EC.presence_of_element_located((By.XPATH, '//select[@id="CountyID"]')))
counties = select_el.find_elements(By.TAG_NAME, 'option')
total_counties = len(counties)

# len - 1 because the 1st option is blank
print(f"Total counties: {total_counties - 1}")
btn = driver.find_element(By.XPATH, '//button[@id="SearchButton"]')

for i in range(1, len(counties)):
    print(f"Clicking County - {counties[i].text}")
    counties[i].click()
    btn.click()
    time.sleep(2)


text:
Q: SQL php Select priority If I have 2 type of data in a table, which is either ID1 or ID2 empty, how can I select the rows that ID1 is not empty and also is the latest inserted row first , then follow by the data with ID2 not empty?
Example:
 Data | ID1 | ID2

 1    | ok  |

 2    |     |  ok

 3    | ok  |

and returns:
Data | ID1 | ID2

 3   | ok  |

 1   | ok  |

 2   |     |  ok

Thank you very much.

A: Try this:
SELECT *
FROM tablename
ORDERBY ID1 DESC, ID2 DESC

A: SELECT *
FROM tablename
ORDERBY ID1 DESC, ID2

A: If ID1 and ID2 are 'ok' or empty then Mahmoud's answer is correct. If not, say its an ID from another table then you can do this:-
SELECT *
FROM tablename
ORDER BY ID1='' DESC, ID2='' DESC, Data DESC


text:
Q: Ruby on Rails 3.1 TypeError: 'word' is undefined in .js.coffee file I wrote some JQuery code in an .js.coffee file and I get the following error: TypeError: 'word' is undefined.
I am new with Rails 3.1 so I am not sure what this error message means.
Here is a snippet of the code int the .js.coffee file:
 $(document).ready(function(){
$("#project_name").focus(function(){
    changeBorder("project_name");
});
$("#project_name").blur(function(){
    resetBorder("project_name");
});
...
});

 function changeBorder(formName){
$("#" + formName).css({border: '1px solid #168DD8', background: '#f2f2f2'});
 }

 function resetBorder(formName){
$("#" + formName).css({border: '1px solid #999999', background: '#ffffff'});
 }

Appreciate any help.

A: why are you writing javascript in your .js.coffee file? If you want to use Javascript, rename file extension to .js


text:
Q: Issue running node with typescript compilation and Jest I am having an issue using typescript compilation. I'm trying to run this in a docker container but even running locally gives the same errors so I think I am messing up the arguments. I need to run using node.
I am trying to run
 node --nolazy -r ./node_modules/tsconfig-paths/register.js -r ./node_modules/ts-node/register ./node_modules/jest/bin/jest.js

which outputs
TypeError: Cannot read property 'alias' of undefined
    at /home/user/Workspace/project/node_modules/jest-validate/build/validateCLIOptions.js:97:58
    at Array.reduce (<anonymous>)
    at validateCLIOptions (/home/user/Workspace/project/node_modules/jest-validate/build/validateCLIOptions.js:96:47)
    at buildArgv (/home/user/Workspace/project/node_modules/jest/node_modules/jest-cli/build/cli/index.js:192:42)
    at Object.run (/home/user/Workspace/project/node_modules/jest/node_modules/jest-cli/build/cli/index.js:155:18)
    at Object.<anonymous> (/home/user/Workspace/project/node_modules/jest/node_modules/jest-cli/bin/jest.js:16:27)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at node:internal/modules/cjs/loader:1121:10
    at Object..js (/home/user/Workspace/project/node_modules/ts-node/src/index.ts:1045:43)
    at Module.load (node:internal/modules/cjs/loader:972:32)

If I try and use my Jest config, I get a different error
node --nolazy -r ./node_modules/tsconfig-paths/register.js -r ./node_modules/ts-node/register ./node_modules/jest/bin/jest.js --config=./jest-config.json

which outputs
Usage: jest.js [--config=<pathToConfigFile>] [TestPathPattern]
Options:
   ...[Jest help output]...
(0 , _jestConfig(...).isJSONString) is not a function

It seems tsconfig-paths is causing the issue since when I remove it the test start to run, but of course they fail because node is expecting javascript and not typescript

A: No idea why, but the jest flag --runInBand is required. I think from this blog it might be because otherwise jest spawns child processes?

--runInBand causes all tests to be run in the parent process rather than child processes.

EDIT: If anyone is curious, this is how I managed to get remote debugging in Jest tests launched within Docker


text:
Q: what is the path format of a file created by upload file in grails how to upload file in resource folder in and access that file in groovy project. I will need the absulate path -

A:
how to upload file in resource folder in and access that file in
groovy project.

src/main/resources/ is a directory that generally only exists in your development environment, not the runtime environment.  It wouldn't really make sense to write code to upload to that directory.


text:
Q: PHP CAC Common Access Card Register and Login I don't have a clue how to make my PHP website register and login with CAC Common Access Card. I developed for the past year a site and I can't sell it because off this. I have no clue. No HTTPS no SSL no PKI.

A: *

*Set up server-side SSL.

*Generate private CA for testing [if you don't have a CAC], issue an identity cert to self.

*Install private CA as trusted root for client AuthN in application.

*Require client-auth during SSL conversation; provide private CA and DoD Root CAs as trusted list of CAs.

*Remove private CA from application trust after validation that it works.

Notes:

*

*You'll have to parse the user-supplied certs for your User ID.  This can come from the certificates signed by "DOD EMAIL CA-XX" [two digit number; presently up to 32] in the userPrincipalName field, or you can use the EDIPI which can be collected from either the DOD CA-XX certs or the DOD EMAIL CA-XX certs.  Done right, both of these IDs will be immutable over time and will reliably identify a user despite any name changes they may have.

*Any buyer worth their salt will demand that you're checking revocations via CRL or OCSP.  Be sure you configure this, probably caching the CRLs from each of the CAs on your local system for quick access and configurable refresh time.

*Assuming you're doing this in Apache, most of that work is documented in other threads here on SO and other sites.  Look around; you should find 90%+ of what you need.


text:
Q: Combining a split tar file with minimal temporary disk space use I have a 400 GB tar file split into 1 GB chunks with split, like file.tar.aa, file.tar.ab, etc.
The entire .tar file can be reconstructed with cat *. I would like to unsplit the file and end up with the single 400 GB file, but I have only 15 GB free and so a simple cat * > file.tar will run out of space.
Can I do this with a minimum of temporary space?

A: Something like this would work:
#!/bin/bash
mv first_part.aa merged.tar
for file in $(cat list);
do
cat $file >> merged.tar
rm $file
done


text:
Q: The locale of morphisms vs a morphism to an ultrapower? I'm fixing some type of structure $\Sigma$ (possibly multi-sorted, with functions symbols and relation symbols, though assuming it single sorted with only relation symbols wouldn't change anything). Let $A$ and $B$ be two $\Sigma$-structure. Is there a connection between the following to notion :

*

*The locale $[A,B]_\Sigma$ classyfing morphisms of $\Sigma$-structure form $A$ to $B$.

*Morphism of $\Sigma$-structure from $A$ to an ultrapower of $B$.
Intuitively both are way to make formal the idea that "their ought to be a morphism from $A$ to $B$, up to potential (infinite) cardinality obstruction"
As a first concrete step, the question would be:
Is it true that $[A,B]_\Sigma \neq \varnothing$ if and only if there exists a morphism of $\Sigma$-structure from $A$ to an ultrapower of $B$ ?
But Ideally (and if the above is indeed true) I would like something more concrete that explain how to go back and forth between a morphism to an ultrapower and some sort of witness that the locale is non-trivial (like maybe points of a compactification or something like this).
If you are a model theorist, I guess you can replace $[A,B]_\Sigma \neq \varnothing$ by the existence of a forcing extention of the base set theory in which there is a map from $A$ to $B$ and that should give something that can be translated back to my question.
I'm giving an explicit example in order to fix the idea :
Let $\Sigma$ be single sorted with a single binary relation $R$, and take $A$ and $B$ two $\Sigma$ structure where $R$ is interpreted as the relation $\neq$. Then $[A,B]_{\Sigma}$ is the classifying locale of injection from $A$ to $B$ wich is non trivial as soon as "$B$ is infinite or $|A| \leqslant |B| < \infty$ ". And this is also the condition under which (I'm assuming choice here) you will be able to get an injection from $A$ to some ultrapower of $B$.

A: I believe there are situations where the relevant locale is trivial, but there are many homomorphisms post-ultrapower.
For example, take $\mathcal{B}=(\mathbb{N};<)$ and let $\mathcal{A}$ be a nontrivial ultrapower of $\mathcal{B}$. There are no genuine homomorphisms from $\mathcal{A}$ to $\mathcal{B}$, and moreover this remains true in any forcing extension (since no homomorphism of strict linear orders can "move" infinitely-far-apart points to within finite distance of each other); per the comments, I think this means that the relevant locale is trivial too, but I'm not very familiar with locales. On the other hand, we trivially have lots of homomorphisms from $\mathcal{A}$ into ultrapowers of $\mathcal{B}$.

EDIT: Well after the fact, I've run into a result which while not directly related to this question may still be of similar interest, so I've decided to mention it here. John Bell's paper Isomorphism of structures in $S$-toposes. Bell shows that for structures $\mathcal{A},\mathcal{B}$ in the same language, the following are equivalent:

*

*$\mathcal{A}\cong\mathcal{B}$ in some forcing extension (that is, $\mathcal{A}\cong_{\infty\omega}\mathcal{B}$ by earlier results).

*$\mathcal{A}$ and $\mathcal{B}$ "become isomorphic" in some topos over $\bf{Set}$ (which Bell calls "$S$").
I think this result adds some nuance to the observations above, although I'm a bit out of my element here.


text:
Q: Multithreading slows down main thread I'll do my best to replicate this issue, since it's quite complicated. As an overview, I have a program that displays graphs using OpenGL. This is thread specific so I know the rendering is only done on one thread. My other thread queries a database and stores the data in a copy vector. Once the thread is finished, it swaps the data with the data the OpenGL thread is using (After joining the thread with the main one). In theory there is nothing about this that should make the program run so slow?
The extremely odd part of this is how it eventually "warms up" and runs much faster after a while (it varies quite a bit, sometimes almost instantaneously, sometimes after 30s of runtime). From value's side of thing to compare, the program begins running at about 30-60 fps whilst querying the data (as in, constantly loading it and swapping it and joining the threads), but then once it has warmed up it runs at 1000 fps.
I have tested some things out, beginning with making the query take A LONG time to run. During this, the fps is at a max of what it would be (3000+). It is only when the data is constantly being changed (swapping vectors) that is starts to run very slow. It doesn't make sense that this alone is causing the performance hit since it runs very well after it's "warmed up".
Edit:
I've managed to make a reasonable minimal reproducable example, and i've found some interesting result.
Here is the code:
#include <iostream>
#include <string>
#include <thread>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "ImGui/imgui.h"
#include "ImGui/imgui_impl_glfw.h"
#include "ImGui/imgui_impl_opengl3.h"

bool querying = false;
std::thread thread;
int m_Window_Width = 1280;
int m_Window_Height = 720;

static void LoadData()
{
    querying = true;

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    querying = false;
}

int main()
{

    glfwInit();

    const char* m_GLSL_Version = "#version 460";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
    GLFWwindow* m_Window = glfwCreateWindow(m_Window_Width, m_Window_Height, "Program", NULL, NULL);
    glfwMakeContextCurrent(m_Window);
    glfwSwapInterval(0); //  vsync

    glewInit();

    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGui::StyleColorsClassic();

    // Setup Platform/Renderer backends
    ImGui_ImplGlfw_InitForOpenGL(m_Window, true);
    ImGui_ImplOpenGL3_Init(m_GLSL_Version);

    thread = std::thread(LoadData);

    while (!glfwWindowShouldClose(m_Window))
    {
        glfwPollEvents();

        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        char fps[12];
        sprintf_s(fps, "%f", ImGui::GetIO().Framerate);
        glfwSetWindowTitle(m_Window, fps);

        //Load the data
        if (thread.joinable() == false && querying == false) {
            thread = std::thread(LoadData);
        }
        //Swap the data after thread is finished
        if (thread.joinable() == true && querying == false) {
            thread.join();
        }

        // Rendering
        ImGui::Render();
        glfwGetFramebufferSize(m_Window, &m_Window_Width, &m_Window_Height);
        glViewport(0, 0, m_Window_Width, m_Window_Height);
        glClearColor(0.45f, 0.55f, 0.60f, 1.00f);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
        glfwSwapBuffers(m_Window);
    }

    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    glfwDestroyWindow(m_Window);
    glfwTerminate();

    return 0;
}

Now the interesting thing here is playing around with std::this_thread::sleep_for(). I have implemented this in so I can simulate the speed it actually takes when running the query on the main database. What is interesting is that it actually causes the main thread to stop running and freezes it. These threads should be separate and not impact one another, however that is not the case here. Is there any explanation for this? This seems to be the root issue for my main program and boiled down to this.
Edit 2
To use the libraries (in Visual Studio), download from here, the binaries, https://www.glfw.org/download.html and here aswell, http://glew.sourceforge.net/ and lastly, ImGui from here, https://github.com/ocornut/imgui
Preprocessor: GLEW_STATIC; WIN32;
Linker: glfw3.lib;glew32s.lib;opengl32.lib;Gdi32.lib;Shell32.lib;user32.lib;Gdi32.lib

A: This may or may not be your issue, but here:
    //Load the data
    if (thread.joinable() == false && querying == false) {
        thread = std::thread(LoadData);
    }
    //Swap the data after thread is finished
    if (thread.joinable() == true && querying == false) {
        thread.join();
    }

it is possible that you start the thread in the first if block, then get to the second one before LoadData modifies that bool, causing the wait for that tread to finish.
I would set querying = true; in the main thread, right after you created LoadData thread. Also, I would use some kind of synchronization, for example declare querying as atomic<bool>.
EDIT:
It appears that you do not need to check joinable() - you know when the thread is joinable: when you enter the loop, and after you re-start that thread. This looks cleaner:
std::atomic<bool> querying = true;

void LoadData()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    querying = false;
}

and later in your loop:
//Swap the data after thread is finished
if (!querying) {
    thread.join();
    querying = true;
    thread = std::thread(LoadData);
}


text:
Q: How to use javas Process.waitFor()? I am trying to run command line commands from Java and a quick sanity check made me realize that the reason I am having trouble is that I can't get the pr.waitFor() call below to work. This programs ends in less than 30s and prints nothing after "foo:". I expected it to take just over 30 s and print a random number after "foo:". What am I doing wrong?
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Sample {

    public static void main(String[] args) throws Exception {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("sleep 32; echo $RANDOM");
        pr.waitFor();

        BufferedReader input = new BufferedReader(
                                   new InputStreamReader(pr.getInputStream()));
        String line=null;

        StringBuilder s = new StringBuilder();
        while((line=input.readLine()) != null) {
            System.out.println(s);
            s.append(line);
        }
        System.out.println("foo: " + s.toString());
    }
}

A: You should try this:
Process pr = rt.exec(new String[]{ "bash","-c", "sleep 32; echo $RANDOM" });

This launches a shell process and then within the shell runs your commands. The shell doesn't return till AFTER the commands have completed.
Let me know if that works for you.

A: Process.waitFor() blocks the current thread until the process has terminated, at which point the execution control returns to the thread that spawned the process.
In the posted code, once the process has terminated (i.e., after the Process.waitFor invocation), the input stream of the now terminated process no longer has any data that can be read. Reading the contents of the stream and printing it out, will therefore not result in any tangible input.
If you need to read the contents of the stream, you'll need to spawn a new thread that will take care of the necessary activities of reading the input stream and writing to the output stream as required, before the child process terminates.
Or you could perform the reading and writing in the same thread, but before you wait for the child process to terminate. In other words, you'll need to switch the sequence of the lines containing pr.waitFor(); and the lines that read from the InputStream.
Related question on SO:

*

*Process.waitFor(), threads, and InputStreams

A: You are trying to execute shell commands.  You should try to execute a program.
As shown in Femi's answer you could invoke bash as the executable and then pass to it arguments that will have bash execute the sleep and echo command.