text:
Q: Can't solve hitbox issues in mobile game made in Unity I am developing a game where objects fall from the top of the screen, and you try to and tap on them before they reach the bottom of the screen. The code works fine when I played the game in the editor (with the touch controls swapped to mouse controls), except when I run the game on a phone, the game only seems to register a successful hit if you tap slightly in front of the object in the direction that it is traveling, and does not register a hit if you tap towards the back end or center of the object. I have built and ran the game over 10 times now, each time trying to fix this issue but nothing seems to help. My theory at the moment is that my code for the touch controls have too much going on and/ or have redundancies and by the time it checks whether or not an object is at the position of the touch, the object has moved to a different location. Any thoughts on why the hit boxes are off, and is there a better way to do hit detection with touch screen?
   void FixedUpdate()
     {
         if (IsTouch())
         {
             CheckTouch(GetTouchPosition());
         }
     }

    // Returns true if the screen is touched
         public static bool IsTouch()
         {
             if (Input.touchCount > 0)
             {
                 if (Input.GetTouch(0).phase == TouchPhase.Began)
                 {
                     return true;
                 }
             }
             return false;
         }

     // Gets the position the touch
         private Vector2 GetTouchPosition()
         {
             Vector2 touchPos = new Vector2(0f, 0f);
             Touch touch = Input.GetTouch(0);

             if (Input.GetTouch(0).phase == TouchPhase.Began)
             {
                 touchPos = touch.position;
             }

             return touchPos;
         }

     // Checks the position of the touch and destroys the ball if the
        ball is touched
         private void CheckTouch(Vector2 touchPos)
         {
             RaycastHit2D hit =
             Physics2D.Raycast(Camera.main.ScreenToWorldPoint(
             (Input.GetTouch(0).position)), Vector2.zero);

             if (hit.collider != null)
              {
                    destroy(hit.collider.gameObject);
              }
     }


text:
Q: Export Version and Adapters from the Source Code using the mfpdev (Exporting Zips from Adapter and Source Code) Hi we are planning to have a automated build for our IBM Mobilefirst cordova project. we are now using the mfpdev to deploy the adapter and also to register the new version using the CLI via Azure dev ops. But some of our MFP Server's are not accessible to the outside so for us the only way is to go the mfpconsole export the Adapter and Version and manually install them in those machines. Is there any command to export the Adapter.zip and version.zip from our source code via mfpdev so that i can store them in our build process and we wont loose older adapters in the process.
The only thing i can see it mfpdev app export which help me export the entire application which i don't need.

A: Mfpdev CLI does not have such an option. However, you can either use mfpadm command line tool or Admin REST endpoint to achieve this:

*

*mfpadm command:
Adapter get binary
Usage:
mfpadm adapter mfp <Adapter_Name> get binary > /tmp/MyAdapter.adapter

*Export resources using Admin REST API:
Download Resources. With this option, you can export adapter binaries.
Usage:
https://www.example.com/mfpadmin/management-apis/2.0/runtimes/myruntime/export?resourceInfos=<Adapter_Name>||ADAPTER_CONTENT

redpajama_set_name: RedPajamaStackExchange


text:
Q: in R rethinking package, what is syntax for nested indices? I'm running the following model using Richard McElreath's "rethinking" package in R. Each species (represented by species_dummy) has several trees associated with it (represented by the index [tree]). I would like to use nested indices or somehow use the species dummy variable to allow two different values of r_sigma_species, one for each species. I can't figure out how to make the indexing work. I don't believe any example like this is covered in the Statistical Rethinking book by McElreath.
I've tried the following:

*

*r_tree[tree_index] ~ dnorm(0, r_sigma_species[species_dummy]) ... but this does not work because rethinking will not accept indices to the right of the ~

*defining r_sigma_oak and r_sigma_juniper separately (i.e. the two species) and then using the dummy variable: r_sigma_tree[tree_index] ~ r_sigma_juniper * (1-species_dummy) + r_sigma_oak * species_dummy .... but rethinking won't interpret this because it doesn't automatically filter the data for species_dummy based on [tree_index], so there is a mismatch in the number of lines of data.

*trying to combine the indices as in r_sigma_tree[tree_index][species_dummy] ~ r_sigma_species[species_dummy] ... rethinking doesn't seem to like combined indices.
Since I already have bunch of versions of the model using the "rethinking" package, I do not want to switch to rstan or any other syntax at this point.
model <- map2stan(
  alist(
    avg_v_cent ~ dnorm(mu,sigma),
    mu <- a * exp(r * day_cent),
    a <- a_base + a_species*species_dummy + a_tree[tree_index],
    r <- r_base + r_species*species_dummy + r_tree[tree_index][species_dummy],

    a_base ~ dnorm(0,1),
    a_species ~ dnorm(0,1),
    a_tree[tree_index] ~ dnorm(0, a_sigma_tree),

    r_base ~ dnorm(0,1),
    r_species ~ dnorm(0,1),
    r_tree[tree_index][species_dummy] ~ dnorm(0, r_sigma_species[species_dummy]),

    sigma ~ dcauchy(0,1),
    a_sigma_tree ~ dcauchy(0,1),
    r_sigma_species[species_dummy] ~ dcauchy(0,1)
  ),
  data=as.data.frame(dataset_2017_2.trim.test),
  iter=2000,
  warmup = 1000,
  control = list(max_treedepth = 13, adapt_delta = 0.9),
  chains = 1
)


text:
Q: Regex to match a number with decimals I have the following regex:
var matches = Regex.Matches(s, @"ratingValue"" content=""(?<content>(?:(.|\n)(?!"">))+)");

However, it gives the output with "number.", anything after the . is not taken. For example, if the number is 4.0 it will output 4. or if it's 3.5 it gives 3..
How can I get the decimals as well?
Example input:

I need to output 4.0.

A: You can use LINQ to XML:
string xml = @"";

string content = XElement.Parse(xml).Attribute("content").Value;

decimal value = Convert.ToDecimal(content, CultureInfo.InvariantCulture);

A: I've changed your regex so it returns the decimal number as the match:
var matches = Regex.Matches(s, @"(?:ratingValue"" content="")(?<content>[\r\n\d\.]*)(?:"">)");

Is this what you were after? It returns 4.0 from the provided sample.


text:
Q: Circular animation duration issue with UICircularProgressRing I am using this library to have some circular progress bar in my table view cell. It should be able to indicate the progress i get simultaneously from AWS S3 progress block.
This is the progress block to upload file(image, video) to s3 bucket:
progressBlock = {(task, progress) in
    DispatchQueue.main.async(execute: {
       cell.circularProgressView.setProgress(value: CGFloat(Float(progress.fractionCompleted)), animationDuration: 0, completion: nil)
       print("PROGRESSING \(Float(progress.fractionCompleted))")
       if(progress.fractionCompleted == 1.0)
       {
       }
    })
}

progress.fractionCompleted keeps updated in block, but it does not reflect on UI (cell.circularProgressView), and i set animationDuration: 0 because i am not supposed to know when uploading might finish.
Note: I suspect, the loop in progressBlock stops the progress/animation, when it is hit for the first time, it animates, then it will stop forever.
I appreciate any help. Thank you.


text:
Q: Projects built on each other I'm developing in PHP, using the Kohana framework (the question has nothing to do with PHP or Kohana, so just keep reading).
This means that I start all my projects by cloning the Kohana's repo from Github, and start building my app.
Step 1: The base app
However, to make my life easier I created a repository - let's name it base-app, where I personalized the framework for my needs.
Basically I created the folder structure for static files, added some JS and CSS files which I'll use in all my future projects (like normalize.css, jquery.js, my JS framework, etc). I also registered some submodules I wrote, and pushed this new repo to a remote.
Great! Now I have a base app (I like to call it skeleton), I can clone everytime I start a new project.
Step 2: Authentication
In most apps we also need an authentication system. So I continued developing.
I created an auth submodule to help me with that, but I also needed to create some views, controllers also JS and CSS files (which I can't just put in a submodule) for the login, recover-password, reset-password, etc. pages. Named the repo base-app-auth, and pushed to a remote.
Great! Now I have a new repository: base-app-auth based on the base-app, I can clone when I want to create an app with a login system (controllers, models, views, js, css) already implemented.
Step 3: Accounts & Payments
In at least two of my future projects (and maybe many others) I will also need a solution for managing accounts (subscriptions) and payments.
So I continued developing. Based on the base-app-auth I implemented a solution for accepting payments (through PayPal) and managing subscriptions. This repository also has new views, controllers, models but also new css and js files. (No, I can't simply put them in a submodule).
Great! Now I have a repository I can clone when I want to create a new app with a login system and accounts/payments management already implemented.
The problem:
The problem is that now I have 3 repositories. Keeping them in sync is a pain in the *.
I mean, when I fix an error in the base-app, or develop a new feature in it, I also want the two other repositories to have these changes. So I have to clone the two others and pull the changes from base-app, then push them back to remote.
I'm looking for a better solution.
A possible solution:
A possible solution, I can think off, is to have all the 3 "apps" in a single repository (because actually it's a single app) on different branches. So when I start a project I clone the repository and decide which branch to checkout.
If I don't need the authentication and the account & payment management feature I checkout the base-app branch. If I need authentication but don't need accounts & payments I checkout the base-app-auth branch, and so on.
Is this a good solution? Is there a better one? What is a good way to manage these "cascading" projects in Git?


text:
Q: how can I prove this $\sum_{k=1}^{n}\frac{1}{4k^{2}-2k}=\sum_{k=n+1}^{2n}\frac{1}{k}$ How can I prove the following equation?:
$$s=\sum_{k=1}^{n}\frac{1}{4k^{2}-2k}=\sum_{k=n+1}^{2n}\frac{1}{k}$$
Simplifying both terms of the equation:
$$\sum_{k=1}^{n}\frac{1}{4k^{2}-2k} = \sum_{k=1}^{n}\frac{1}{(2k-1)2k} =(\sum_{k=1}^{n}\frac{1}{2k-1}-\sum_{k=1}^{n}\frac{1}{2k})$$
$$\sum_{k=n+1}^{2n}\frac{1}{k}=(\sum_{k=1}^{2n}\frac{1}{k}-\sum_{k=1}^{n}\frac{1}{k})=(\sum_{k=1}^{n}\frac{1}{2k-1}+\sum_{k=1}^{n}\frac{1}{2k}-\sum_{k=1}^{n}\frac{1}{k})$$
Now we have:
$$s=(\sum_{k=1}^{n}\frac{1}{2k-1}-\sum_{k=1}^{n}\frac{1}{2k})=(\sum_{k=1}^{n}\frac{1}{2k-1}\color{blue}{+}\sum_{k=1}^{n}\frac{1}{2k}\color{blue}{-\sum_{k=1}^{n}\frac{1}{k}})$$
How can I continue?

A: A non-inductive proof ,
$$ S= \sum_{k=1}^{n}\frac{1}{4k^2-2k}=\frac{1}{2}\sum_{k=1}^{n}\frac{1}{(2k-1)(k)} $$
$$ S= \frac{1}{2}\left ( \sum_{k=1}^{n}\frac{2}{(2k-1)}-\frac{1}{k} \right)
$$
$$S= \sum_{k=1}^{n}\frac{1}{(2k-1)}-\sum_{k=1}^{n}\frac{1}{2k} $$
Also it is easy to see that,
$$ \sum_{k=1}^{2n}\frac{1}{k} = \sum_{k=1}^{n}\frac{1}{(2k-1)}+\sum_{k=1}^{n}\frac{1}{2k} $$
Subtracting the 2 equations we get,
$$ S =\sum_{k=1}^{2n}\frac{1}{k} - 2\sum_{k=1}^{n}\frac{1}{2k} =\sum_{k=n+1}^{2n}\frac{1}{k} $$
Hence, proved.

A: Let's do a cute induction on $n$:
For $n = 1$, we have $\frac{1}{4 - 2} = \frac{1}{2}$, so the claim holds.
Assume $n > 1$ and the claim holds for $n - 1$. Then $$\sum_{k = 1}^n \frac{1}{4k^2 - 2k} = \frac{1}{4n^2 - 2n} + \sum_{k = 1}^{n - 1} \frac{1}{4k^2 - 2k} = \frac{1}{4n^2 - 2n} + \sum_{k = n}^{2(n  -1)} \frac{1}{k}$$
by the induction hypothesis. So we only need to show that $\frac{1}{2n} + \frac{1}{2n - 1} - \frac{1}{n} = \frac{1}{4n^2 - 2n}$, which is just a direct computation.

A: The core part of the induction argument spelled out more explicitly:
\begin{align}
\sum_{i=1}^{k+1}\frac{1}{2i(2i-1)}&= \sum_{i=1}^k\frac{1}{2i(2i-1)}+\frac{1}{2(k+1)(2k+1)}\\[1em]
&= \sum_{i=k+1}^{2k}\frac{1}{i}+\frac{1}{2(k+1)(2k+1)}\\[1em]
&= \sum_{i=k+2}^{2k+2}\frac{1}{i}+\frac{1}{k+1}-\frac{1}{2k+1}-\frac{1}{2k+2}+\frac{1}{2(k+1)(2k+1)}\\[1em]
&= \sum_{i=k+2}^{2k+2}\frac{1}{i}+\frac{2(2k+1)-2(k+1)-(2k+1)}{2(k+1)(2k+1)}+\frac{1}{2(k+1)(2k+1)}\\[1em]
&= \sum_{i=k+2}^{2k+2}\frac{1}{i}-\frac{1}{2(k+1)(2k+1)}+\frac{1}{2(k+1)(2k+1)}\\[1em]
&= \sum_{i=k+2}^{2k+2}\frac{1}{i}.
\end{align}


text:
Q: MVC - Parse Objects From Database I am trying to make my best OOP code to parse objects with data from database so I created a hook that call a class AppAutoLoadObjects from hooks folder.
config/hooks.php
$hook['pre_system'][] = array(
    'class' => 'AppAutoLoadObjects',
    'function' => 'initialize',
    'filename' => 'AppAutoLoadObjects.php',
    'filepath' => 'hooks'
);

hooks/AppAutoLoadObjects.php
class AppAutoLoadObjects
{

    public function initialize()
    {
        spl_autoload_register(array($this,'autoloadCoreObjects'));
    }

    public function autoloadCoreObjects($class)
    {
        $path = array(
            'objects/',
        );

        foreach($path as $dir) {
            if (file_exists(APPPATH.$dir.$class."_Object".'.php'))
                require_once(APPPATH.$dir.$class."_Object".'.php');
        }
    }

}

As you see in the code I have a objects folder where I require the object parser.
So if I have models/Products_model.php, the autoloadCoreObjects automatically loads objects/Products_Object.php .
Then in my Products_model.php I use on each function:
  public function select_by_limit($start, $limit, $resolution) {
    ..........................................
    $query = $this->db->get_compiled_select();
    $result = $this->db->query($query);
    return $result->custom_result_object('Products_Object');
  }

So my object with items from database are parsed in Products_Object.php
class Proprietati_Object
{

    private $_resolution;

    public function __construct($resolution = 270){
        $this->_resolution = $resolution;
        $this->_ci = get_instance();
    }

    //here is where I check if any image in database and if not give a default
    public function image(){

        if($this->image_name):
            return base_url('assets/uploads/'.$this->id_proprietate.'/'.$this->image_resolution());
        else:
            return base_url('assets/images/no-product-image-available.png');
        endif;
    }
    //here is where I load a small part of view as string because I must show in view different html code for each product_type
    public function get_block_caracteristics(){
        if($this->product_type == 'apartament')
            return $this->_ci->load->view('blocks/apartament', array('product' => $this), TRUE);
        elseif($this->product_type == 'land')
            return $this->_ci->load->view('blocks/land', array('product' => $this), TRUE);
    }

    //here is where I set the image resolution and depends on each page where I show the products. E.g. 100, 200, 500
    private function image_resolution() {

        $image = explode('.', $this->image_name);
        return $image[0].'_'.$this->_resolution.'.'.$image[1];
    }
}

With this approach I have my controller clean and I only use:
$products = $this->products->select_by_limit(0, 10);
$data['products'] = $products;

then in view:
<?php foreach($products as $product): ?>

<?= $product->image() ?>
<?= $product->get_block_caracteristics() ?>

<?php endforeach; ?>

My question is how can I pass the $resolution variable from the model to the Products_Object constructor? Or maybe my approach is not a good one?
I now this is a very detailed question but I am dealing with this from long time ago, and my purpose is to start coding with clean controllers and models. The framework I use is CodeIgniter.

A: your model
public function select_by_limit($start, $limit, $resolution)
{
    $query = $this->db->get_compiled_select();
    $result = $this->db->query($query);

    $arrData = array();

    foreach($result->result("Proprietati_Object") AS $objProduct)
    {

        $objProduct->setResolution($resolution);
        $arrData[] = $objProduct;
    }

    return $arrData;
 }

and in your Proprietati_Object add a function called setResolution
public function setResolution($resolution)
{
    $this->_resolution = $resolution;
}

and thats it


text:
Q: Update in LINQ to Objects How to do an update in LINQ to Objects. Trying convert SQL to Linq
Quality
        (
          TransactionID int,
          Quantity float,
          MaterialID int,
          ProductID int,
          ParameterID int,
          ParameterValue float,
          TotalTonnes float
        )

How to convert below SQL to linq:
UPDATE  Q1
            SET     TotalTonnes = ( SELECT  SUM(Quantity)
                                    FROM    @Quality Q2
                                    WHERE   Q1.ParameterID = Q2.ParameterID
                                            AND ( ( Q1.MaterialID = Q2.MaterialID )
                                                  OR ( Q1.MaterialID IS NULL
                                                       AND Q2.MaterialID IS NULL
                                                     )
                                                )
                                            AND ( ( Q1.ProductID = Q2.ProductID )
                                                  OR ( Q1.ProductID IS NULL
                                                       AND Q2.ProductID IS NULL
                                                     )
                                                )
                                  )
            FROM    @Quality Q1

Thanks

A: Well, I would do updates imperatively. Something like this:
foreach (var q1 in Q1)
{
    q1.TotalTonnes = (from q2 in Q2
                      where q1.ParameterID == q2.ParameterID
                        && q1.MaterialID == q2.MaterialID
                        && q1.ProductID == q2.ProductID
                      select q2.Quantity).Sum();
}

Note that the double null checks aren't required because of the way null comparisons are handled in C#. (i.e. (null == null) is true)

A: For better performance and what I think is cleaner code you can use the ToLookUp method.  If Q2 is large this will be much better performance as there is no nested loops.
var Q2LookUp =
    Q2.ToLookUp(q2 => new {q2.ParameterId, q2.MaterialID, q2.ProductId});
foreach (var q1 in Q1)
{
    q1.TotalTonnes =
        Q2Lookup[new {q1.ParameterId, q1.MaterialID, q1.ProductId}]
            .Sum(q2 => q2.Quantity);
}


text:
Q: using global exception handeling messes up DelegatingHandler When ovveride the IExceptionHandler, the response does not reach the DelegatingHandler when a unexpected exception occurs. How can I fix this?
In webapi 2, I want to implement a audit logger for request and response messages. I also want to add a global exception handler. However, when I replace the IExceptionHandler with my custom implementation. the response never reaches the DelegatingHandler -on exception - And thus the audit for response is lost.
in WebApiConfig
// add custom audittrail logger
config.MessageHandlers.Add(new AuditLogHandler());
// replace global exception handeling
config.Services.Replace(typeof(IExceptionHandler), new WebAPiExceptionHandler());

Custom Exception Handler
public class WebAPiExceptionHandler : ExceptionHandler
{
    //A basic DTO to return back to the caller with data about the error
    private class ErrorInformation
    {
        public string Message { get; set; }
        public DateTime ErrorDate { get; set; }
    }

    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
        new ErrorInformation { Message = "Iets is misgegaan", ErrorDate = DateTime.UtcNow }));
    }
}

Custom Auditlogger
public class AuditLogHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            var task = await request.Content.ReadAsStringAsync();

            // .. code for loggign request
        }

        var result = await base.SendAsync(request, cancellationToken);

        // .. code for logging response
        // when I do not replace WebAPiExceptionHandler, code is reachred here
        // When I Do use WebAPiExceptionHandler, code is not reached here

        return result;
    }
}

Code for throwing exception in webapi
public class Values_v2Controller : ApiController
{
    public string Get(int id)
    {
        throw new Exception("haha");
    }
}

A: Dont use ExceptionHandler as base class, implement interface IExceptionHandler
public class WebAPiExceptionHandler : IExceptionHandler
{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        var fout = new ErrorInformation
        {
            Message = "Iets is misgegaan"
            , ErrorDate = DateTime.UtcNow
        };

        var httpResponse = context.Request.CreateResponse(HttpStatusCode.InternalServerError, fout);

        context.Result = new ResponseMessageResult(httpResponse);

        return Task.FromResult(0);
    }

    private class ErrorInformation
    {
        public string Message { get; set; }
        public DateTime ErrorDate { get; set; }
    }
}

A: The problem is that ExceptionHandler only executes Handle(ExceptionHandlerContext context) method if ShouldHandle(ExceptionHandlerContext context) returns true.
Overriding bool ShouldHandle(ExceptionHandlerContext context) to always return true fix the problem for me.


text:
Q: Can emulators show an Android app's details page? I have code straight from Google's dev guide:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.example.android"));
startActivity(intent);

It works perfectly on a physical device, the app crashes on Android emulators.  Are Android emulators capable of doing it?

A: The Play Store (formerly known as the Android Market) does not exist on emulators.


text:
Q: Unable to create a new partition for Windows I have only Ubuntu installed and now I need to install Windows 7. I'm using GParted for that, however, I can't create a new partition since most of the menu items are disables including Partition -> New.

A: You are not able to create partitions because you have installed ubuntu in the total size of the disk.  So Gparted can't do the partitioning because the partitions are 'locked' because Ubuntu is running.
So you should make a live CD of ubuntu and boot from that live CD to make the partitions.
OR you can use GParted live CD.

A: To achieve what you want and to prepare  your disk for eventual changes in the  future:

*

*Boot from an Ubuntu Live DVD or USB.

*Open the built-in tool gparted.

*Delete the Linux swap partition sda5.

*Delete the extended partition sda2.

*Resize (reduce) the partition sda1.

*Create a new primary partition.

*Format the partition as swap.

*Create a new primary partition.

*Format the partition with NTFS.

Note 1:
It is recommended to first install Windows before installing Ubuntu because when you install Windows after Ubuntu the MBR (Master Boot Record) will be overwritten by Windows.
When you nevertheless want to install Windows after you installed Ubuntu you will have to reinstall the GRUB boot loader afterwards to select the OS to boot.
You can reinstall the GRUB boot loader by following the instructions.
Boot from Ubuntu install media - then  open a terminal and execute:
sudo mount /dev/sda1 /mnt
sudo grub-install --boot-directory=/mnt/boot /dev/sda

Note 2:
sda = disk | sda1 = Ubuntu system partition
Note 3:
When you want to have more partitions (later), for instance to store personal data or backups - just create a new extended (logical) partition after completing the steps above.

A: You need to boot from an Ubuntu LiveUSB/LiveDVD and start gparted.
Then you will be able to shrink the sda1 partition and create a new partition using the unallocated space.
After you install Windows you will need to re-install grub.

A: I think you will be able to shrink of your partition by using GParted as mentioned in this (http://ccm.net/faq/2036-how-to-resize-a-partition-using-gparted-on-linux ) article.
[P.S.: You can use USB instead of CD.]
Then boot up your ubuntu and create a partition for windows.
Note: As mentioned by other users , it is good if you install windows first and ubuntu later.
(After installing windows make sure to rebuild/reinstall GRUB).
Source

A: My suggestion is install windows from scratch; during the install you can tell it to blow away all existing partitions. Get yourself an external USB hard drive and follow the answer I gave to another question posted in this forum "How to create an external USB bootable Linux hard drive (without dual-boot)


text:
Q: How to test whether a string doesn't contain specified letters in bash In a program I am writing I need to check whether a string contains characters not in another string e.g.:
if [ $string ?? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ]; then
    echo $string isnt alphanumeric
fi

or
if [ $string ?? "ABCDEGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"]; then
    echo $string isnt alphabetic
fi

Where ?? is the mystery operation.
Any help would be appreciated!

A: In bash, within [[...]], the == and != operators are pattern matching operators, so
validChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

if [[ $string != *["$validChars"]* ]]; then
    echo "$string does NOT contain any of $validChars"
fi

Ref: https://www.gnu.org/software/bash/manual/bash.html#index-_005b_005b

To test that a string ONLY contains characters in $validChars, we can use bash's extended pattern matching
if [[ $string == +(["$validChars"]) ]]; then
    echo "$string ONLY contains chars in $validChars"
fi
if [[ $string != +(["$validChars"]) ]]; then
    echo "string is empty or contains some character not in $validChars"
fi


text:
Q: How to get the Product Entity targeted in a Scheduled Update? I am using 2.3.x Magento Enterprise.
I am able to get the schedules updates. And for brevity I'm using the Object Manager in my example as a proof of concept:
$om = ObjectManager::getInstance();
/** @var \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria */
$searchCriteria = $om->get(\Magento\Framework\Api\SearchCriteriaInterface::class);
/** @var \Magento\Staging\Model\UpdateRepository $updateRepo */
$updateRepo = $om->get(\Magento\Staging\Api\UpdateRepositoryInterface::class);
/** @var \Magento\Staging\Model\ResourceModel\Update\Collection $updateList */
$updatesList = $updateRepo->getList($searchCriteria);
/** @var array $updateArray */
$updatesArray = $updatesList->getItems();

foreach ($updatesArray as $update) {
    /** @var \Magento\Staging\Model\Update $update */
}

I will further filter my results, (out of scope of my question) but I want to know how to get the Product entity that is related to my update (if it exists).
If I go into the admin to Content > Content Staging Dashboard I can see my target update and there is a product associated to that Update. It says

This update includes 1 Objects

And underneath it, there is a link to the update where the data for my Product resides.
How can I get that Product through the Magento\Staging\Model\Update or something similar?

A: You will have to set the current version using Magento's version manager. You can use the below function getProductByScheduleId() to get the product.
<?php

namespace Vendor\Module\Folder;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Staging\Model\VersionManager;
use Magento\Catalog\Model\ProductRepository;
use Magento\Store\Model\StoreManagerInterface;

class YourClass
{
    private VersionManager $versionManager;
    private ProductRepository $productRepository;
    private StoreManagerInterface $storeManager;

    public function __construct(
        VersionManager $versionManager,
        ProductRepository $productRepository,
        StoreManagerInterface $storeManager
    )
    {
        $this->versionManager = $versionManager;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
    }

    public function getProductByScheduleId(ProductInterface $product, int $scheduleId): ProductInterface
    {
        try {
            $this->versionManager->setCurrentVersionId($scheduleId);
            $product = $this->productRepository->getById($product->getId(), true, $this->storeManager->getStore()->getId());
        } catch (NoSuchEntityException $e) {
            return $product;
        }
        return $product;
    }

}


text:
Q: Mailkit Email not showing as clickable link I am trying to send a confirmation email and everything is working except that the link comes through as plain text and not as a clickable link.
This is my code:
        public static Task SendEmailConfirmationAsync(this IEmailSender emailSender, string email, string link)
    {
        return emailSender.SendEmailAsync(email, "Please Confirm your email",
            $"Please confirm your account by clicking this link: link");
    }

Thank you in advance

A: Be sure to check that whatever email client you are using is displaying the email as HTML. It appears from your screenshot that the email is being displayed in plain text.

A: using NETCore.MailKit.Core;
Add true for html type:
EmailService.Send(user.Email, "Reset Password", $"Please reset your password by clicking here: link",true)

A: you must sent us mail template. how are you writing on html page this code.
get link only like string and create a mail template and in a tag write like  MailText = MailText.Replace("[FirstName]", user.FirstName).Replace("[email]", user.Email).Replace("[URL]", URL) and in html you must write  Click Here


text:
Q: Asserting two statements are true at the same time in Selenium Unittest I have been trying to assert that two textbox elements contain two specific values for a successful test.
Textbox 1: 100
Textbox 2: 0
I have tried the following code:
def test_example(self):

    self.set_textbox1('100')
    self.set_textbox2('0')

    tb1 = self.find_by_id('textbox1')
    tb2 = self.find_by_id('textbox2')

    self.assertEquals((tb1.get_attribute('value'), 100) and (tb2.get_attribute('value'), 0))

This gives the following error:
Traceback (most recent call last):
File "test_textboxes.py", line 48, in test_textbox
self.assertEquals((tb1.get_attribute('value'), 100) and (tb2.get_attribute('value'), 0))
TypeError: assertEqual() takes at least 3 arguments (2 given)

Is there a way to do this?

A: For me is the readability one of the most important points on unit testing, i would prefer to have multi lines assertion for each case.
You can keep your workflow but using assertEqual and add something like that
self.assertEqual((tb1.get_attribute('value'),tb2.get_attribute('value'),(100,0))

the AssertionError would be, lets say the first value query is 99:
AssertionError: (99,0) != (100,0)

A: The following may solve your issue:
Concatenating the 2 strings:
self.assertEqual(tb1.get_attribute('value') + tb2.get_attribute('value'), '1000')

Or:
self.assertEqual(''.join([tb1.get_attribute('value'), tb2.get_attribute('value')]), '1000')

Using tuples:
self.assertEqual((tb1.get_attribute('value'), tb2.get_attribute('value')), (100, 0))


text:
Q: blocking function accept() restarts when SIGINT occurs even though SA_RESTART flag is set to zero I'm writing a C program on Linux, where I have a main() and two pthreads created by it. In one of the pthreads I have a call to accept() function.
I have a signal handler which is invoked upon receiving of SIGINT, SIGQUIT or SIGTERM.
My expectation is, because I am making SA_RESTART flag zero, when I press ctrl-c, accept() function should return EINTR instead of getting restarted, however I realised via bunch of printf calls while debugging (to see which lines are executed by printing where the code is), that even though my application is able to catch the SIGINT, the accept function remains blocked, it is not failing with EINTR and not moving to next line of code.
Here are my settings inside main()
struct sigaction signal_action;
signal_action.sa_flags = 0; // Don't restart the blocking call after it failed with EINTR
signal_action.sa_handler = terminate;
sigemptyset(&signal_action.sa_mask);
sigfillset(&signal_action.sa_mask); // Block every signal during the handler is executing
if (sigaction(SIGINT, &signal_action, NULL) < 0) {
    perror("error handling SIGINT");
}
if (sigaction(SIGTERM, &signal_action, NULL) < 0) {
    perror("error handling SIGTERM");
}
if (sigaction(SIGQUIT, &signal_action, NULL) < 0) {
    perror("error handling SIGQUIT");
}

Here is the signal handler:
void terminate (int signum)
{
    terminate_program = 1;
    printf("Terminating.\n");
}

Here is the pthread where the accept() call is made (I tried to delete unrelated stuff to make my question more understandable):
void* pthread_timerless_socket_tasks(void* parameter)
{

    server_socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(server_socket_fd < 0)
    {
        perror("error creating IPv4 TCP stream socket");
        return (NULL);
    }
    printf("socket created\n"); // for debugging
    if(fcntl(server_socket_fd, F_SETFL, 0) < 0)
    {
        perror("error making socket_fd blocking");
        close(server_socket_fd);
        return (NULL);
    }

    while(!terminate_program)
    {
        printf("socket blocking on accept\n"); // for debugging
        client_socket_fd = accept(server_socket_fd,(struct sockaddr *) &client_address, &client_length);
        printf("socket accepted?\n"); // for debugging
        if(client_socket_fd < 0)
        {
            perror("error accepting socket_fd");
            close(server_socket_fd);
            return (NULL);
        }

    }

I hope I made myself clear.
So, now I am wondering, what is missing or incorrect as I am unable to see the behaviour described in the linux manuals for SA_RESTART.

A: From the signal(7) manual page:

If  more  than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.

What that means is that if the signal is not sent to the thread doing the accept, then the call won't be interrupted by the signal.
You should block (by setting the signal mask) the signals in all other threads, then the only thread that can receive the signal is the one calling accept.


text:
Q: Firebase Dynamic URL not working with my Wix page I've implemented all the Firebase Requirements in order to use Dynamic Links with my custom domain. The A records, and the TXT information are both added, however now my website is not working.

My Firebase Hosting tab tells me that the www.mydomain.com is connected, however the image above tells me otherwise, here's my Firebase Hosting information:

Here's my DNS information on my Wix page

Note: Sorry about the heavy editing, I don't know exactly what is and what is not sensitive information


text:
Q: Sending a HTTP post to a web server with Java As per title really I'm wanting to send a custom HTTP post request to a web server and I have little experience in this area. The web server uses an LDAP server for access control (not sure if that's important) for which of course I know the username and password. Could anyone flesh out some code to do this or at least get me started?
Edit for one of the comments, the server is running a LAMP stack with PhP 5+ and Apache 2+

A: You can use HttpClient module from Apache.

Although the java.net package provides
  basic functionality for accessing
  resources via HTTP, it doesn't provide
  the full flexibility or functionality
  needed by many applications.
  HttpClient seeks to fill this void by
  providing an efficient, up-to-date,
  and feature-rich package implementing
  the client side of the most recent
  HTTP standards and recommendations.
Designed for extension while providing
  robust support for the base HTTP
  protocol, HttpClient may be of
  interest to anyone building HTTP-aware
  client applications such as web
  browsers, web service clients, or
  systems that leverage or extend the
  HTTP protocol for distributed
  communication.

A: LDAP and authentication are separate issues from sending POSTs to web servers.
Th server side needs to do that authentication.  Set it up either in your code or in the web server itself.
If your client is a Java application, you can create a POST using UrlConnection.
If your client is an HTML page or JSP, you need a form with a POST action.


text:
Q: Developing Markov Transition Matrix I would like to build a transition matrix based on some tabular data given that:

*

*I have about 50,000 historical data points

*Data is organized in a way such as road_id, age, condition

*There are 10 condition levels (1 to 10)

*The Transition Matrix will be condition vs. condition. Roads are assumed to deteriorate based on their current condition and not on any historical data. i.e. if currently the road is in condition 5, it can either stay at 5 or go to 6. Whatever happened in the past is of no effect.

*Age is the "known" variable as in it's the only variable that is "actual" for all the data. Condition is either calculated, assumed, or observed based on video, calculations, local knowledge, etc.

*the TPM is of the following structure:

$$
\begin{bmatrix}
a & b & 0 & 0 & ... & 0 \\
0 & c & d & 0 & ... & 0 \\
... & ... & ... & ... & ... & ... \\
0 & 0 & 0 & 0 & ... & 1
\end{bmatrix}
$$

*

*The reason that the last Pnn = 1 is that a road can't get any worse once it reaches that stage.

Data Sample:
$$
\begin{array}{lr}
\text{age} & \text{condition} \\
\hline
0 & 1.18 \\
0 & 1.18 \\
30 & 9.87 \\
13 & 4.97 \\
26 & 8.30 \\
19 & 6.50 \\
11 & 3.82 \\
9 & 2.68 \\
6 & 1.49 \\
9 & 2.68 \\
16 & 6.22 \\
\end{array}
$$
What is the correct way to calculate my Transition Matrix?
The transition matrix shall be used to:

*

*Estimate and forecast road conditions in the future whether as a whole or for a unique road. For example, what's the average condition of roads of type A or what's the condition of road R001 now and what will its condition be in 10 years?

*I currently use a mixed integer program to solve this but I'm toying around with probabilistic models.

A: I'll give you this reference to a mortgage delinquency transition model: Grimshaw, Scott D., and William P. Alexander. "Markov chain models for delinquency: Transition matrix estimation and forecasting." Applied Stochastic Models in Business and Industry 27.3 (2011): 267-279.
Mortgages go from current to a couple of terminal states: Full Pay-Off and Default. Payoff can happen from any state, at this point the mortgage is fully paid. Defaults happen gradually (usually), i.e. you go 30 day delinquent, then 60 etc. Sometimes, though you may default at once.
What is similar to yours is that delinquency transitions are usually gradual to: 30-60-90...Default. In theory you can't jump from 30 to 90, but due to data errors this happens in the dataset. You have only one terminal state: 1.
Take a look at how the build the markov transition model.


text:
Q: How to sync sliders on qgraphicsview? I have two qgraphicsviews, how do I keep their sliders in sync? That is, if I drag one slider (let's say horizontal) on one qgraphicsview, then it (the horizontal slider) changes accordingly on the other qgraphicsview.
example:

A: Following code should sync them:
QGraphicsView leftView(leftScene);
QGraphicsView rightView(rightScene);

QObject::connect(leftView.horizontalScrollBar(), SIGNAL(valueChanged(int)), rightView.horizontalScrollBar(), SLOT(setValue(int));
QObject::connect(rightView.horizontalScrollBar(), SIGNAL(valueChanged(int)), leftView.horizontalScrollBar(), SLOT(setValue(int));

leftView.show();
rightView.show();

By the way if you are trying to show exactly the same thing in both views, you can use one scene for both of them.


text:
Q: Converting List string or string to dataframe python I have a code that captures information and I need to transform the output of this information into a data frame using pytesseract and cv2
import pyautogui
import cv2
import pytesseract
import numpy as np
from PIL import ImageGrab, Image, ImageEnhance
import time
from pytesseract import Output

size = 1000, 1000
chats = []
pytesseract.pytesseract.tesseract_cmd
='My Patch to Tesseract'

def ScreenSearch():

 while True:
    time.sleep(1)
    img = (ImageGrab.grab(bbox =(1290, 247, 1586, 517)))
    img = img.resize(size, Image.ANTIALIAS)

    gray = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY)

    # Perform text extraction
    data = pytesseract.image_to_string(gray, lang='eng', config='--psm
6')

    print(data)
    print(type(data))

    chats.append(data)
    print(chats)
    print(type(chats))

ScreenSearch()

the outputs are in this format resulting in
Preco(USDT) Quantia(BTC) Total
23624.21 0.00617 145.76138
23624.04 0.02000 472.48080
23624.00 0.00100 YRS tt)
23623.60 0.00650 153.55340
23623.37 0.00842 198.90878
23623.36 0.00846 199.85363
23623.28 0.00636 150.24406
23623.27 0.01913 451.91316
23623.01 0.00640 151.18726
23622.98 0.00675 159.45512
23622.85 0.00052 12.28388
23622.84 0.00210 49.60796

<class 'str'>
['Preco(USDT) Quantia(BTC) Total\n23624.21 0.00617 145.76138\n23624.04 0.02000 472.48080\n23624.00 0.00100 YRS tt)\n23623.60 0.00650 153.55340\n23623.37 0.00842 198.90878\n23623.36 0.00846 199.85363\n23623.28 0.00636 150.24406\n23623.27 0.01913 451.91316\n23623.01 0.00640 151.18726\n23622.98 0.00675 159.45512\n23622.85 0.00052 12.28388\n23622.84 0.00210 49.60796\n']
<class 'list'>

How to transform one or both outputs into data frame?

A: Use string.IO:
from io import StringIO

data = StringIO("""Preco(USDT) Quantia(BTC) Total
23624.21 0.00617 145.76138
23624.04 0.02000 472.48080
23624.00 0.00100 YRS
23623.60 0.00650 153.55340
23623.37 0.00842 198.90878
23623.36 0.00846 199.85363
23623.28 0.00636 150.24406
23623.27 0.01913 451.91316
23623.01 0.00640 151.18726
23622.98 0.00675 159.45512
23622.85 0.00052 12.28388
23622.84 0.00210 49.60796""".replace(' ', ','))

df = pd.read_csv(data)

Two things to note:
Since there is YRS instead of YRS tt in your desired output, I removed tt from the string. The second thing is you could directly use string.IO without needing replace but as your string has no seperator, I had to replace blanks with commas.

A: Use pd.read_csv to convert the string to dataframe. You can use blank space as separator and add errors handle on lines with too much values (like 23624.00 0.00100 YRS tt)).
*sep=' ' can be replaced with delim_whitespace=True if you prefer
df = pd.read_csv(StringIO(data), sep=' ', on_bad_lines=lambda x: x[:3], engine='python')
print(df)

Output
    Preco(USDT)  Quantia(BTC)      Total
0      23624.21       0.00617  145.76138
1      23624.04       0.02000  472.48080
2      23624.00       0.00100        YRS
3      23623.60       0.00650  153.55340
4      23623.37       0.00842  198.90878
5      23623.36       0.00846  199.85363
6      23623.28       0.00636  150.24406
7      23623.27       0.01913  451.91316
8      23623.01       0.00640  151.18726
9      23622.98       0.00675  159.45512
10     23622.85       0.00052   12.28388
11     23622.84       0.00210   49.60796


text:
Q: Outputting information using super and overwriting I am trying to get the right total sales output, I keep on getting 0.0 instead of the appropriate 400 and 950 for the first and second employee.
I think my problem is in the Commission class with the overwritten pay method
The overridden pay method in Commission must call the pay method from the parent class from Hourly to compute the pay for hours worked then add to that the pay from commission on sales(totals sales times the commission rate) The total sales should be reset to 0 after the payment is calculated. –
public class Commission extends Hourly
{
  double total_sales;
  double commission_rate;

  public Commission(String name, String address, String phone,
                    String soc_sec_number, double rate,double commission_rate)
  {
    super(  name,   address,   phone,
                      soc_sec_number,   rate);
    // set commission rate
     commission_rate = 0.02;
  }

  public void addSales (double sales)
  {
    total_sales += sales;

  }

  public double pay()
  {
    double payment = super.pay();   // call the method of the parent
                                    // add other code
    payment = payment + (total_sales * commission_rate);

    total_sales = 0.0;

    return payment;
  }

  public String toString()
  {
    return super.toString() + "\nTotalSales: " + total_sales;
  }

}

Hourly, the parent class with the pay method
// ********************************************************************
// Hourly.java       Java Foundations
//
// Represents an employee that gets paid by the hour
// ********************************************************************

public class Hourly extends Employee
{
  private int hours_worked;

  // -------------------------------------------------------------------------
  // Constructor: Sets up this hourly employee using the specified information
  // -------------------------------------------------------------------------
  public Hourly(String name, String address, String phone,
                String soc_sec_number, double rate)
  {
    super(name, address, phone, soc_sec_number, rate);
    hours_worked = 0;
  }

  // -----------------------------------------------------
  // Adds the specified number of hours to this employee's
  // accumulated hours
  // -----------------------------------------------------
  public void addHours(int more_hours)
  {
    hours_worked += more_hours;
  }

  // -----------------------------------------------------
  // Computes and returns the pay for this hourly employee
  // -----------------------------------------------------
  public double pay()
  {
    double payment = pay_rate * hours_worked;

    hours_worked = 0;
    return payment;
  }

  // ----------------------------------------------------------
  // Returns information about this hourly employee as a string
  // ----------------------------------------------------------
  public String toString()
  {
    return super.toString() + "\nCurrent hours: " + hours_worked;
  }
}

and staff where all the information is stored
// ********************************************************************
// Staff.java       Java Foundations
//
// Represents the personnel staff of a particular business
// ********************************************************************

import java.text.DecimalFormat;

public class Staff
{
  private static DecimalFormat fmt = new DecimalFormat("0.00");
  private StaffMember[] staff_list =
                        {
                          new Executive ("Tony",        "123 Main Line",  "555-0469", "123-45-6789", 2423.07),
                          new Employee  ("Paulie",      "456 Off Line",   "555-0101", "987-65-4321", 1246.15),
                          new Employee  ("Vito",        "789 Off Rocker", "555-0000", "010-20-3040", 1169.23),
                          new Hourly    ("Michael",     "678 Fifth Ave.", "555-0690", "958-47-3625",   10.55),
                          new Volunteer ("Adrianna",    "987 Babe Blvd.", "555-8374"),
                          new Volunteer ("Benny",       "321 Dud Lane",   "555-7282"),
                          new Commission("Christopher", "345 Movie Lane", "555-3831", "302-48-3871",    6.25, 0.2),
                          new Commission("Bobby",       "61 Train St.",   "555-2869", "492-58-2956",    9.75, 0.15)
                        };

  // ----------------------------------
  // Constructor: Updates staff members
  // ----------------------------------
  public Staff()
  {
    ((Executive)staff_list[0]).awardBonus(500.00);

    ((Hourly)staff_list[3]).addHours(40);

    ((Commission)staff_list[6]).addHours(35);    // add commissioned employees
    ((Commission)staff_list[7]).addHours(40);

  }

   // ----------------------
   // Pays all staff members
   // ----------------------
  public void payday()
  {
    double amount;

    for (int count=0; count < staff_list.length; count++)
    {
      System.out.println(staff_list[count]);
      amount = staff_list[count].pay();
      if (amount == 0.0)
        System.out.println("Thanks!");
      else
        System.out.println("Paid: " + fmt.format(amount));
      System.out.println("-----------------------------------");
    }
  }
}

A: First of all, I don't see your field total_sales being initialized in your Commission constructor.
Also, I am not sure what you mean by first and second employee, if you are referring to staff_list[1] and staff_list[2] they are Employee class so verify that the Employee constructor is being properly initialized, the only way I see them earning any money is if they have some hard-coded number being returned in the Employee.pay() method.


text:
Q: Integrating $\int \frac{x^2+1}{x(x^2-1)}$ How would I integrate the following.
$$\int \frac{x^2+1}{x(x^2-1)}$$
I have done the following.
$$\frac{x^2}{(x)(x+1)(x-1)}$$
$$\frac{A}{x}+\frac{B}{x+1}+\frac{C}{x-1}$$
I then did $\quad \displaystyle A(x^2-1)+B(x-1)+C(x+1)=x^2+1$
Then $\quad Ax^2-1A+Bx-1B+Cx+C=x^2+1$
Grouping I get  $$Ax^2=x^2,\quad A=1, \quad C=1,\quad Bx+Cx=0, \quad B=-1$$
Then plug back in
$$\int\frac{1}{x}-\frac{1}{x+1}+\frac{1}{x-1}$$
But I am not sure if I did it correctly.

A: $$\frac{x^2}{(x)(x+1)(x-1)} = \frac{A}{x}+\frac{B}{x+1}+\frac{C}{x-1}$$
$$A(x^ - 1) + Bx(x-1) + Cx(x+ 1) = (A + B + C)x^2 + (-B+ C)x + -A = x^2 + 1$$
$$A + B + C = 1$$
$$C - B = 0\iff B = C$$
$$-A = 1\iff A = -1$$
Now, we have $$A = -1,\;B = C, \implies A + B + C = -1 + 2B = 1 \iff 2B = 2 \iff B = C = 1$$
Can you take it from here?

A: Indeed, you have $$\int\frac{x^2+1}{x(x^2-1)}dx=\int\frac{x^2}{x(x^2-1)}dx+\int\frac{1}{x(x^2-1)}dx$$ $$=\int\frac{x}{(x^2-1)}dx+\int\frac{1}{x(x^2-1)}dx=\int\frac{x}{(x^2-1)}dx+\int\left(\frac{1/2}{x+1}+\frac{1/2}{x-1}-\frac{1}x\right)dx$$ $$=\int\frac{du}{2u}+\int\left(\frac{1/2}{x+1}+\frac{1/2}{x-1}-\frac{1}x\right)dx$$

A: $$\frac{x^2+1}{x(x^2-1)} = \frac{(x+1)^2-2x}{x(x-1)(x+1)} = \frac{x+1}{x(x-1)} - \frac{2}{(x-1)(x+1)} = \frac{1}{x-1} + \frac{1}{x(x-1)} - \frac{(x+1)-(x-1)}{(x-1)(x+1)} = \frac{1}{x-1} + \frac{1}{x-1} - \frac{1}{x}  + \frac{1}{x+1} - \frac{1}{x-1} = \frac{1}{x-1} - \frac{1}{x}  + \frac{1}{x+1}$$

A: A simpler solution is to note that you can calculate
$$\int \frac{x^2-1}{x(x^2-1)} \mbox{and} \int \frac{3x^2-1}{x(x^2-1)}$$
Now
$$x^2+1=(3x^2-1)-2(x^2-1)$$
Thus, your integral is
$$\int \frac{3x^2-1}{x^3-x}- 2\int \frac{x^2-1}{x(x^2-1)}$$


text:
Q: JProfiler 7.2.2 Remote JVM crashes I am attaching Jprofiler Remotely to Linux server. But while connecting eventually remote JVM crashes.
Error Message by JProfiler GUI is as:
The network connection has been lost. The JVM might have terminated unexpectedly.

If the JVM has crashed, please try the following strategies:
*Reduce the -Xmx value of the profiled application.
*Change your profiling settings

My  Remote  JVM java version is 1.6.0_33
Java Hotspot(TM) 64-Bit Server VM
Why it's saying to reduce the -Xmx value of profiled application, or How to resolve this?

A: I had similar problem with JProfiler 7.2.3 after specifying JVM GC settings for JBoss 4.2.3:
-XX:+UseConcMarkSweepGC
-XX:+UseParNewGC
It worked again for me after removal of these settings.


text:
Q: Jhipster v6.10.5 javax.servlet errors in Intellij 2020.3 for maven project I was getting the compilation errors in Intellij after importing the maven project. Intellij was complaining about javax.servlet package not found. The project is building and running from the command line. I have tried reimporting the project after deleting the .idea folder and other idea files.

A: After struggling for two half days on this, I stumbled upon this link. It needed a simple toggle of maven profile. Uncheck the IDE profile option in the maven tool window.
The Jhipster docs have suggestion on enabling the IDE profile. This was causing all the errors.


text:
Q: Is ${(prime^2-1) \over 24}$ always a member of the generalized pentagonal number set? I was working through a puzzle on why the square of a prime minus one is always a factor of 24 (http://puzzles.nigelcoldwell.co.uk/fifteen.htm) and noticed that the sequence of numbers for ${(prime^2-1) \over 24}$ always seems to be a member of the generalized pentagonal number set (http://oeis.org/A001318).
For example, the first 70 members of the set of ${(prime^2-1) \over 24}$ are:
0, 0, 1, 2, 5, 7, 12, 15, 22, 35, 40, 57, 70, 77, 92, 117, 145, 155, 187, 210, 222, 260, 287, 330, 392, 425, 442, 477, 495, 532, 672, 715, 782, 805, 925, 950, 1027, 1107, 1162, 1247, 1335, 1365, 1520, 1552, 1617, 1650, 1855, 2072, 2147, 2185, 2262, 2380, 2420, 2625, 2752, 2882, 3015, 3060, 3197, 3290, 3337, 3577, 3927, 4030, 4082, 4187, 4565, 4732, 5017, 5075, 5192, 5370, 5612, 5797, 5985, 6112, 6305, 6567, 6700, 6970, 7315, 7385, 7740, 7812, 8030, 8177, 8400, 8702, 8855, 8932, 9087, 9560, 9882, 10045, 10375, 10542, 10795, 11310, 11397, 12195
And the first 181 members of the generalized pentagonal set are (bolded members are also a member of ${(prime^2-1) \over 24}$:
0 1 2 5 7 12 15 22 26 35 40 51 57 70 77 92 100 117 126 145 155 176 187 210 222 247 260 287 301 330 345 376 392 425 442 477 495 532 551 590 610 651 672 715 737 782 805 852 876 925 950 1001 1027 1080 1107 1162 1190 1247 1276 1335 1365 1426 1457 1520 1552 1617 1650 1717 1751 1820 1855 1926 1962 2035 2072 2147 2185 2262 2301 2380 2420 2501 2542 2625 2667 2752 2795 2882 2926 3015 3060 3151 3197 3290 3337 3432 3480 3577 3626 3725 3775 3876 3927 4030 4082 4187 4240 4347 4401 4510 4565 4676 4732 4845 4902 5017 5075 5192 5251 5370 5430 5551 5612 5735 5797 5922 5985 6112 6176 6305 6370 6501 6567 6700 6767 6902 6970 7107 7176 7315 7385 7526 7597 7740 7812 7957 8030 8177 8251 8400 8475 8626 8702 8855 8932 9087 9165 9322 9401 9560 9640 9801 9882 10045 10127 10292 10375 10542 10626 10795 10880 11051 11137 11310 11397 11572 11660 11837 11926 12105 12195
I verified that this was true for the first 600 primes, but is this true generally?

A: First of all, $24\mid(n^2-1)\Leftrightarrow 3,8\mid(n^2-1)$ by CRT, which is easy to very mod $3$, $8$ so long as we have $n\ge5$. This holds regardless of whether or not $n$ is prime, so primes are a red herring here.
Secondly, solving
$$\frac{n^2-1}{24}=\frac{k(3k-1)}{2}$$
for $k$ yields $k=\frac{1\pm n}{6}$, so in particular $\frac{n^2-1}{24}$ is generalized pentagonal iff $n\equiv\pm1$ mod $6$.


text:
Q: Script tag breaking my html document? I am currently writing out a HTML document, and I'm trying to include Bootstrap's Js file. However, each time I try to do so, it will just make my page appear blank white. I know it is something to do with the head of the document, but i'm unsure why this is happening...
So I viewed the source code via chrome, and I get this (click image to enlarge)

So when I remove the Bootstrap.js link It goes back to normal, content reappears again, like this. (click to enlarge)

By me saying content not showing and reappearing, I literally mean the visual side upon previewing.

A: You have this:
<script src="js/bootstrap.js"/>

<script> tags don't support auto-closing. Use this instead:
<script src="js/bootstrap.js"></script>


text:
Q: Can I republish my SO answers as a copyrighted work? Some of my posted answers to questions of using pyparsing are very detailed, and at some time in the future, I would like reuse some of them as material in a copyrighted ebook or book. Can I do this, given that posts on SO are under the CC-wiki license? And can someone else do this with my answers, publish my answers in their publication?

A: Standard I am not a lawyer; this is not legal advice disclaimer applies.
When you write your posts, you hold the copyright. As such, you have final control over who can publish the material. When you post them on the Stack Exchange network, you grant a non-exclusive perpetual CC-BY-SA license to Stack Exchange. What this means is that anyone can reuse and modify your material's posts so long as (1) they attribute you appropriately, and (2) their work also has a CC-BY-SA license.
However, you are not bound by the CC-BY-SA license, since you are the copyright holder. Therefore, you can continue to use your work in any form you choose, including publishing them in a book.
This, however, does not stop anyone from finding the original posts on Stack Exchange and reusing them from here (following the attribution guidelines), as they have the Creative Commons license you granted when you published the material on Stack Exchange. Any new material, however, would be entirely protected since you have not granted CC-BY-SA on those.


text:
Q: GCC 4.6 seems not to working I've downloaded binaries for GCC 4.6, I've set up toolchain executables in code::blocks and yet this fails to compile (I can compile it from the command line though):
int main()
{
int array[5] = { 1, 2, 3, 4, 5 };
for (int& x : array)
  x *= 2;
    return 0;
}

What shall I do in order to properly configure compiler in code::blocks?

A: you have to tell g++ that it should compile with c++0x syntax:
g++ --std=c++0x prog.cpp -o prog.x

because this is new C++0x ranged-for syntax:
for (int& x : array)

if this doesn't work, confirm that you use GCC 4.6+
towi@havaloc:~$ gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3

because 4.4 is not enough.


text:
Q: Why can't scipy.optimize.curve_fit fit my data using a numpy.sinc function? I can't use scipy.optimize.curve_fit to fit data generated with numpy.sinc.  Even when I do (or at least I think I do) the exact same thing as in the scipy documentation. Here is my simple try:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

xdata = np.arange(-10, 10, 0.1)
y = 100*np.sinc(xdata - 3) + 1
y_noise = np.random.normal(3, 2, 200)
ydata = y + y_noise

def func(x, a, h, k):
    return(a*np.sinc(x - h) + k)

popt, pcov = curve_fit(func, xdata, ydata)

plt.plot(xdata, ydata)
plt.plot(xdata, func(xdata, *popt))
plt.show()

Here is the result:

A: For many functions, it is essential that you give curve_fit a "pretty good" initial guess for the parameters.  Without it, the optimization routine finds a local minimum of its objective function that is actually a bad fit.
In your case, I got a nice fit by using:
k = ydata.argmax()
p0 = [ydata[k], xdata[k], ydata.mean()]
popt, pcov = curve_fit(func, xdata, ydata, p0=p0)

Here's the plot:

A: You can provide curve_fit with an initial guess using p0=[...]
For example:
from scipy.optimize import curve_fit

xdata = np.arange(-10, 10, 0.1)
y = 100*np.sinc(xdata - 3) + 1
y_noise = np.random.normal(3, 2, 200)
ydata = y + y_noise

def func(x, a, h, k):
    return(a*np.sinc(x - h) + k)

popt, pcov = curve_fit(func, xdata, ydata, p0=[100, 1, 1])

plt.plot(xdata, ydata)
plt.plot(xdata, func(xdata, *popt))
plt.show()


text:
Q: Using pos_weight to improve recall in a multi-class multi-label problem I have a multi-label classification problem, and so I've been using the Pytorch's BCEWithLogitsLoss. I'd like to optimize my model for a higher F2 score, and so want to bias it to have greater recall (with decent precision too of course). Are there any guidelines for setting the values of pos_weight to be able to do this?

A: While adjusting pos_weight does change the model, and may therefore change the association between predicted probabilities and labels, it doesn't have any direct influence on the F2 score itself. Indeed, for a multi-class and multi-label problem, it's not even clear which class or label would be a "positive."
Instead, F2 score depends on the precision and recall of the model's predictions. The precision and recall are, in turn, binarizations of the model's predicted probabilities. You can change the F2 score directly by changing the choice of threshold.


text:
Q: Search option index via option text Hi is there anyway to return the index of an option by it's text? (without jquery or any lib)
<select>
     <option>I</option> //0
     <option>Love</option> //1
     <option>my</option> //2
     <option>granny<option> //3
</select>

say for example I'll pass a string "granny" it'll return 3

A: If you have a select element that looks like this:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>

Running this code:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

A: Sorry for being inactive for few days, here's the one I made, It'll return the index of an option based on the needed string, not the value. I just thought there's an easy function to do the process but I think there's none. just in case, this will do.
HTML
<select id = "myDropDown">
     <option>I</option> //0
     <option>Love</option> //1
     <option>my</option> //2
     <option>granny<option> //3
</select>

Javascript
var dropDownList = document.getElementById("myDropDown");
var str = "granny";
var i =0;
for(i=0;i<dropDownList.length;i++){
    if(dropDownList.options[i].text == str){
        console.log("index: " + i);
    }
}

A: <select>
 <option value="0">I</option> //0
 <option value="1">Love</option> //1
 <option value="2">my</option> //2
 <option value="3">granny<option> //3
</select>

A: Getting the index
Fiddle
Javascript code
function findIndex() {
    var e = document.getElementById("select1");
    alert(e.selectedIndex);
}

HTML
<select id="select1" onchange="findIndex()">
    <option>I</option>
    <option>Love</option>
    <option>my</option>
    <option>granny</option>
</select>

A: I think you want to retrieve the selected Index on change event of Select so you can try the following Code.
jsFiddle
HTML
<select id="select1">
     <option>I</option>
     <option>Love</option>
     <option>my</option>
    <option>granny</option>
</select>

JavaScript
var select1=document.getElementById("select1");
select1.onchange=function(){
var s=document.getElementById("select1").selectedIndex;
alert(s);
}

A: yes and example here from w3chools
http://www.w3schools.com/jsref/prop_option_value.asp


text:
Q: Prove the Borel Lemma I'm trying to prove the Borel Lemma, which is:

For every series $a_0,a_1,a_2,\dots$ in $\mathbb{C}$ exists $f \in C^{\infty}(\mathbb{R})$ such as $$ f^{(k)}(0) = a_k $$ for every $k \in \mathbb{N}_0$.

My idea: I would set $$f(x) = \sum\limits_{k=0}^{\infty} \frac{a_k}{k!} x^k,$$ so if the series $(a_k)_{k \in \mathbb{N}_0}$ converges this $f$ would do it. But I don't know anything about the series, so it could diverge. To avoid this, I would think about to cut the sum by multiplying with a cut-off-function $\chi \in C^{\infty}(\mathbb{C})$ so that $\chi(x) = 0$ for every $|x| > R, R \in \mathbb{C}$. But I don't know how to continue..
I would be thankful for any kind of help.

A: Using cut-off to produce functions $f_n$ such that
$f_n(x)=x^n$ for $|x|<r_n$ and $f_n(x)=0$ for $|x|>r_{n-1}$. Then
$$f(x)=\sum_{k=0}^\infty \frac{a_k}{k!}f_k(x)$$
should do the trick, provided $r_n\to0$ fast enough (how fast do you need for the sum to be "friendly"?)


text:
Q: Different result when i switch positions of my two different functions Note - I am using VSCode
Sample 1: In this example my function nextSquare() is been executed, but aFunc() is not been executed, as in, i get no output for my 2nd function
def nextSquare():
    i = 1
    while True:
        yield i*i
        i += 1
for num in nextSquare():
    if num<100:
        print(num)

def aFunc():
    print("This is inside our function")
print("This is outside of our funcion as a seperate entity")

aFunc()

Output:
Code/RoughWork.py
1
4
9
16
25
36
49
64
81

Sample 2: In this example my function nextSquare() is been executed, but aFunc() gives me output, all i did is, just shift aFunc() before nextSquare()
def aFunc():
    print("This is inside our function")
print("This is outside of our funcion as a seperate entity")

aFunc()

def nextSquare():
    i = 1
    while True:
        yield i*i
        i += 1
for num in nextSquare():
    if num<100:
        print(num)

Output:
Code/RoughWork.py
This is outside of our funcion as a seperate entity
This is inside our function
1
4
9
16
25
36
49
64
81

so when i used the sample 1: in the above code block, i expected that both the functions will get executed, but they didn't, instead by rearranging the function's positions, i got an output, so why is that why did the position of what existed before what mattered in this scenario,and when i try the same in jupyter notebook, the cell doesn't run at all for sample 2.

A: The for loop never ends, so nothing after it is executed. When num is more than 100 it stops printing, but it keeps looping. You need to stop the loop.
for num in nextSquare():
    if num<100:
        print(num)
    else:
        break


text:
Q: Cannot FTP upload using php I have this code:
<?php

$host = "ftp.myserver.com";
$port = 21;
$username = "my_username";
$password = "my_password";
$destination = "/folder/folder2/test.txt";
$file = __DIR__."/folder/folder2/test.txt";

$connection = ftp_connect($host, $port);
if (!$connection)
    throw new Exception("Cannot found host");

$login = ftp_login($connection, $username, $password);
if (!$login)
    throw new Exception("Cannot login with provided credentials");

// return mime type ala mimetype extension
$finfo = finfo_open(FILEINFO_MIME);

//check to see if the mime-type starts with 'text'
$isText = substr(finfo_file($finfo, $file), 0, 4) == 'text';
$mode = $isText == true ? FTP_ASCII : FTP_BINARY;

ftp_pasv($connection, true);

$upload = ftp_put($connection, $destination, $file, $mode);
if (!$upload) {
    echo error_get_last();
}

ftp_close($connection);

And when I run via CMD, the result is as follow:
C:\xampp\htdocs\ftptest>php test.php

Warning: ftp_put(): Can't open that file: No such file or directory in C:\xampp\
htdocs\ftptest\test.php on line 27
Array

Line 27 is on ftp_put command. Folder folder and folder2 is not exist on ftp server. I expect it created by ftp_put (Or should I check and create it manually?)


text:
Q: Where is the code that does floating-point division for C#? Question
I would like to see the piece of code that does a floating-point division and returns Infinity when dividing by zero. Where can I find it?
Code example
The motivation of wanting to know that comes from this code taken from the .NET documentation. I would have expected to get a DivideByZeroException but instead I get Infinity.
https://learn.microsoft.com/en-us/dotnet/api/system.dividebyzeroexception?view=netframework-4.8#remarks
using System;

public class Example
{
   public static void Main()
   {
      int number1 = 3000;
      int number2 = 0;

      Console.WriteLine((double)number1 / number2);
   }
}
// The example displays the following output:
//        Infinity

Documentation
I found the documentation stating that floating-point division by zero does not throw an exception, so that's fine:
https://learn.microsoft.com/en-us/dotnet/api/system.dividebyzeroexception?view=netframework-4.8#remarks

Dividing a floating-point value by zero doesn't throw an exception; it
  results in positive infinity, negative infinity, or not a number
  (NaN), according to the rules of IEEE 754 arithmetic. Because the
  following example uses floating-point division rather than integer
  division, the operation does not throw a DivideByZeroException
  exception.

Code in .NET Framework
In Visual Studio, I hovered over the "/" division sign and Resharper shows
double double.operator /(double left, double right)

And now, I'd like to see the implementation of that to see how that Infinity is returned. But I can't find it.
I checked here

*

*https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/
but don't see the division operator.
The above link then lead me here

*

*https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#division-operator-
but also nothing about the implementation detail.
I also looked here

*

*https://referencesource.microsoft.com/#mscorlib/system/double.cs,428
but only see commented out code
///        Double IArithmetic<Double>.Divide(Double divisor, out bool overflowed) {
///            Double s = m_value / divisor;
///            overflowed = IsInfinity(s) || IsNaN(s);
///            return s;
///        }

Also nothing in the Double implementation of corefx:

*

*https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/Double.cs
I would have expected something liked this (pseudo code):
public static double operator /(double left, double right)
{
   if (right == 0)
   {
      return double.Infinity;
   }
   else
   {
      ...
   }
}

A: Your code compiles down to the following CIL:
.method public hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       21 (0x15)
  .maxstack  2
  .locals init (int32 V_0,
           int32 V_1)
  IL_0000:  nop
  IL_0001:  ldc.i4     0xbb8
  IL_0006:  stloc.0
  IL_0007:  ldc.i4.0
  IL_0008:  stloc.1
  IL_0009:  ldloc.0
  IL_000a:  conv.r8
  IL_000b:  ldloc.1
  IL_000c:  conv.r8
  IL_000d:  div
  IL_000e:  call       void [mscorlib]System.Console::WriteLine(float64)
  IL_0013:  nop
  IL_0014:  ret
} // end of method Example::Main

That IL_000d:  div call is the divide operation happening.  This means the CLR will perform the work, so you won't find any source code doing the work.  If we dig into the CLR source code (here showing the coreclr) for the divide operator for floating point values:
TFp FpDiv(TFp dividend, TFp divisor)
{
#ifdef _TARGET_ARMARCH_
    // From the ECMA standard:
    //
    // If [dividend] is zero and [divisor] is zero
    //   the result is NaN.
    // If [dividend] is infinity and [divisor] is infinity
    //   the result is NaN.

    if (dividend == 0 && divisor == 0)
    {
        return TFpTraits::NaN();
    }
    else if (!_finite(dividend) && !_isnan(dividend) && !_finite(divisor) && !_isnan(divisor))
    {
        return TFpTraits::NaN();
    }
#endif // _TARGET_ARMARCH_

    return dividend / divisor;
}

You can see it's handling some preconditions, then calling into the compiler's intrinsic operation.  On x86 that will in turn be a FDIV call, which is documented as raising a divide by zero flag, which the C runtime, thanks to IEEE 754, will turn into an infinity.  This infinity works it way back up the chain to your C# app.


text:
Q: detecting dangerous unix command line metacharacters I'm working on a web application that has some api calls that send arguments for command line operations. For example, (using jquery), an api call like:
$.get('/api',{
function:function_1,
data:data
},funcion(){},'text')

might execute a command line like:
php a.php data

in that case, if the content of data was "whatever;rm -rf *;", two commands would be executed

*

*php a.php watever;

*rm -rf *;
And I don't want to take that risk.
My problem is not detecting when a character is part of the data string, my problem is knowing which chars should I look for?
I'm adding a list of shell command metacharacters. Please specify which characters are risky and which combination of characters (if any) are risky.

NOTE:
Taken from: http://www.fmrib.ox.ac.uk/fslcourse/unix_intro/shell.html
The shell meta characters include:
\ / < > ! $ % ^ & * | { } [ ] " ' ` ~ ;
NOTE 2: There may be other characters, please, if you know another add it or comment and I'll add it.
NOTE 3: My problem is similar to what might happen with sql injection. when someone adds hidden querys inside search text-boxes, but in my case, the problem is with shell commands. To prevent sql injection you can look at this.

A: You are much better off trying to define what characters are allowed in the input, and check that the input only contains those, i.e. a "white-list" approach.

A: That's exactly what escapeshellarg is for.
http://www.php.net/manual/en/function.escapeshellarg.php


text:
Q: Gradle ziptree fails on chinese filename I have a Zipfile containing a foldername in Chinese.
The Zipfile can be extracted without any problems using Linux unzip, Windows Winrar and 7Zip
When using Gradles "ziptree" I always get the following error:
Could not expand ZIP '/pathToZip/myZip.zip'.

Stacktrace says:
Caused by: org.gradle.api.GradleException: Could not copy zip entry /pathToZip/myZip.zip!somefolderstructure/??/ to '/destination/somefolderstructure/??'.
    at org.gradle.api.internal.file.AbstractFileTreeElement.copyTo(AbstractFileTreeElement.java:79)
    at org.gradle.api.internal.file.copy.DefaultFileCopyDetails.copyTo(DefaultFileCopyDetails.java:106)
    at org.gradle.api.internal.file.copy.FileCopyAction$FileCopyDetailsInternalAction.processFile(FileCopyAction.java:44)
    at org.gradle.api.internal.file.copy.SyncCopyActionDecorator$1$1.processFile(SyncCopyActionDecorator.java:59)
    at org.gradle.api.internal.file.copy.NormalizingCopyActionDecorator$1.maybeVisit(NormalizingCopyActionDecorator.java:98)
    at org.gradle.api.internal.file.copy.NormalizingCopyActionDecorator$1.access$000(NormalizingCopyActionDecorator.java:53)
    at org.gradle.api.internal.file.copy.NormalizingCopyActionDecorator$1$1.processFile(NormalizingCopyActionDecorator.java:65)
    at org.gradle.api.internal.file.copy.DuplicateHandlingCopyActionDecorator$1$1.processFile(DuplicateHandlingCopyActionDecorator.java:60)
    at org.gradle.api.internal.file.copy.CopyFileVisitorImpl.processFile(CopyFileVisitorImpl.java:62)
    at org.gradle.api.internal.file.copy.CopyFileVisitorImpl.visitFile(CopyFileVisitorImpl.java:46)
    at org.gradle.api.internal.file.AbstractFileTree$FilteredFileTreeImpl$1.visitFile(AbstractFileTree.java:181)
    at org.gradle.api.internal.file.archive.ZipFileTree.visit(ZipFileTree.java:91)
    ... 97 more
Caused by: org.gradle.internal.nativeintegration.filesystem.FileException: Could not set file mode 755 on '/destination/somefolderstructure/??'.
    at org.gradle.internal.nativeintegration.filesystem.services.GenericFileSystem.chmod(GenericFileSystem.java:89)
    at org.gradle.api.internal.file.AbstractFileTreeElement.copyTo(AbstractFileTreeElement.java:76)
    ... 108 more
Caused by: net.rubygrapefruit.platform.NativeException: Could not set UNIX mode on /destination/somefolderstructure/??: could not convert string to current locale
    at net.rubygrapefruit.platform.internal.DefaultPosixFiles.setMode(DefaultPosixFiles.java:61)
    at org.gradle.internal.nativeintegration.filesystem.services.NativePlatformBackedChmod.chmod(NativePlatformBackedChmod.java:33)
    at org.gradle.internal.nativeintegration.filesystem.services.GenericFileSystem.chmod(GenericFileSystem.java:87)
    ... 109 more

I already tried to set the File Encoding in gradle.properties
file.encoding=utf-8

I tried to add a Gradle Parameter
-Dfile.encoding=utf-8

I also tried different Gradle Versions: 3.4.1 and 2.14
Nothing works.
UPDATE
Here is my build.gradle (paths don't match the stacktrace because I manually modified the stacktrace):
apply plugin: 'maven'

def defaultEncoding = 'UTF-8'
tasks.withType(AbstractCompile).each {
    it.options.encoding = defaultEncoding
}
tasks.withType(GroovyCompile).each {
    it.groovyOptions.encoding = defaultEncoding
}

configurations {
    mydependencies
}

dependencies {
    mydependencies 'my.group:my-artifact:1.0.0@zip'
}

task copyArtifact(type: Copy) {
    from configurations.mydependencies
    into "$buildDir/zip"
}

task extractZip(type: Sync) {
    from zipTree("$buildDir/zip/my-artifact.zip")
    into "$buildDir/xtract"
}

Any Ideas?
Modifying the zip is the last solution.

A: How about this? Your -Dfile.encoding=UTF-8 is gradle's encoding itself, but it does not affect to compile encoding. Please use this on your build.gradle.
def defaultEncoding = 'UTF-8'
tasks.withType(AbstractCompile).each {
  it.options.encoding = defaultEncoding
}
tasks.withType(GroovyCompile).each {
  it.groovyOptions.encoding = defaultEncoding
}

A: As far as the chinese folder is only for testing-purpose of a node submodule (https://github.com/jfhbrook/node-ecstatic/tree/master/test/public/%E4%B8%AD%E6%96%87) I use the "exclude" from my copy task:
task extractDependency(type: Copy) {
    from zipTree( configurations.mydependencies )
    into "$buildDir/xtract"
    exclude "$parentFolder/npm/node_modules/http-server/node_modules/ecstatic/test/public/"
}


text:
Q: Automorphisms of non-abelian groups of order 27 What are the automorphism groups of non-abelian groups of order 27? (there are two non-abelian groups of order 27).

A: The non-abelian group of order $p^3$ with no elements of order $p^2$ is the Sylow $p$-subgroup of $\operatorname{GL}(3,p)$.  Its automorphism group can also be viewed as a group of $3\times3$ matrices, the affine general linear group,
$$\operatorname{AGL}(2,p) = \left\{ \begin{pmatrix}a & b& e\\ c& d& f\\ 0 & 0 & 1\end{pmatrix} : a,b,c,d,e,f \in \mathbb{Z}/p\mathbb{Z},\; ad-bc ≠ 0 \right\}, $$
which is the semi-direct product of $\operatorname{GL}(2,p)$ on its natural module.
This description is reasonably famous, especially when considering non-abelian groups of order $p^{2n+1}$ with no elements of order $p^2$ whose center and derived subgroup have order $p$.  Instead of $\operatorname{GL}(2,p)$ you get a variation on $\operatorname{Sp}(2n,p)$, that simplifies to $\operatorname{GL}(2,p)$ when $n=1$.
The non-abelian group of order $p^3$ with an element of order $p^2$ and $p ≥ 3$ has as its automorphism group a semi-direct product of $\operatorname{AGL}(1,p)$ with the dual of its natural module, so you get all $3×3$ matrices
$$\left\{ \begin{pmatrix}a & b& 0\\ 0& 1& 0\\ c & d & 1\end{pmatrix} : a,b,c,d \in \mathbb{Z}/p\mathbb{Z},\; a ≠ 0 \right\}. $$
In both cases the "module part" of the semi-direct product is the group of inner automorphisms and the quotient ( $\operatorname{GL}(2,p)$ and $\operatorname{AGL}(1,p)$ ) are the outer automorphism groups.
You can read about some of this in section A.20 of Doerk–Hawkes, or Winter (1972).

*

*Winter, David L.
"The automorphism group of an extraspecial p-group."
Rocky Mountain J. Math. 2 (1972), no. 2, 159–168.
MR297859

*Doerk, Klaus; Hawkes, Trevor.
Finite soluble groups.
de Gruyter Expositions in Mathematics, 4. Walter de Gruyter & Co., Berlin, 1992. xiv+891 pp. ISBN: 3-11-012892-6
MR1169099


text:
Q: Does the damage bonus from Two-Handed-Style apply to spells? I just got to choose my first talent and noticed that the Two-Handed-Style talent provides quite a substantial damage bonus. As I'm wielding a staff as a wizard right now, this looks quite handy if it actually applies to my spells as well as my staff damage.
The description doesn't seem entirely clear to me, it doesn't actually restrict the damage bonus to anything. Does the bonus apply to any damage my character does, or are there restrictions that aren't explicitly listed here?

A: It doesn't appear to affect anything but melee damage, after some quick testing on a Cipher at level up with a poleaxe.

A: weapons do not affect the accuracy or damage of spells.  they are completely independent of one another.  As for the two-handed buff, it doesn't seem to apply, at least with the latest patch 1.04, to all two-handed weapons even.  ranged weapons for instance seem not to apply, after a bit of testing.  quite an oversight if you ask me


text:
Q: Is there a test coverage requirement for 2GP Unlocked package? From here we learn of the 75% coverage requirement for any package that is to be published on App Exchange

In addition, before you deploy Apex or package it for the AppExchange,
  the following must be true.
• Unit tests must cover at least 75% of your Apex code, and all of those tests must complete successfully.

I'm under the impression that my private 2GP packages are not under the same requirement. Am I right?

A: The documentation says:

Although code coverage isn't enforced for unlocked packages, it's a best practice to include Apex tests in your unlocked packages.

Update:
75% code coverage will be enforced for promoting an Unlocked Package beginning with Winter '21:
Release Notes


text:
Q: 'microsoft print to pdf' makes pdf image no clear I print qr.bmp into qr.pdf with 'microsoft print to pdf'.
Original qr.bmp is pure black (RGB 0,0,0), and perfect clear.
But qr.pdf is vague, not clear.
how to get clear image from pdf (or microsoft print to pdf)?

qr.bmp

zoomed qr.pdf
//////////////////////////////////////////////////////////////
I have tried to get pdf from printing job with ghoststcript, and also unclear pdf qr image, but improved pdf.
With -dGraphicsAlphaBits=1, I got more clear image, but not clear.
Can I get clear image from ghostscript?
gswin32c.exe -q -dBATCH -dNOPAUSE -dGraphicsAlphaBits=1 -sDEVICE=pdfwrite -sOutputFile=qr.pdf -

A: It is not always obvious if a source QRcode is good for primary use here are two good ones they can be reduced small without problems, scan to see at what distance they work.

Your camera autofocus should jump to the upper pair equally but struggle with focusing on the worst lower left one.
these two suffer some damage during reduction it may not be instantly obvious and they should still function, but perhaps at closer range.

What makes a good QRcode source ? is a good generator and here 4 different online FREE generators produce very different results and qualities when re scaling.
It is important you test the generator output by reducing the number of pixels in monochrome GIF or TIF or PNG formats as Black and white (should not be grey,  except for rotation) nor castellated as seen in the lower left image. Also every black or white block should be truly square and equal the lower right is not even.
Your first image already shows that problem as the blocks are not even (you have 5s and 4s) and as soon as they are rescaled they will start causing issues in quality reading.

When you inject 1:1 or 2:1 (preferred) or print as PDF (not auto unless tested for scales), it is important that scaling is calculated to preserve monochrome squares, without degrading. Jpeg format or colour is NOT suitable for QRcodes (especially bulk processes) , unless quality assurance inspected for tolerance problems.
Your question says can GhostScript out put a crisp image and the answer is yes if the input is good and crisp as it cant correct for bad sources so here squares of one single pixel are output 100 times larger without any aberrations whatsoever
Source  Probably too small to be detected until enlarged.
enlarged in PDF note the pixels are single pixels (no noise or chatter)

gswin32c  -dGraphicsAlphaBits=1 -sDEVICE=pdfwrite -o qr.pdf -f in.pdf

Output (qr.pdf) copy and pasted in paint for checking. Quality in Quality out = 100% fidelity each block is exactly 100 x 100 pixels e.g. 10,000 times better! No sign of a failure.


text:
Q: Wrong definition of UINT16_C in arm-none-eabi-gcc? I noticed that arm-none-eabi-gcc 10.2 defines the macros UINTN_C in the following way (compiling with -mcpu=cortex-m7 -std=c99 -g3 -O0):
#define UINT32_C(x) __UINT32_C(x)
#define UINT16_C(x) __UINT16_C(x)

Then
#define __UINT32_C(c) c ## UL
#define __UINT16_C(c) c

The C99 standard (7.18.4.1 p2) says that:

The macro UINTN_C(value) shall expand to an unsigned integer constant
with the specified value and type uint_leastN_t.

The 32 bits version is indeed expanding to an unsigned 32 bits representation (uint_least32_t is unsigned long on this CPU).
However the 16 bits version expands to a signed representation: UINT16_C(1) expands to 1 which is of type int.
Isn't it contradictory to the standard ? Is there an option of gcc that would fix that ?
Why not doing something like #define __UINT16_C(c)  ((uint_least16_t)(c)) ?

A: C doesn't recognize the notion of a numeric literal whose type is smaller than int and unsigned int.  On a platform where int is 32 bits, the expression (uint16_t)123 would behave as type signed int as a result of integer promotion, and it would be somewhat illogical for an expression containing a numeric literal of supposed type uint16_t to behave in a manner inconsistent with the way any other expression of that type would be processed.


text:
Q: how can I get this data to router from html Im trying to send Get data from html . I want to submit the data of input to my router to return something. My code is a simply from :

    <form action="/search" method="GET" class="form-inline">

        <input type="text" name="search" id="search" placeholder="search..." class="form-control">
        <input type="submit" value="search" id="search" class="btn btn-default">

    </form>

and my router
    router.get("/search",(req,res)=>{
    gameName.find({gameName: req.body.search})
    .then((gamesInfo)=>{
      ///  res.send('id: ' + req.query.id);
        res.render("search",{gamesInfo:gamesInfo});
     //   console.log(gamesInfo)
        return;

    })
    .catch((err)=>{
            console.log("errr errr errrr");
            console.log(err);
            res.send(err);
    });
});


text:
Q: Setting repeater values from database I have this code
$w("#repeater1").forEachItem( ($item, itemData, index) => {
                $item("#image2").src = reviews[count].ReviewerImage;
                $item("#text17").text = reviews[count].ReviewerComment;
                $item("#text28").text = reviews[count].ReviewerNickname;
                $item("#ratingsDisplay1").value = reviews[count].ReviewerRating;
                count++;
            } );

When this runs, it updates the information in the repeater based on the information in the array reviews. The nickname, comment, and image all are being displayed correctly, but the ratings on the repeater are not updating with the rest of the data. I have tried console logging the 'reviews[count].ReviewerRating' which outputs a value of 5 for each item, but when the page loads, it the ratings display only shows 3 stars. Is there an event I need to trigger to update the reviews?

A: $w("#repeater1").forEachItem( ($item, itemData, index) => {
    $item("#image2").src = reviews[count].ReviewerImage;
    $item("#text17").text = reviews[count].ReviewerComment;
    $item("#text28").text = reviews[count].ReviewerNickname;
    $item("#ratingsDisplay1").rating= reviews[count].ReviewerRating;
    count++;
} );

Had to set the ratings display with .rating instead of .value