text:
Q: Getting error while case_when() applied on empty column in R I have several dataframes with same column names. I wrote a code to perform some operations on a column based on several conditions. But I got error if all the values of that column is empty.
For an example, if my dataframe is like below, my code works fine.

unit
temperature

C
70

C

F
20

K
130

But if my dataframe is like below, my code gives error.

unit
temperature

K

C

F

C

My code is,
data <- data %>%
  mutate(temperature = case_when(
               unit == 'C' ~ temperature,
               unit == 'F' ~ (temperature - 32)*(5/9),
               unit == 'K' ~ temperature - 273))

Could someone help?

A: You can force your empty column (it does not matter if it contains empty strings or logical NA's) to a specific data type, i.e. in this case to a numeric class. Then your case_when() should work and should return NA (NA_real_)
library(dplyr)

tibble::tribble(~unit, ~temperature,
                    "K","",
                    "C","",
                    "F","",
                    "C", "") %>%
      mutate(
        temperature = temperature %>% as.numeric(),
        temperature = case_when(
        unit == 'C' ~ temperature,
        unit == 'F' ~ (temperature - 32)*(5/9),
        unit == 'K' ~ temperature - 273))

A: library(tidyverse)

data <- tribble(
  ~unit, ~temperature,
  "K", NA,
  "C", NA,
  "F", NA,
  "C", NA
)

data %>%
  mutate(
    temperature = as.numeric(temperature),
    temperature = case_when(
      unit == "C" ~ temperature,
      unit == "F" ~ (temperature - 32) * (5 / 9),
      unit == "K" ~ temperature - 273
    )
  )
#> # A tibble: 4 × 2
#>   unit  temperature
#>   <chr>       <dbl>
#> 1 K              NA
#> 2 C              NA
#> 3 F              NA
#> 4 C              NA

Created on 2022-06-08 by the reprex package (v2.0.0)


text:
Q: Superellipse filled with a color I would like to create a superellipse shape. I found the following question "How do I make a superellipse node shape in tikz?" with @Jake's answer that does indeed produce a superellipse. Unfortunately I would like to fill the superellipse with a color and it does not work by adding fill=blue for example to Jake's superellipse node parameters.
\node [fill=blue,minimum width=4cm, minimum height=2cm,
 superellipse, superellipse parameter=1.5] (a) {};

I don't know if this is due to the fact that it is a node shape. This is not necessary in my case of use and a path in the shape of a superellipse is enough for me. In fact I am looking for more or less the equivalent of a
\fill [blue] (0,0) circle [x radius=2cm, y radius=1cm];

but for a superellipse.
Moreover the code in the referred answer was written more than 9 years ago, maybe there is a way to do things more efficiently today, following the improvements of tikz etc.

A: \documentclass[tikz, border=1cm]{standalone}
\begin{document}
\begin{tikzpicture}[
declare function={
  sx(\t)= a*cos(\t r)^(2/n);
  sy(\t)= b*sin(\t r)^(2/n);
  a=1;
  b=1;
  n=4;
}]
\draw[fill=green, variable=\t, domain=0:pi/2] plot ({sx(\t)},{sy(\t)}) -- plot({-sx(pi/2-\t)},{sy(pi/2-\t)}) -- plot({-sx(\t)},{-sy(\t)}) -- plot({sx(pi/2-\t)},{-sy(pi/2-\t)}) -- cycle;
\end{tikzpicture}
\end{document}

Edit: Here is an alternative way to draw the same:
\draw[fill=green, variable=\t]
  plot[domain=0:pi/2] ({sx(\t)},{sy(\t)}) --
  plot[domain=pi/2:0] ({-sx(\t)},{sy(\t)}) --
  plot[domain=0:pi/2] ({-sx(\t)},{-sy(\t)}) --
  plot[domain=pi/2:0] ({sx(\t)},{-sy(\t)}) -- cycle;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Request.Cookies always retuns null through jQuery Ajax call I have jQuery Ajax call which set the cookie in server side. If the cookie exists it should append the value to cookie. The issue here is that HttpContext.Current.Request.Cookies always returns null (cookie exists in browser though) when called from Ajax call.
This is happening because the HttpContext.Current.Request.Cookies searches in Ajax Request URL/Page instead of the parent page.
How can i get the cookies from Original page? Any idea?
Ajax call:
 function GccVideos (http,gccCookieJar,captain) {
    var watchedVideos = [];
    var path = captain.path();

    init();

    this.watch = function (vguid) {
          var request = {
          method: 'POST',
          url: '/videos/watched',
          data: {
             VideoGuid: vguid
          }
        };
        http(request)
          .success(function(response){
            console.log('GccVideos.watched('+vguid+'): Success: ',response);
          })
          .error(function(error){
            throw new Error('GccVideos.watch('+vguid+'): '+error);
          })
        ;
      }

Server side code:
[Route("videos/watched")]
public void SetVideoWatched()
    {
         HttpCookie videoRotationCookie = HttpContext.Current.Request.Cookies[_config.VideoRotation.CookieName] ??
                                                new HttpCookie(_config.VideoRotation.CookieName);

       var videoItem =  _contentItemService.GetItem<VideoItem>(key);

        var videoNameValueCollection = new NameValueCollection { { videoItem.AnalyticsVideoName , videoItem.Key.ToString() } };

        if (videoRotationCookie.Values.AllKeys.Contains(videoItem.AnalyticsVideoName))
        {
            videoRotationCookie.Values.Remove(videoItem.AnalyticsVideoName);
        }

        videoRotationCookie.Path = HttpContext.Current.Request.UrlReferrer.AbsolutePath;

        videoRotationCookie.Expires = DateTime.Now.AddDays(_config.VideoRotation.Duration);

        videoRotationCookie.Values.Add(videoNameValueCollection);

        HttpContext.Current.Response.Cookies.Add(videoRotationCookie);
    }


text:
Q: Somthing like key listener for text field I want to do something with a text field in my program that as soon as the user presses a key on keyborad and writes the first character of a word a special task begin executing something like click listener on a button but for a text field
I will be thankful if you help me

A: Do you mean TextView or EditText?
In case of EditText you can use a TextWatcher. Here you can use the method "onTextChanged".

A: TextView dont receive key pressed. You need an EditText to do this.
Follow the code below:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
   //here is your code
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
   // TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
   // TODO Auto-generated method stub
}
});


text:
Q: How to type useState for files? const [files, setFiles] = useState([])
const filesHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
     e.preventDefault()
     setFiles(e.target.files)
}

input:
<input
     id="file" type="file"
     multiple={true}
     onChange={e => filesHandler(e)}
/>

Argument of type 'FileList | null' is not assignable to parameter of type 'SetStateAction<never[]>'.   Type 'null' is not assignable to type 'SetStateAction<never[]>'.

A: If you are using vscode is already trying to say the type of the multiple file
Argument of type HERE--->'FileList | null' is not assignable to parameter of type 'SetStateAction<never[]>'.   Type 'null' is not assignable to type 'SetStateAction<never[]>'.
const [files, setFiles] = React.useState<FileList | null>();


text:
Q: how can I call a query from a variable from an included file This is my code from my query.php
     $ubh = "SELECT
     ec_product.kode
     FROM
     ec_product
     WHERE
     ec_product.dtcode = '1' AND
     ec_product.kode_agencyplatform = '$kodeParnter' AND
     ec_product.kode = '$kode'";

     $qbaru = "SELECT
     GROUP_CONCAT(kode_category)
     FROM
     ec_product_category
     WHERE
     kode_product = ''
     AND
     dtcode ='1'";

This is from my another ubah.php
      include "query.php";
      $r = mysqli_fetch_array(mysqli_query($conn, "$ubh"));

How to call the $qbaru for ubah.php instead calling $ubh.
Sorry for my bad English

A: Both variables are in the same file, so if you can call $ubh then calling $qbaru should not be a problem. If there is a error, then please provide the error.


text:
Q: Error: LNK2001: unresolved external symbol "private: static class This forum contains many examples of such situation, but in my case static variables are defined correctly, however I still get that error. So this issue is not duplicate of previous and above link does not answer the question. Suggested 21 answers post does not have solution Simon gave me here, please unmark this as "duplicate".
Seems I've declared all correctly, check this:
.h file:
class ValueSetsModelsContainer : public QObject
{
  Q_OBJECT

public:
  static void DLLEXPORT loadAllergiesValueSets(MPTDatabase *db);
  static void DLLEXPORT loadProceduresValueSets(MPTDatabase *db);

  // Models access functions
  static QStandardItemModel *drugsModel();
  static QStandardItemModel *substanceModel();
  static QStandardItemModel *reactionsModel();

private:
  static QStandardItemModel *myDrugsModel, *mySubstanceModel, *myReactionsModel;
};

.cpp:
QStandardItemModel *ValueSetsModelsContainer::myDrugsModel = 0;
QStandardItemModel *ValueSetsModelsContainer::mySubstanceModel = 0;
QStandardItemModel *ValueSetsModelsContainer::myReactionsModel = 0;

QStandardItemModel *ValueSetsModelsContainer::drugsModel()
{
  return ValueSetsModelsContainer::myDrugsModel;
}

QStandardItemModel *ValueSetsModelsContainer::substanceModel()
{
  return ValueSetsModelsContainer::mySubstanceModel;
}

QStandardItemModel *ValueSetsModelsContainer::reactionsModel()
{
  return ValueSetsModelsContainer::myReactionsModel;
}

So static variables are defined in cpp, however I still get linking error in another module which calls ValueSetsModelsContainer methods:

*

*allergiesdialog.obj:-1: error: LNK2001: unresolved external symbol
  "private: static class QStandardItemModel *
  ValueSetsModelsContainer::myDrugsModel"
  (?myDrugsModel@ValueSetsModelsContainer@@0PAVQStandardItemModel@@A)

*allergiesdialog.obj:-1: error: LNK2001: unresolved external symbol    "private: static class QStandardItemModel *
  ValueSetsModelsContainer::mySubstanceModel"
  (?mySubstanceModel@ValueSetsModelsContainer@@0PAVQStandardItemModel@@A)

*allergiesdialog.obj:-1: error: LNK2001: unresolved external symbol    "private: static class QStandardItemModel *
  ValueSetsModelsContainer::myReactionsModel"
  (?myReactionsModel@ValueSetsModelsContainer@@0PAVQStandardItemModel@@A)

Where the problem could be?

A: From your link commands it turned out that you are linking together objects into a DLL and then in a second step link the DLL with your final binary. This might be caused by a subdirs template in your project settings.
Whenever you want to have a method of a DLL available from outside, you need to make it available via __declspec( dllexport ). I guess this is done in your custom precompiler constant DLLEXPORT.
Now try this in your .h file:
static DLLEXPORT QStandardItemModel *drugsModel();
static DLLEXPORT QStandardItemModel *substanceModel();
static DLLEXPORT QStandardItemModel *reactionsModel();

to make those methods available from outside the DLL.

By the way: I don't think it makes sense here to have an intermediate dynamic library (DLL) if you are just linking stuff from your own project and don't need to make it available to someone else. Consider using a static library instead by setting TEMPLATE = lib and CONFIG += staticlib in the .pro file where ValueSetsModelsContainer is in. But this is another topic and another question.


text:
Q: microk8s pods are restarting frequently on my raspberry pi ubuntu I have installed an 64bit ubuntu on my raspberry pi 4 and it seems to me that each pod restarts frequenty:
microk8s.kubectl describe pod redis-c49fd5d65-g8ghn
Name:         redis-c49fd5d65-g8ghn
Namespace:    default
Priority:     0
Node:         raspberrypi4-docker1/192.168.0.45
Start Time:   Thu, 10 Sep 2020 08:11:38 +0000
Labels:       app=redis
              pod-template-hash=c49fd5d65
Annotations:  <none>
Status:       Running
IP:           10.1.42.201
IPs:
  IP:           10.1.42.201
Controlled By:  ReplicaSet/redis-c49fd5d65
Containers:
  redis:
    Container ID:   containerd://9b8300e456691025ccbfbee588a52069a1fa25ffa6f0c1b5f5f652227a1172f3
    Image:          hypriot/rpi-redis:latest
    Image ID:       sha256:2e0128f189c5b19a15001e48fac1d0326326cebb4195abf6a56519e374636f1f
    Port:           6379/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Sun, 07 Mar 2021 10:15:57 +0000
    Last State:     Terminated
      Reason:       Unknown
      Exit Code:    255
      Started:      Sun, 07 Mar 2021 09:24:16 +0000
      Finished:     Sun, 07 Mar 2021 10:14:43 +0000
    Ready:          True
    Restart Count:  4579
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-dn4bk (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-dn4bk:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-dn4bk
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason          Age                    From     Message
  ----     ------          ----                   ----     -------
  Normal   SandboxChanged  8d                     kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   SandboxChanged  8d                     kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   Pulled          8d                     kubelet  Container image "hypriot/rpi-redis:latest" already present on machine
  Normal   Created         8d                     kubelet  Created container redis
  Normal   Started         8d                     kubelet  Started container redis
  Normal   SandboxChanged  8d                     kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   Pulled          8d                     kubelet  Container image "hypriot/rpi-redis:latest" already present on machine
  Normal   Created         8d                     kubelet  Created container redis
  Normal   Started         8d                     kubelet  Started container redis
  Normal   SandboxChanged  8d                     kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   Pulled          8d                     kubelet  Container image "hypriot/rpi-redis:latest" already present on machine
  Normal   Created         8d                     kubelet  Created container redis
  Normal   Started         8d                     kubelet  Started container redis

...
  Normal   SandboxChanged  108m                   kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   Pulled          107m                   kubelet  Container image "hypriot/rpi-redis:latest" already present on machine
  Normal   Created         107m                   kubelet  Created container redis
  Normal   Started         107m                   kubelet  Started container redis
  Normal   SandboxChanged  101m                   kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   Pulled          101m                   kubelet  Container image "hypriot/rpi-redis:latest" already present on machine
  Normal   Created         101m                   kubelet  Created container redis
  Normal   Started         101m                   kubelet  Started container redis
  Normal   SandboxChanged  49m                    kubelet  Pod sandbox changed, it will be killed and re-created.
  Normal   Pulled          49m                    kubelet  Container image "hypriot/rpi-redis:latest" already present on machine
  Normal   Started         49m                    kubelet  Started container redis
  Normal   Created         49m                    kubelet  Created container redis

I have read that this error can be a result of networking failure, what I can found is a DNS error messages in my journalctl logs:
Mar 07 11:24:52 raspberrypi4-docker1 systemd-resolved[1760]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
Mar 07 11:24:52 raspberrypi4-docker1 systemd-resolved[1760]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
Mar 07 11:24:52 raspberrypi4-docker1 systemd-resolved[1760]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
Mar 07 11:24:52 raspberrypi4-docker1 systemd-resolved[1760]: Server returned error NXDOMAIN, mitigating potential DNS violation DVE-2018-0001, retrying transaction with reduced feature level UDP.
Mar 07 11:24:55 raspberrypi4-docker1 microk8s.daemon-kubelet[4953]: E0307 11:24:55.190320    4953 summary_sys_containers.go:47] Failed to get system container stats for "/systemd/system.slice": failed to get cgroup stats for "/systemd/system.slice": failed to get container info for "/systemd/system.slice": unknown container "/systemd/system.slice"

Microk8s inspect output:
Inspecting Certificates
Inspecting services
  Service snap.microk8s.daemon-cluster-agent is running
  Service snap.microk8s.daemon-flanneld is running
  Service snap.microk8s.daemon-containerd is running
  Service snap.microk8s.daemon-apiserver is running
  Service snap.microk8s.daemon-apiserver-kicker is running
  Service snap.microk8s.daemon-proxy is running
  Service snap.microk8s.daemon-kubelet is running
  Service snap.microk8s.daemon-scheduler is running
  Service snap.microk8s.daemon-controller-manager is running
  Service snap.microk8s.daemon-etcd is running
  Copy service arguments to the final report tarball
Inspecting AppArmor configuration
Gathering system information
  Copy processes list to the final report tarball
  Copy snap list to the final report tarball
  Copy VM name (or none) to the final report tarball
  Copy disk usage information to the final report tarball
  Copy memory usage information to the final report tarball
  Copy server uptime to the final report tarball
  Copy current linux distribution to the final report tarball
  Copy openSSL information to the final report tarball
  Copy network configuration to the final report tarball
Inspecting kubernetes cluster
  Inspect kubernetes cluster

Building the report tarball
  Report tarball is at /var/snap/microk8s/2038/inspection-report-20210307_113359.tar.gz

How can I prevent restarting of containers?

A: I switched back from K3S to MicroK8S and got the restarts on a fresh installed MicroK8S cluster with only one node. After inspecting the logs I found a strange log in one of the MicroK8s services:
root@biehler2:/git/webnut-ups-k8s/k8s# snap logs "microk8s.daemon-apiserver-kicker "
2022-11-11T18:49:14Z microk8s.daemon-apiserver-kicker[335004]: CSR change detected. Reconfiguring the kube-apiserver

I asked google and found this:
https://github.com/canonical/microk8s/issues/1710#issuecomment-721043408
When the kicker detects some change in the network it will reconfigure and restart the apiserver. This is to help those who are moving from one network to another.

I think the api-server restart may have forced the pod restarts (no idea how K8S works at this place). At least the timestampts of the restarts and the timestamps of the service log have matched.
I also found a possible solution:
I think yes you can turn it off systemctl stop snap.microk8s-daemon-apiservice-kicker
You can give that a try though.

A few comments below I found this:
do you by any chance have ipv6 enabled on the machine? For example when you do hostname -I does it show ips which are not ipv4? This can be the reason why the kicker is constantly restarting the apiservice.

If you can turn off ipv6 and then re-enable the kicker it shouldn't restart the apiservice.

And this:
if you want to turn disable the kicker from detecting network changes you can follow the instructions below. See if this helps.

The author of the comment referenced this link:
https://github.com/canonical/microk8s/issues/1822#issuecomment-745335208
MIcroK8s has a service that periodically check for changes on your network, reconfigures and restarts the API server if needed. Looking at this services logs (journalctl -n 1000 -u snap.microk8s.daemon-apiserver-kicker) I see a few restarts. To stop the API server restarts even if the network changes you can configure it to use a specific interface. To do so, edit /var/snap/microk8s/currect/args/kube-apiserver and add one of the arguments --advertise-address, --bind-address as described in [1]; then do a microk8s.stop; microk8s.start.

[1] https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/

So I see three options:

*

*disable IPv6

*disable the kicker service

*reconfigure the API server

I recently disabled the kicker service. Until now I saw no restarts anymore and no impact on my cluster. No idea what the kicker service does. Maybe this can help other people, too.


text:
Q: How to add & build a typescript file in ASP.net web application under Visual studio 2012? After installing "TypeScript 1.0 Tools for Visual Studio 2012",
Typescript file can be added & built under [HTML Application with TypeScript].
However, it doesn't work under ASP.NET Web application.
And, if I add a .js file and rename it as a .ts file, I can't find TypescriptCompile
under build Action.
Do I miss some important setting or need to modify the project file?
Thanks.

A: You need to modify the project file. Here is a sample section:
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
  <TypeScriptTarget>ES5</TypeScriptTarget>
  <TypeScriptRemoveComments>false</TypeScriptRemoveComments>
  <TypeScriptSourceMap>true</TypeScriptSourceMap>
  <TypeScriptModuleKind>AMD</TypeScriptModuleKind>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
  <TypeScriptTarget>ES5</TypeScriptTarget>
  <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
  <TypeScriptSourceMap>false</TypeScriptSourceMap>
  <TypeScriptModuleKind>AMD</TypeScriptModuleKind>
</PropertyGroup>
<Import Project="$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets" Condition="Exists('$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets')" />


text:
Q: How do I make sure my cronjob job does NOT retry on failure? I have a Kubernetes Cronjob that runs on GKE and runs Cucumber JVM tests. In case a Step fails due to assertion failure, some resource being unavailable, etc., Cucumber rightly throws an exception which leads the Cronjob job to fail and the Kubernetes pod's status changes to ERROR. This leads to creation of a new pod that tries to run the same Cucumber tests again, which fails again and retries again.
I don't want any of these retries to happen. If a Cronjob job fails, I want it to remain in the failed status and not retry at all. Based on this, I have already tried setting backoffLimit: 0 in combination with restartPolicy: Never in combination with concurrencyPolicy: Forbid, but it still retries by creating new pods and running the tests again.
What am I missing? Here's my kube manifest for the Cronjob:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: quality-apatha
  namespace: default
  labels:
    app: quality-apatha
spec:
  schedule: "*/1 * * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        spec:
          containers:
            - name: quality-apatha
              image: FOO-IMAGE-PATH
              imagePullPolicy: "Always"
              resources:
                limits:
                  cpu: 500m
                  memory: 512Mi
              env:
                - name: FOO
                  value: BAR
              volumeMounts:
                - name: FOO
                  mountPath: BAR
              args:
                - java
                - -cp
                - qe_java.job.jar:qe_java-1.0-SNAPSHOT-tests.jar
                - org.junit.runner.JUnitCore
                - com.liveramp.qe_java.RunCucumberTest
          restartPolicy: Never
          volumes:
            - name: FOO
              secret:
                secretName: BAR

Is there any other Kubernetes Kind I can use to stop the retrying?
Thank you!

A: To make things as simple as possible I tested it using this example from the official kubernetes documentation, applying to it minor modifications to illustrate what really happens in different scenarios.
I can confirm that when backoffLimit is set to 0 and restartPolicy to Never everything works exactly as expected and there are no retries. Note that every single run of your Job which in your example is scheduled to run at intervals of 60 seconds (schedule: "*/1 * * * *") IS NOT considerd a retry.
Let's take a closer look at the following example (base yaml avialable here):
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - non-existing-command
          restartPolicy: Never

It spawns new cron job every 60 seconds according to the schedule, no matter if it fails or runs successfully. In this particular example it is configured to fail as we are trying to run non-existing-command.
You can check what's happening by running:
$ kubectl get pods
NAME                     READY   STATUS              RESTARTS   AGE
hello-1587558720-pgqq9   0/1     Error               0          61s
hello-1587558780-gpzxl   0/1     ContainerCreating   0          1s

As you can see there are no retries. Although the first Pod failed, the new one is spawned exactly 60 seconds later according to our specification. I'd like to emphasize it again. This is not a retry.
On the other hand when we modify the above example and set backoffLimit: 3, we can observe the retries. As you can see, now new Pods are created much more often than every 60 seconds. This are retries.
$ kubectl get pods
NAME                     READY   STATUS   RESTARTS   AGE
hello-1587565260-7db6j   0/1     Error    0          106s
hello-1587565260-tcqhv   0/1     Error    0          104s
hello-1587565260-vnbcl   0/1     Error    0          94s
hello-1587565320-7nc6z   0/1     Error    0          44s
hello-1587565320-l4p8r   0/1     Error    0          14s
hello-1587565320-mjnb6   0/1     Error    0          46s
hello-1587565320-wqbm2   0/1     Error    0          34s

What we can see above are 3 retries (Pod creation attempts), related with hello-1587565260 job and 4 retries (including the orignal 1st try not counted in backoffLimit: 3) related with hello-1587565320 job.
As you can see the jobs themselves are still run according to the schedule, at 60 second intervals:
kubectl get jobs
NAME               COMPLETIONS   DURATION   AGE
hello-1587565260   0/1           2m12s      2m12s
hello-1587565320   0/1           72s        72s
hello-1587565380   0/1           11s        11s

However due to our backoffLimit set this time to 3, every time the Pod responsible for running the job fails, 3 additional retries occur.
I hope this helped to dispel any possible confusions about running cronJobs in kubernetes.
If you are rather interested in running something just once, not at regular intervals, take a look at simple Job instead of CronJob.
Also consider changing your Cron configuration if you still want to run this particular job on regular basis but let's say once in 24 h, not every minute.


text:
Q: DBVis SQL Query - Using Date Variables Firstly it's been a very long time since I did any SQL and even then it wasn't at a high level.
I have created a SQL query which works but I want it so the date range changes automatically, for example to run for the previous month.  I have struggled for hours but cant seem to get any type of variable to work.
Here is the simple SQL I have created.
SELECT   DEST, COUNT (DEST),  SUM(TALK_TIME), SUM(HOLD_TIME)

    FROM ACC.CALLDETAIL a

    where a.ORIG_DATE>='1140201'
    and a.ORIG_DATE<'1140301'
    and a.APPLIC_NUM = 185

GROUP BY a.DEST;

The date format is strange, its  years after 1900 month day
Any help will be appreciated.

A: Try:
SELECT   DEST, COUNT (DEST),  SUM(TALK_TIME), SUM(HOLD_TIME)
    FROM ACC.CALLDETAIL a
    where a.ORIG_DATE >= '1' + (right(convert(varchar,DateAdd(mm, DateDiff(mm, 0, GETDATE()) - 1, 0), 112),6))
    and a.ORIG_DATE < '1' + (right(convert(varchar,DateAdd(mm, DateDiff(mm, 0, GETDATE()) - 0, 0), 112),6))
    and a.APPLIC_NUM = 185
GROUP BY a.DEST;

And see if that does what you want.
(If it doesn't, you may have to declare @startdate and @enddate and define them before the query.)


text:
Q: JavaScript max ,что в нем не правильно? спасибо

function fn3(a, b, c) {
  if (a > b >= c || a > c >= b) {
    return a;
  } else if (b > a >= c || b > c >= a) {
    return b;
  } else if (c > a >= b || c > b >= a) {
    return c;
  }
}
var p = fn3(4, 5, 1);
console.log(p);

A: Операторы сравнения возвращают булевское значение, поэтому после того, как сравнились a > b результат true/false будет сравниваться с числом, причем true приведется к 1, а false - 0.
Для исправления нужно разбить сравнения на пары, например:
a > b >= c

можно представить как:
(a > b) && (b >= c)

A: Вы разобрали слишком много случаев, но при этом умудрились забыть некоторые. Что выдаст ваша функция при трех одинаковых значениях?
Учитесь упрощать свой код. Зачем вам знать порядок переменных a и b для того чтобы заключить что максимум - это c? Незачем, это лишние проверки.
function max3(a, b, c) {
  if (a >= c && a >= b) {
    return a;
  } else if (b >= c && b >= a) {
    return b;
  } else if (c >= b && c >= a) {
    return c;
  }
  return NaN;
}

Вот так будет проще и правильнее.
Причину же ошибки вам уже объяснил Grundy.


text:
Q: Spring Project - Classworlds Configuration not specified i'm new to Spring and Maven development and i'm making the example guides at: https://spring.io/guides.
In fact i'm trying to make a jar file with eclipse.
The guide im following is this one: https://spring.io/guides/gs/device-detection/
INFORMATION:
System: Windows 8.1 (x64) - i5-62000U @ 2.30GHz
Im behind a proxy - Its all set up and eclipse handles all dependencies succefully.
Eclipse: JEE Mars 2 (version 4.5.2)
Java: JDK 1.8.0_77
JRE:  JRE 1.8.0_77
Maven: 3.3.9
M2E: It's installed in my eclipse (comes with JEE version).
STS: i'm not using Spring Tool Suite Eclipse, only Clean JEE Eclipse.
Environment variables: JAVA_HOME, M2_HOME are set up and next i put my path.
Windows PATH:
C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\OpenVPN\bin;C:\Program Files (x86)\Skype\Phone\;C:\Progra~1\apache-maven-3.3.9\bin;C:\Program Files\Java\jdk1.8.0_77\bin

Context:
I have created the project using the skip arcthetype selection and declare it clean with all the dependencies (following the example).
POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
  </parent>
  <groupId>org.springframework</groupId>
  <artifactId>gs-device-detection</artifactId>
  <version>0.1.0</version>

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.mobile</groupId>
            <artifactId>spring-mobile-device</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Milestone Repository</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Milestone Repository</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

XML settings inside .m2 folder:
<?xml version="1.0" encoding="UTF-8"?>
<settings>
<proxies>
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>MY_USER</username>
      <password>MY_PASSWORD</password>
      <host>MY_HOST</host>
      <port>3128</port>
    </proxy>
</proxies>
</settings>

Output from "mvn -version":
C:\Users\MY_USER>mvn -version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T17:41:47+01:00)
Maven home: C:\Progra~1\apache-maven-3.3.9
Java version: 1.8.0_77, vendor: Oracle Corporation
Java home: C:\Progra~1\Java\jdk1.8.0_77\jre
Default locale: it_IT, platform encoding: Cp1252
OS name: "windows 8.1", version: "6.3", arch: "amd64", family: "dos"

The problem:
So far i have been able to compile, run and create the standalone jar file service, but using in the Command Prompt (each one does perfectly):
mvn spring-boot:run
mvn clean package

MY problem is that when i do in Eclipse: Select Project > Run as.. Maven Build
Always get this Exception (no matter what i change or what i put or edit or reinstall in the system):
java.lang.Exception: classworlds configuration not specified nor found in the classpath at  org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)

What i have done so far?
First
Among all the things in the setting that i changed and re-installed all from zero (even Java and Maven).
I notice is the source code of this "Launcher" in the plexus which experts would understand but i put the link for sake of the all with the same problem:
https://codehaus-plexus.github.io/plexus-classworlds/xref/org/codehaus/plexus/classworlds/launcher/Launcher.html
It seen's that im missing a classworlds.conf file at the maven installation directory, but i have no idea what should have inside or where to put it.
Second
I have also seen in GitHub some programmer that have their own classwordls.conf files but i dont understand where do i have to put it, or why this exception appears ONLY in Eclipse and not in the Command Prompt.
Third
Also i notice that some people have changed M2_HOME to M3_HOME (worked for some Mac users i saw around in StackOverflow).
Forth
I saw that others said it was a dependence on the "plexus-classworlds-2.5.2.jar" located in M2_HOME\boot. I didn't understood why, Maven "should" handle all dependencies.
Thank you in advance.

A: For future developers with this problem i will leave the changes i made to successfully download all the dependencies.
First:
There was a mirror in the company that was pointing a private ArtiFactory and downloading all the artifacts from there, some of the artifacts were not present to fulfill all the dependencies and that was the main reason why classworlds wasn't being donwloaded. I asked for support and configured it correctly. As an advice, check ALWAYS the location from were the dependencies are being downloaded, if they ARE actually there and if you have the necessary permissions.
Second
I changed my eclipse version to Luna Service Release 2 (4.4.2) and the connection problems stopped, i saw in other answers and the Maven Integration for Eclipse Luna and newer page where were some bug reports for the version Mars 4.5.2.
Last
Has an additional step to avoid confusion with maven configuration settings, i changed the file location in Eclipse to point to the same file either for global settings and user settings. This way you know that if there's a problem with settings you have to check only one file.


text:
Q: Excel doesn't replace 7 for 07 in a formated text cell Excel doesn't display the zero at the beginning of the text cell.
This file must be in a specific format for a program to read it, so it's very important that the cell is set as text.
THE CELL MUST BE SET AS TEXT, IT CANNOT BE CODE OR CUSTOM it's for a program to read and not a human, the formating is important.
IMPORTANT: I can't add any new data/collumn/row/code to my file, the program that reads it requires it to be a set number of collumn and doesn't read code.
Here is the cell set as text:

Here is how I'm tryng to replace it:

A: What you want to do is right click the cells you want to change, click "Format Cells", then on the Number tab click the "Custom" list option. The field under "Type:" will allow you to format text in the same way the second half of my answer does. 00 will allow one preceding zero for single digit numbers and no preceding zeroes for two digit numbers:

Alternatively, you can also do the following as you seem to have multiple rows using the same data:

The TEXT function =Text(CELL, "XXXX") allows you to set preceding zeroes depending on how many digits are in the row it references, among other things.

A: If you want to enter a number as text in Excel, you can do it by adding a single quote (') in front of the number, e.g. '07. This will force Excel to store as text, even if it looks like a number.
As quicker alternative, if you have lots of values, you can use a temporary column with the formula ="0"&V3 or =""&V3. Copy this cell and paste it in values in the column V, and Excel will store it as a text.

A: I've found a work around, i copied the collum to notepad++ and edited it there, then i copied it back to excel, it works, but it's not ideal, please if you have a way to make it without an axiliar software it would be much better

A: Try this in adjacent cell & fill down.

 =REPT(0,2-LEN(A2))&A2

NB: Suppose you want 2 leading zero before numbers then replace 2 with 3 in the Formula values will looks like shown below.
007
008
005
002
006


text:
Q: sql database search record in database using listview Good day. How can i put a search in my program in c#? It would search record from SQL database then display the records in listview. thanks you
i've tried add this line of code in my program but an error message appears:
There is already an open DataReader associated with this Command which must be closed first
private void button6_Click(object sender, EventArgs e)
{
    SqlConnection MySqlConnection;
    SqlDataReader m_dr;
    SqlCommand command;
    DataTable p_table = new DataTable();

    MySqlConnection = new SqlConnection("Data Source=A-A-PC\\MSSQLSERVER1;Initial Catalog=lights and sounds;User ID=sa;Password=itexpert;");

    MySqlConnection.Open();
    command = new SqlCommand("SELECT * FROM inventory  WHERE package='" + textBox7.Text + "'", MySqlConnection);
    m_dr = command.ExecuteReader();

    if (m_dr.HasRows)
    {
        SqlCommand command1 = new SqlCommand("Select * from inventory", MySqlConnection);
        p_table.Clear();
        SqlDataAdapter m_d = new SqlDataAdapter("Select * from inventory", MySqlConnection);

        m_d.Fill(p_table);
        listView1.Items.Clear();

        for (int i = 0; i < p_table.Rows.Count; i++)
        {
            DataRow drow = p_table.Rows[i];
            if (drow.RowState != DataRowState.Deleted)
            {
                ListViewItem lvi = new ListViewItem(drow["id"].ToString());
                lvi.SubItems.Add(drow["package"].ToString());
                lvi.SubItems.Add(drow["number"].ToString());
                listView1.Items.Add(lvi);
            }
        }
    }
}

A: Here are some things that may be causing issues or conflicts. They may be unnecessary but it just neatens your code.

*

*Create the SQL Command object inside your SQL Connection:
MySQLConnection = new SQLConnection(/*Connection string here*/);
command = MySQLConnection.CreateCommand();

*Use a try{} catch{} block. This will catch on any errors and show you what is going on if you follow the code in debug mode. eg.
try
{
//your code here
}
catch(SqlException e){ Console.WriteLine(e.Message); }
finally
{ if (MySQLConnectrion != null)
    {
        MySQLConnection.Close();
    }
}

A: Your code is lacking "using" block. Use the using block to make sure of the disposal of the connection. Like this:
using (SqlConnection sqlConn = new SqlConnection())
{
    conn.Open();
    Sqlmd.Connection = sqlConn;
    SqlDataAdapter da = new SqlDataAdapter(Sqlmd);
   //code goes here...
}


text:
Q: Get last part of string after hyphen Is there a simple command line to extract the last part of a string separated by hyphens? E.g., I want to extract 123 from foo-bar-123.

A: echo "foo-bar-123"| awk -F"-" '{print $3}'

A: You can use Bash's parameter expansion:
string="foo-bar-123" && printf "%s\n" "${string##*-}"
123

If you want to use another process, with Awk:
echo "foo-bar-123" | awk -F- '{print $NF}'

Or, if you prefer Sed:
echo "foo-bar-123" | sed 's/.*-//'

A lighter external process, as Glenn Jackman suggests is cut:
cut -d- -f3 <<< "$string"

A: grep -Po '(?<=\w-)\w+(?=$|[\s.,])'


text:
Q: Template parse errors: Can't bind to '{ngModel}' since it isn't a known property of 'input' I did everything about ngModel still i am getting the problem
Template parse errors: Can't bind to '{ngModel}' since it isn't a known property of 'input'. (" type="text"
My code:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { ServerComponent } from "./server/server.component";
import { ServersComponent } from './servers/servers.component';

@NgModule({
  declarations: [
    AppComponent,
    ServerComponent,
    ServersComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Example Picture


text:
Q: Number of console logs in component body not equal to number of rerenders? I have a simple React component that is just supposed to console.log some dummy text when component is rendered. I have read some articles about rendering and I would assume that rendering happens at the same time as invoking the component, i.e. rendering is not possible without invoking/executing component function a priori.
So, the number of console logs in this case should be 2 for each - once when component initially renders, and second time when I click on the button and i is set to 2. Every next time React should be able to detect that state is actually not the same and not re-render the component.
But, I get "Hello from invoking" (that is not in use effect but in component body) three times, once when component initially renders, and two times when I click on the button. This component is for sure rendered just twice, so where did that third console.log come from? Is it possible that the component function is invoked, but not re-rendered? In contrary, "Hello from rendering" is logged twice as I would assume.
import { useEffect, useState } from "react";

const DummyComponent = (props) => {
    const [i, setI] = useState(0);

    useEffect(() => {
        console.log("hello from rendering!");
    });

    console.log("hello from invoking!");

    return (
        <div onClick={() => setI(2)}}> Hello </div>
    );
};

export default DummyComponent;

A: When the onClick calls setI, this causes a change to the state and an update gets triggered. This will call the lifecycle methods associated with an update.

*

*static getDerivedStateFromProps()

*shouldComponentUpdate()

*render()

*getSnapshotBeforeUpdate()

*componentDidUpdate()

The useEffect hook is called during componentDidUpdate() (as well as componentDidMount), while the console.log outside the useEffect is going to be called during render().
That means we should expect to see 1 hello from rendering! and 1 hello from invoking! when we refresh or when we click the "Hello" div.
In this codesandbox example you can see that we are getting the expected behavior of one a single console.log of each.
Now in this codesandbox example we are using StrictMode, and you can see that when we click the "Hello", we are seeing hello from rendering! 1 time, but we are seeing hello from invoking! 2 times!
StrictMode was enabled by adding a <StrictMode> tag to index.js
root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

It seems that the behavior you are describing is coming from the use of StrictMode.
This happens because StrictMode intentionally double-invokes the following functions:

*

*Class component constructor, render, and shouldComponentUpdate methods

*Class component static getDerivedStateFromProps method

*Function component bodies

*State updater functions (the first argument to setState)

*Functions passed to useState, useMemo, or useReducer

Thus, we see the render function occurring 2 times, and we get the 2 console.logs.


text:
Q: Amending a cast attribute inside a collection in Laravel I have a model has an attribute which is cast to an array, like so
protected $casts = [
   'data' => 'array',
];

I need to make an amendment to the array before returning the Collection.  Using the each method on the Collection I can make changes to the attributes inside.
$collection = $collection->each(function ($collection, $key) {
    if ($collection->type == 'foo') {
       $collection->type = 'bar';
    }
});

This works and the Collection is altered.  However I need to change the array in the cast attribute.
$collection = $collection->each(function ($collection, $key) {
    if ($collection->type == 'foo') {

        foreach ($collection->data['x'] as $k => $v) {
            $collection->data['x'][$k]['string'] = 'example';
        }

    }
});

However this returns an error.
Indirect modification of overloaded property App\Models\Block::$data has no effect

I understand that accessing $collection->data will be using a magic  __get() is being used, so I would need to use a setter.  So how do I achieve this?
Thanks in advance.

A: Presumably you can take the whole array, perform your modifications and then set it:
$collection = $collection->each(function ($collectionItem, $key) {
    if ($collectionItem->type == 'foo') {
        $data = $collectionItem->data;
        foreach ($data['x'] as $k => $v) {
            $data['x'][$k]['string'] = 'example';
        }
        $collectionItem->data = $data;

    }
});

Though if this modification is required for all uses of the model, perhaps it would be better to do this in the model its self:
class SomeModel
{

    //protected $casts = [
    //   'data' => 'array',
    //];

    public function getDataAttribute($value)
    {
        $data = json_decode($value);
        foreach ($data['x'] as $k => $v) {
                $data['x'][$k]['string'] = 'example';
        }
        return $data;
    }

    public function setDataAttribute($value)
    {
        $this->attributes['data'] = json_encode($value);
    }

}


text:
Q: NSInputStream from URL doesn't seem to be getting anything I've got the following code, which I know is being run:
ReadDelegate * del = [[ReadDelegate alloc] init];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;

CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)(@"server.com"), port, &readStream, &writeStream);

NSInputStream * readSock = (__bridge_transfer NSInputStream*)readStream;

[readSock setDelegate:del];
[readSock scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

NSOutputStream * writeSock = (__bridge_transfer NSOutputStream*)writeStream;
[writeSock scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSLog(@"Open socket");
[readSock open];
[writeSock open];

[writeSock write:(uint8_t*)("request\0\0\0") maxLength:10];

while (YES) {
     //I'm skipping over inconsequential stuff
}
NSLog(@"finished reading");
[readSock close];
[writeSock close];

return [del getMessage];

My ReadDelegate class is declared like @interface ReadDelegate : NSObject <NSStreamDelegate> and includes a - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode. That particular function just has a print statement in it to see if it's ever being called. It's not.
I know for a fact that the connection is being opened because my server is receiving the "request\0\0\0" message and the server is sending the file (I have tests in other environments which can receive the file just fine).
However, as mentioned, the ReadDelegate object declared in the beginning (del) never receives the stream message, even once (to say the stream is open or whatever).
Why is the delegate not being called?

A: It looks like your stream doesn't receive events because of your while loop.
Every new event from a stream can be handled in a new iteration of run loop. But the new iteration can not be started because the current one never finishes.


text:
Q: Why is this while loop exiting after the first iteration? I have a very strange situation while trying to use a specific tool (efetch from the NCBI E-utilities suite) in a while loop. This is my input file, a list of strings, one per line:
$ cat transcripts.list
NR_169596.1
NR_169595.1
NR_169594.1

I want to run the efetch command using each of those strings as an argument, so I do:
$ while read -r line; do echo "Line: $line"; esearch -db nucleotide -query "$line"; done <  transcripts.list
Line: NR_169596.1
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb689d20b59b3e2e2d405d</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>

This is a single result, not three, as you can see by the single echo that runs.
The same thing works, however, if I use a bad practice for loop:
$ for line in $(cat transcripts.list); do echo "Line: $line"; esearch -db nucleotide -query "$line"; done
Line: NR_169596.1
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb68cabbe98560233344a7</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>
Line: NR_169595.1
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb68cad05f5825d75e3ace</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>
Line: NR_169594.1
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb68cb6bdec5435b5a41cb</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>

Question: How is this possible? Even if there is some sort of bug in the specific esearch program, that shouldn't affect the looping, so why is the shell exiting after the first iteration? And how can the for work and the while fail? What do they do differently here?

Some more details.

*

*Adding an echo in front of the esearch command makes the loop behave as expected, so this has to be related to the specific esearch command (but how can that break the shell loop?):
$ while read -r line; do echo esearch -db nucleotide -query "$line"; done <  transcripts.list
esearch -db nucleotide -query NR_169596.1
esearch -db nucleotide -query NR_169595.1
esearch -db nucleotide -query NR_169594.1

*There is nothing odd in the list itself, I can reproduce it with different lists and there are no hidden characters:
$ od -c transcripts.list
0000000   N   R   _   1   6   9   5   9   6   .   1  \n   N   R   _   1
0000020   6   9   5   9   5   .   1  \n   N   R   _   1   6   9   5   9
0000040   4   .   1  \n
0000044

*I get the same behavior in bash and dash, so it can't be related to things like PIPEFAIL or anything like that. In any case, the exit status of the command is 0:
 while read -r line; do esearch -db nucleotide -query "$line"; echo "EXIT: $?"; done <  transcripts.list
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb69e71191d1185543b24a</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>

*This is happening on a system running Ubuntu, bash, version 4.4.20(1)-release. You can install the efetch tool with sudo apt install ncbi-entrez-direct, if you want to try this out.

*Works as expected in a loop using a different language. For instance, in perl:
$ perl -ne 'chomp;system("esearch -db nucleotide -query \"$_\"")' transcripts.list
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb6c68d8f66e4bb03f00e8</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb6c69947ca95fce4d4f0f</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>
<ENTREZ_DIRECT>
  <Db>nucleotide</Db>
  <WebEnv>MCID_61bb6c6a85c14642940393f9</WebEnv>
  <QueryKey>1</QueryKey>
  <Count>1</Count>
  <Step>1</Step>
</ENTREZ_DIRECT>

A: This is probably because esearch exhausts its standard input; read and esearch are both reading from transcripts.list.
To fix that, change esearch's standard input, e.g. esearch < /dev/null.
See I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed! in the Bash FAQ for details.


text:
Q: NSData returning 0 bytes I am trying to load the image in the following way. But when I call my loadImageFromURL:(NSURL*)inURL function as [self loadImagesFromURL:url] in my tableView its showing 0 bytes.
How to get the value of (delta)NSData in my tableview?, which is declared as global...
NSURLConnection* connection;
NSMutableData* delta;

- (void)loadImageFromURL:(NSURL*)inURL {
    NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];

    if (conn) {
        delta = [[NSMutableData data] retain];
    }
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    [delta appendData:data];

    }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSURL *urlink=[NSURL URLWithString:[[objectsForImages objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]];
    [self loadImageFromURL:urlink];
    UIImage *imageForAz=[UIImage imageWithData:delta];
    cell.imageView.image=imageForAz;

}

A: You're getting confused by the asynchronicity. If loadImageFromURL: were synchronous, e.g. wrapping sendSynchronousRequest:returningResponse:error:, your code would work as you would expect; loadImageFromURL: would block while fetching, and return when delta was populated.
However, this is all asynchronous, so what you actually need to do is implement connectionDidFinishLoading: in your delegate (which in this case is self) and have it set cell.imageView.image there.
Rewriting some of your code accordingly (I assume that you removed extraneous code in tableView:cellForRowAtIndexPath: for the purpose of this example):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSURL *urlink=[NSURL URLWithString:[[objectsForImages objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]];
    [self loadImageFromURL:urlink];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *imageForAz=[UIImage imageWithData:delta];
    cell.imageView.image=imageForAz;
}

Check out the URL Loading System Programming Guide on NSURLConnection for more details / examples.


text:
Q: How do I get hex codes to work with tkinter text boxes? The regular colors like "red", "yellow" etc works. But not hex OS: Windows 10
This is my "texter", it is used to print letter for letter at certain speeds. It takes the text to print, and a text color as arguments. This works perfectly if i write - texter("Hello there", "red")
global charpos
charpos = 1.0
def texter(inserted_text, text_color = "white"):
    global charpos, text
    text.configure(state='disabled')
    charpos = (charpos + 1)
    for char in inserted_text:
        text.configure(state='normal')
        text.insert(charpos, f"{char}", text_color)
        charpos += 1.0
        text.configure(state='disabled')
        waithere(10)

However it stops working and only prints white text when I do something like - texter("Hello there", "orange2")
And "orange2" should be a supported color in tkinter, right?
For instance, this code works perfectly:
texter("[Freya]: ", "yellow")
    texter("Well you don't have a choice!\n\n")

While these examples do not work, and just prints the white text:
texter("[Freya]: ", "snow")
    texter("Well you don't have a choice!\n\n")

texter("[Freya]: ", "#8E44AD")
    texter("Well you don't have a choice!\n\n")

This is my first python project, started learning two or three weeks ago so please excuse any other mistakes in my code. Does anyone have any good ideas to why the most basic colors work, but the tkinter "advanced" colors do not, and hex values do not?
I should also mention the hex colors and advanced colors DO WORK when applied to the tkinter main window, or background colors of the textbox I am using, but not on the actual text inside it. I believe my texter function is the problem, but I cannot figure out what it is since it is working with regular colors such as "yellow", "blue", "red", "black" etc.

A: Do you know what that last argument to insert is? it's tag name, what you should do, is then configure that tag to the color you want, so basically just add text.tag_config(text_color, foreground=text_color) at the end of the function, also I hope that you understand that you don't need to insert characters individually and you can just do text.insert(charpos, inserted_text, ...) and then just do charpos += len(inserted_text), so the function now should look like:
charpos = 1.0
def texter(inserted_text, text_color = "white"):
    global charpos
    charpos += 1
    text.configure(state="normal")
    text.insert(charpos, inserted_text, text_color)
    text.tag_config(text_color, foreground=text_color)
    text.configure(state="disabled")
    charpos += len(inserted_text)
    waithere(10)

A: There are a couple of problems with your code.
The first is the declaration of charpos as a float. tkinter.Text widget uses a string of two integers connected by a dot. (1.0 = row 1. column 0). There are methods for calculating cursor position in Text widget.
The second problem is the use of color_text to change foreground color. You need to use text.tag_config(color_text, ...) to declare color_text as a tagname.
Here is a code snippet that demonstrates.

import time
import tkinter as tk

window = tk.Tk()

text = tk.Text(window)
text.grid(sticky = tk.NSEW)

charpos = '1.0'

def waithere(n):
    text.update()
    while n > 0:
        n = n - 0.00005

def texter(inserted_text, text_color = "white"):
    text.configure(state='disabled')
    charpos = text.index("end")
    # inform text of new color tag
    text.tag_config(text_color, foreground = text_color)

    for char in inserted_text:
        text.configure(state='normal')
        text.insert(charpos, f"{char}", text_color)
        charpos = text.index(charpos + " + 1c")
        text.configure(state='disabled')
        waithere(10)

# showing off with multiple colors on same line.
for a in range(3):
    texter("Hello ", "black")
    texter("i'm a ", "blue")
    texter("robot\n", "red") # linefeed here controls text layout


text:
Q: 0xc000007b "The application was unable to start correctly" error? I've written a C++ console application in Visual Studio 2019 and am trying to deploy it to another windows laptop. Both laptops are up-to-date with 64 bit Windows 10, and my target laptop has installed/up-to-date .NET Framework, vc_redist.x64.exe, and DirectX.
In terms of deployment method, I followed this Microsoft walkthrough word for word, with the added step of ensuring that my newly created "setup" project was also targeting x64 platform, since some of the external libraries in my code required x64. The resulting "setup" .exe/.msi pair work as planned on the source laptop - installs and runs with no frills required.
Installation goes fine on the target laptop, but launching the program gives the error mentioned in the title of this post. After a few hours of trying to figure it out, I think I have an idea where the problem is coming from, but first, I'll share what I've tried, which is basically every recommendation found by googling this error code:

*

*clean boot

*SFC scan

*chkdsk c: /f /r

*repairing/fresh installing all of the frameworks mentioned in the first paragraph

*running both the application installer and the installed application as administrator

*restarting laptop and reinstalling application after all of those changes

What I think is the root of the problem:
In the setup/deployment project in VS, three of the "detected dependencies" (MSVCP140D.dll, ucrtbased.dll, VCRUNTIME140D.dll) have filepaths through …\System32\ rather than the identical dependencies that could be found in …\SysWOW64. The other two detected dependencies are external 64-bit DLLs (which is why I specified my entire project to x64). When I run my application through Dependency Walker, it agrees that the three formerly mentioned dependencies are "wrong CPU type", while the two latter ones are fine. This scenario does not, however, explain to me why install/run (outside of VS) works fine on the source laptop (shouldn't it not work if VS is packaging a mix of 32 and 64 bit dependencies?). In fact, running the application through Dependency Walker on the source laptop reveals the exact same thing as on the target laptop - the same 3 dependencies are "wrong CPU type", yet the application runs here.
I do not see an option in VS to change the "setup" project to read the 64 bit filepath. I have tried manually swapping in the 64-bit DLLs at various stages (including restarting the computer between DLL swap and application run), which did not seem to have any effect. In fact, I tried replacing the 3 relevant DLLs in the System32 folder with the DLLs from the SysWOW64 folder (my idea of a cheap workaround for not being able to change the filepath - just change the file) and this just caused me to get the same error on my source laptop as I had been getting on my target laptop.
All of this stuff is relatively new to me, so please let me know if I'm foolishly overlooking some fundamental detail with my process/project - at this point it would be nice if that were the case and this is easy to fix.

A:
Wrote this before I noticed the above comment had already answered.
  Just leaving it in.

Debug Binary: Looks like you have deployed a debug version of your binary (The D in the file name: MSVCP140D.dll). Try to compile in Release mode and deploy the new binary.
Cause: Debug binaries generally need the debug-versions of the VCRedist binaries to exist on the box you try to run the binary - they are only available on developer PCs with the SDK (and / or Visual Studio) installed. That error message: 0xc000007b means "STATUS_INVALID_IMAGE_FORMAT".

Tips: There are some resource links here and some tips on how to debug deployment problems.


text:
Q: Aspnetboilerplate - No Social Login documentation available It seems there's no documentation regarding Social Login.
I went here:
https://aspnetboilerplate.com/Pages/Documents/Zero/User-Management#social-logins
And the Social Login topic is supposed to be discussed here:
https://aspnetboilerplate.com/Pages/Documents/Zero/Startup-Template
Does this means Social Login implementation has been removed from the Boilerplate?

A: It was not done for ABP v3.0.0 as there are tutorials for ASP.NET Core 2.x:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/
If you are using an earlier version like ABP v2.3.0, refer to the documentation reproduced here:

Startup template supports Facebook, Twitter and Google+ logins. In the web.config, you can see the following settings:
<add key="ExternalAuth.Facebook.IsEnabled" value="false" />
<add key="ExternalAuth.Facebook.AppId" value="" />
<add key="ExternalAuth.Facebook.AppSecret" value="" />

<add key="ExternalAuth.Twitter.IsEnabled" value="false" />
<add key="ExternalAuth.Twitter.ConsumerKey" value="" />
<add key="ExternalAuth.Twitter.ConsumerSecret" value="" />

<add key="ExternalAuth.Google.IsEnabled" value="false" />
<add key="ExternalAuth.Google.ClientId" value="" />
<add key="ExternalAuth.Google.ClientSecret" value="" />

Here, you can enable which you need. Surely, you must have application keys and passwords which you need to get from related social web site. You can find guides from web to learn how to obtain this keys. Once you enable a social login and enter true keys, you will see a button in the login page. You can implement other logins as similar.

ABP owner's comment: https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2406#issuecomment-323978304


text:
Q: .Net MVC binding dynamic Type to a Model at runtime I have a slightly long conceptual question I'm wondering if somebody could help me out with.
In MVC I've built a website which builds grids using kendoui's framework.
All the grids on my website are constructed exactly the same except for the model they use and the CRUD methods that need to be implemented for each model.  I set things up where each Model implement an interface for CRUD methods like below to get the logic all in one place.
//Actual interface has variables getting passed
public interface IKendoModelInterface
{
    void Save();
    void Read();
    void Delete();
}

public class Model1: IKendoModelInterface
{

    [Key]
    public int IdProperty1 { get; set; }

    public int SomeProperty2 { get; set; }

    public string SomeProperty3 { get; set; }

    public void Save(){
        //Implement Save
    }

    public void Read(){
        //Implement Read
    }

    public void Delete(){
        //Implement Delete
    }
}

Then to speed up the writing of all the scaffolding Action methods needed to get the grids to work I created an abstract Controller that can call the interface methods of the Model that gets passed into it.
    //Implement the AJAX methods called by the grid
    public abstract class KendoGridImplController<T> : Controller where T : class, IKendoModelInterface
{
    // Method called from kendo grid
    public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<T> createdRecords)
    {
        //Invoke Create Method for Model and return results
    }

     public virtual ActionResult Read([DataSourceRequest]DataSourceRequest request, int Id)
    {
      //Invoke read method for model and return results
    }
    //Update and Delete also implemented..

 }

Then I just need a Controller per model that implements the abstract controller above passing in the type of Model being used.
     public class ResponsibilityMatrixController :  KendoGridImplController<Model1>
{
   //Set up the page the grid will be on
    public ActionResult Index(int id)
    {

        return View("SharedGridView", id);
    }
    //Can override abstract methods if needed but usually won't need to
}

I'm wondering if I can take this one step further or if I've reached the end of the road.  To me it just seems like more repeated code if I have to create a controller per Model that does nothing but pass in the type to the abstract controller and calls the same View.
I attempted for quite a while yesterday to figure out if I could dynamically assign the type to the abstract controller.  I setup something where I was sending back the type of model via strings and I could still invoke the methods needed.  Where it failed, was that the mapping could no longer be done on any of the controller actions by default since the type isn't known at compile time.  eg
public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<T> createdRecords)

createdRecords can't be bound like this if T that's passed in is an interface and not the Model itself and I've found no real way to map the form data to an instance of a type that isn't known at compile time.
I'm wondering if there's an easy way to do this mapping between an instance of the type of object getting passed in that I can figure out at runtime, if there's some other way to set this up that I'm overlooking or if both those things are going to be way too much work and I should just not attempt something like this and build a controller per model like I do now?

A: In case anybody else finds this in the future here's what I've done so far to solve my issue.  First I downloaded the impromptu-interface code lib which is incredibly helpful when dealing with dynamic types.
Then for the abstract controller's save methods where it was important that I could bind back to the original object type I did this.
// Method called from kendo grid
public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ExpandoObject> createdRecords)
{
    Type originalGridType = GetTypeOfModelUsingCustomCodeIDevelopedEarlier();
    foreach (ExpandoObject record in createdRecords)
    {
        var convertedType = Impromptu.InvokeConvert(record, originalGridType);
        T objectInstance = Impromptu.ActLike(convertedType);
        objectInstance.Save();
    }

}

Then I just needed to add a cast in my model that could convert from the ExpandoObject to my model.  An extra method that I still wish didn't have to be there but with some helper methods that I wrote it's not a lot more code to make happen.
    public static implicit operator Model1(ExpandoObject expando)
    {
        Model1 model = new Model1();
        //Set fields of model...
        //....
        return model;
    }

From here everything works front to back.  Maybe there's a better way but this is the best I could come up with so far.


text:
Q: Azure Load Balancer (Resource Manager) - How to use public IP for backend pool I can't for the life of me find documentation or a clear way to assign the public IP of a VM to the backend pool for a load-balancer (both VM and loadbalancer are Resource Manager assets).
I'm starting to hit the SNAT-related ephemeral port allocation limits with the backend pool of the loadbalancer, and need to use the public ip for a given vm -- though the only information I'm able to find is regarding assigning instance level public ip addresses under the classic deployment model.
Can anyone offer any insights around this?  Thanks!

A: how would you benefit from that?
I'm sure you cannot achieve that, since you basically attach a NIC to a backend pool of a Load Balance (there's the loadBalancerBackendAddressPools property on the VM NIC).
Also, if you look at the Load Balancer reference (https://learn.microsoft.com/en-us/rest/api/network/loadbalancers) you will find that the backend pool is a  Collection of references to IPs defined in network interfaces. And those are basically the ips in the network interface definition. not public ips.


text:
Q: JsonServiceClient C# In Excel COM Add-In We develop an Excel COM Add-In using add-in express. We have been using this add-in past 6 months and we don't have any issue. Past few weeks we start facing an issue in the add-in and after debugging I found that we have an issue with the communication channel between add-in and service stack web service. I am not sure quite what has been changed but we are getting error.

The underlying connection was closed: An unexpected error occurred on a send.

I tried to use the same line of codes in the LINQPad, and it works fine. But in the add-in, it does not work and generates the above error.
using (var client = new JsonServiceClient(_config.SchemaServiceUrl))
{
    client.UserName = login;
    client.Password = password;

    response = client.Get<AuthenticateResponse>("/auth");
}

Any suggestions or comments on this?
Regards,
Jamil


text:
Q: Inversion of control - when to use? In which cases should I use inversion of control - for constructing all application classes or just these that depends on some other object?

A: Simply put, whenever you want loose coupling between classes.
I think that Mark Seemann in his book Dependency Injection in .NET  has a simple but very true statement about DI/IoC:

DI enables loose coupling, and loose coupling makes code more maintainable.

So you should use it when you want to have all the advantages that loose coupling brings, to name a few from the book: late binding, extensibility, parallel development capabilities, testability. For all these advantages you pay the cost of implementing and maintaining an IoC solution in your codebase, which for green field projects is IMHO negligible, especially thanks to IoC containers. For ideas on how to implement it globally for your application you may have a look at the Composition Root Pattern.
Of course, it is also possible to implement IoC only for parts of your project, especially if you are working with a brown field project. If you are using an IoC container though, one disadvantage of this approach is that the use of the IoC container may not be transparent anymore, but you have to explicitly call it and ask for the instances that you need (Service Locator Pattern).


text:
Q: Isn't the set of all literature a regular language? Let one piece of literature be one string.  Let's define our alphabet to be sufficient to represent all literature (e.g. we may need a page-turn character, etc).  So, since the collection of current literature is finite, it is a regular language.  However, we usually talk about such languages as context sensitive and natural which are harder for a computer to deal with.  So, what am I missing here?
Thanks.


text:
Q: Set up payment attribute in Nopcommerce I am using nopcommerce version 4.50. I need to add new attribute for payment page same as checkout attribute. Some new fields need to be added in Payment Page.
Please help me with the steps or helpful link.


text:
Q: What is the correct way to share a locking reference to a resource in AVR (no_std) Rust? I have two device drivers that need to use the SPI bus.
Fortunately the one that wants to "own" it, uses a trait, and I can interpose my own implementation.
If this were regular Rust an Arc<Mutex<SPI>> would be sufficient, but I am encountering challenges.

extern crate alloc;

use alloc::sync::Arc;
use avr_hal_generic::avr_device::interrupt::{CriticalSection, Mutex};

...

let spi = Arc::new(Mutex::new(spi));
let device_interface = SpiWorkaround::new(spi.clone(), cs, dc);

When I try to compile this in a project based off the https://github.com/Rahix/avr-hal-template I get
error[E0463]: can't find crate for `alloc`
 --> src/main.rs:5:1
  |
5 | extern crate alloc;
  | ^^^^^^^^^^^^^^^^^^^ can't find crate

If I add alloc="*" to the Cargo.toml I get
error: no matching package named `alloc` found
location searched: registry `crates-io`

I was able to get past these using cargo build --release -Z build-std=core,alloc (is there a way to put that in the Cargo.toml?) and got this error:
error[E0432]: unresolved import `alloc::sync`
 --> src/main.rs:7:12
  |
7 | use alloc::sync::Arc;
  |            ^^^^ could not find `sync` in `alloc`

What is the proper technique for letting two data structures take turns using an object in the no_std AVR environment?

A: You cannot use Arc for that. Arc uses atomic usize for its reference counter, and therefore only supports target that have usize-sized atomics. Unfortunately the size of usize for your platform is 16 bits, but it only supports up to 8 bits atomics.
You can copy the source code of Arc from std and adapt it to use AtomicU8 instead of AtomicUsize (there may already be a crate for that, I didn't found one though). Note this will only support up to 255 active owners.
As for the other question, you can put change .cargo/config.toml [build-std] key as follows to avoid the need to pass -Zbuild-std every time:
[unstable]
build-std = ["core", "alloc"]


text:
Q: Can free abelian groups have a basis of infinite element? I'm now reading Rotman's 'An Introduction to Algebraic Topology' and confused with the definition of free abelian group.

Let $B$ be a subset of an (additive) abelian group $F$. Then $F$ is
free abelian with basis $B$ if the cyclic subgroup $⟨b⟩$ is infinite
cyclic for each $b \in B$ and $F=\sum\limits_{b \in B} \langle b \rangle$ (direct
sum).
A free abelian group is thus a direct sum of copies of $\mathbb{Z}$. A
typical element $x \in F$ has a unique expression $x=\sum{m_b b}$
where $m_b \in \mathbb{Z}$ and almost all $m_b$ (all but a finite
number) are zero.

But next in Theorem 4.1(ii):

Every abelian group G is isomorphic to a quotient group of the form
$F/R$, where $F$ is a free abelian group.

the proof of it said that:

For each $x \in G$, choose an infinite cyclic group $\mathbb{Z}_x$ having
generator $b_x$, say. It follows that $F = \sum\limits_{x \in G} \mathbb{Z}_x$
is a free abelian group with basis $B = \{ b_x : x \in G \}$...(The content hereafter is ommited.)

My question is that an abelian group $G$ could be infinite, then the construction of $F$ in this proof should have a basis of infinite elements, as the book said above:

one can exhibit a free abelian group with a basis of any cardinality
merely by forming the direct sum of the desired number of copies of $\mathbb{Z}$.

but it seems to contradict with the definition of free abelian group because

$x=\sum{m_b b}$
where $m_b \in \mathbb{Z}$ and almost all $m_b$ (all but a finite
number) are zero

I also looked up Wikipedia and another Algebra textbook, free abelian group should indeed be finitely generated. (I misunderstand the sentence 'every finitely generated abelian group is a direct sum of a free abelian group and a finite group' , sorry. Edited after.)
I dont't know what's going wrong.
(If I limit the elements of the "infinite direct summed free abelian group" to those who have finite nonzero components, then the finite linear combination of them should also have finite nonzero components, but that seems strange and I don't think this should be called a direct sum. )


text:
Q: How to update positions of inset axes in matplotlib set_position() seems not to work for inset axes in matploltib, see code below:
import matplotlib.pyplot as plt

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
# make inset axes
axin = ax.inset_axes([0.1, 0.1, 0.2, 0.2])
# update position, NOT working
axin.set_position([0.2, 0.2, 0.2, 0.2])

Is there any way to update position of inset axes ?

A: Here's a great answer. I saw this and modified your code. I don't have enough knowledge to explain this so please refer to his answer.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
axin = ax.inset_axes([0.1, 0.1, 0.2, 0.2])

ip = InsetPosition(ax,[0.2, 0.2, 0.2, 0.2])
axin.set_axes_locator(ip)


text:
Q: onclick of a link Submitting a form I am working on a application where I am using tiles templates for display. In a screen, on left hand side I am displaying the links for navigating to other pages. on the right hand side I am displaying the content of the screen.
Both are from different JSP's. So I need to do a form submission from screen's content by clicking on that link. Please suggest any ideas for doing this, I am not even close get this idea on how to write a javaScript function for this case.

A: If I get your question correctly, There are two ways in which you can send your form easily.

*

*Write a event Handler and call document.getElementById("myForm").submit(); where "myForm" is your form name.

*Use jquery for the same. The code below can help if your form id is target. Here other refers to a button or link which you click.
$( "#other" ).click(function() {
  $( "#target" ).submit();
});


text:
Q: NGINX: поиск ресурса во внутренних папках Итак, есть конфигурационный файл, вот часть конфига:
    location = / {
        root   www/html;
        try_files $uri $uri/ $uri.html;

    }

    location ~* \.(jpg|jpeg|png)$ {
        root www/resources/img;
        expires 1y;
        add_header Cache-Control public;
    }

    location ~* \.(css)$ {
        root www/resources/css;
        expires 1y;
        add_header Cache-Control public;
    }

    location ~* \.(js)$ {
        root www/resources/js;
        expires 1y;
        add_header Cache-Control public;
    }

Если сделать запрос: localhost/1.jpg, то файл будет найдет во втором location (www/resources/img), но если вложить в эту папку еще одну с другой картинкой, то в ней поиск происходить не будет. Как сделать, чтобы если в директории www/resources/img файл не нашелся, то nginx самостоятельно прошелся по внутренним папкам и там искал файл?


text:
Q: HTML elements not lining up when text is too long I am using Twig Templates with scss and js files. I created a twig template for Bootstrap popovers. The popover information is formatted correctly in most cases. However, it seems that when some text becomes too long, specifically the Instructor Info
 tag, the alignment gets altered.
The correct layout. @ is the icon.
@ Header Text
  Instructor info text
  text text text text text text

@ Header Text
  Instructor info text
  text text text text text text

The error case
@
Header Text
Longer than average Instructor info text
text text text text text text

@ Header Text
  Instructor info text
  text text text text text text

The twig and html
{% embed 'fragments/popover.html.twig' %}
    {% block link_class %}more-sections{% endblock %}
    {% block link_text %}

    {% endblock %}

{% block title %}Contact Info{% endblock %}
{% block content %}
    {% for ArrayIndex in 0..(section.getInstructorNamesArrayCount()-1)  %}

{{section.getInstructorNamesArray()[namesArrayIndex]}}

{{ section.getInstructorInfo()[namesArrayIndex] }}

{{ section.getInstructorEmails[namesArrayIndex] }}

   {% endfor %}
{% endblock %}

CSS
.instructor-contact-info-header {
  display: inline-block;
  color: #005993;
  margin: 0;
}

.instructor-contact-info-data {
  margin: 0;
}

.contact-info-container {
  display: inline-block;
  vertical-align: top;
}

EDIT:: Below is the rendered code for one block of info that produces the

LASTNAME, S.

Title, Department of..., Statistics

email@email.com

Here is the rendered code second contact information that produces the correct layout

LASTNAME, D.

Statistics

name@email.com


text:
Q: Programmatically add Pivot Items I want to display a list of photos in a Pivot Control, so I have this xaml
<Grid x:Name="LayoutRoot" Background="Transparent">
    <controls:Pivot x:Name="DiaporamaPivot">
    </controls:Pivot>
</Grid>

and in the code behind I do :
    public Diaporama()
    {
        InitializeComponent();

        PivotItem p = new PivotItem();
        Image     i = new Image();

        i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
        p.Margin = new Thickness(0, -10, 0, -2);

        DiaporamaPivot.Items.Add(i);
    }

Any idea why I get an exception

A: You are adding i (Image) to Pivot. Instead, add i to p and then, add p (PivotItem) to Pivot.
public Diaporama()
{
    InitializeComponent();

    PivotItem p = new PivotItem();
    Image     i = new Image();

    i.Source = new BitmapImage(new Uri("/image.jpg", UriKind.Relative));
    p.Margin = new Thickness(0, -10, 0, -2);

    p.Content = i;
    DiaporamaPivot.Items.Add(p);
}


text:
Q: SVG file parsing issue in java I'm trying to parse the following svg file named 1.svg:
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="841.89px" height="595.28px" viewBox="0 0 841.89 595.28" enable-background="new 0 0 841.89 595.28" xml:space="preserve">
<g id="Layer_2">
</g>
<g id="Layer_1">
    <line fill="none" stroke="#ED1C24" stroke-miterlimit="10" x1="103.667" y1="105.667" x2="126.667" y2="95"/>

</svg>

With the following java program.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class Test {

    public static void main(String[] args){
        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse("1.svg");

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

For some reason I cannot understand I get
java.io.FileNotFoundException: http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1835)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:646)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:1300)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:1267)
    at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:263)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1164)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1050)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:964)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:177)
    at Test.main(Test.java:12)

I tried to open the file with File class and it worked. Can you give me some help with it? Thanks!

A: Your SVG file references a DTD which is getting loaded.
You can turn off DTD loading:
dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

and maybe also
dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);


text:
Q: Lightning component to display records based on selected static picklist value Please help me how to display Account records based on selected picklist value. If picklist value "Banking" is selected then only those Account should be displayed which Industry is Banking, if Non Banking is selected then those Account records should be displayed which Industry type is other than Banking.
Apex:

    public class CustomListView {
        @AuraEnabled
        public static List <Account> fetchAccounts() {
            List<Account> accList = [SELECT Id, Name, BillingState,
                                        Website, Phone, Industry, Type from Account];
            //return list of accounts
            return accList;
        }
    }

Component:

<aura:component controller="CustomListView">

    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>

    <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/>

    <lightning:select name="cStat" label="select a value" value="New" aura:id="statusPicklist" >
        <option value="All">All</option>
        <option value="Banking">Banking</option>
        <option value="Other">Other</option>
    </lightning:select>

    <lightning:datatable data="{! v.acctList }"
                         columns="{! v.mycolumns }"
                         keyField="id"
                         hideCheckboxColumn="true"/>

</aura:component>

Controller:

({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, helper);
    },

    onChange: function (cmp, event, helper) {
        var selectedPicklistValue= component.find("statusPicklist").get("v.value");
        alert("selectedPicklistValue ==>" +selectedPicklistValue)

    }

})

Helper:

({
    fetchAccHelper : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
                {label: 'Industry', fieldName: 'Industry', type: 'text'},
                {label: 'Phone', fieldName: 'Phone', type: 'Phone'},
                {label: 'Website', fieldName: 'Website', type: 'url '}
            ]);
        var action = component.get("c.fetchAccounts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})

App:

<aura:application extends="force:slds">
    <c:CustomListView/>
</aura:application>

A: Shared code requires many changes as below:
1.)Apex Controller :
Since you need to fetch accounts based on industry , it needs to be passed to apex
public class CustomListView {
        @AuraEnabled
        public static List <Account> fetchAccounts(String accountType) {//Pass accountType from lightning
            List<Account> accList = new List<Account>():
            //query based on passed value
            if(String.isNotBlank(accountType)){
            accList = [SELECT Id, Name, BillingState,Website, Phone, Industry, Type from Account WHERE Industry =:accountType];
           }
           else{
                 //add limit according to your requirement or implement pagination
                 accList = [SELECT Id, Name, BillingState,Website, Phone, Industry, Type from Account LIMIT 5000];
           }
            //return list of accounts
            return accList;
        }
    }

2.) Lightning component:
  Here , we can declare a attribute to store account type ,bind it with lightning:select and initialize it with blank value.Also , call controller function on change of picklist selection.
<aura:component controller="CustomListView">

    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="accountType" type="String" default=""/>

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/>

    <lightning:select name="cStat" label="select a value" value="{!v.accountType}" aura:id="statusPicklist" onchange="{!c.fetchAcc}">
        <option value="">All</option>
        <option value="Banking">Banking</option>
        <option value="Other">Other</option>
    </lightning:select>

    <lightning:datatable data="{! v.acctList }"
                         columns="{! v.mycolumns }"
                         keyField="id"
                         hideCheckboxColumn="true"/>

</aura:component>

3.) Lightning helper:
Here , pass accounttype value to apex by setting action parameters as below :
({
    fetchAccHelper : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
                {label: 'Industry', fieldName: 'Industry', type: 'text'},
                {label: 'Phone', fieldName: 'Phone', type: 'Phone'},
                {label: 'Website', fieldName: 'Website', type: 'url '}
            ]);
        var action = component.get("c.fetchAccounts");
        action.setParams({"accountType":component.get("v.accountType")});// pass account type to apex
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})

4.) Lightning Controller:
Add "doInit" method and pass blank value in "accountType" so as to fetch all records as written in apex.Also , set accounttype attribute to blank on initial load.
({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, helper);
    },

    onChange: function (cmp, event, helper) {
        var selectedPicklistValue= component.find("statusPicklist").get("v.value");
        alert("selectedPicklistValue ==>" +selectedPicklistValue)

    },

    doInit : function(component, event, helper) {
       helper.fetchAccHelper(component, event, helper);
    }
})

I have not tested it , but this is just to give you an idea of how to pass account type and query based on value passed from lightning component.Also , clarity is needed if all accounts needs to be fetched for none value.


text:
Q: How do I hide the status bar completely in an iOS 7 web app? I'm building a single page JavaScript/PHP web app that currently hides the url bar and stays in full screen successfully with the following code:
<meta name="apple-mobile-web-app-capable" content="yes">

What I need to do now is hide the actual status bar. I've tried the following meta tags to no avail:
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

Is there some other meta tag or JavaScript/PHP code I could use to hide the status bar completely? I noticed that the Belly Card iPad mini web app (www.bellycard.com) does this successfully and I'm not sure how. Any insight is genuinely appreciated.
Cheers!

A: There is no direct method for this (see: similar question) but... this link seems promising:

*

*Everything Hybrid Web Apps Need to Know About the Status Bar in iOS7

The summary of the link is as below:
Key Comments (at link):

When viewing sites in Safari you do not have the ability to customize
  the status bar in any way. Previous versions of iOS offered the
  ability to view sites in full screen mode, but that was removed in
  iOS7, see
http://www.mobilexweb.com/blog/safari-ios7-html5-problems-apis-review.

Key Notes (in link):

StatusBar Cordova Plugin
With iOS7 Apple introduced some native Objective C APIs to control the
  status bar. Because of Cordova, we have the ability to bridge these
  native APIs directly into JavaScript APIs.
  Luckily for us @shazron has already done this with the StatusBar plugin.
After adding the plugin to your application, you are given a StatusBar
  object with a number of methods to manipulate the status bar in
  JavaScript directly.
  ...
  You can hide the status bar using StatusBar.hide(), or even change its
  background color with StatusBar.backgroundColorByName() or
  StatusBar.backgroundColorByHexString().
  For example, the following sets the status bar to green.
<script>
    document.addEventListener('deviceready', function() {
        StatusBar.overlaysWebView(false);
        StatusBar.backgroundColorByName('green');
    }, false);
</script>

...
Outstanding Issues
While the web has come up with workarounds for most of the iOS7 status
  bar issues, there are still a few that remain unresolved.

*

*The status bar still overlays content displayed in a cordova InAppBrowser.
  There is no known workaround, but a fix is slated for cordova 3.2.

*The StatusBar plugin does not work in apps that lock the device into landscape mode.

Key Critic Comment (at link):

These solutions seem to be working only for Phonegap applications, for
  us who don't use this and simply wrap our apps in a webview it seems
  the only easy solution is to set the webview's top property to 20
  instead of zero and that takes care of the issue at hand.


text:
Q: remove extra data after end tag of xml using java I want to remove extra data appended after end tag of XML. for example
dffgghh
My XML is of very large size.I want to read it and delete extra data if present.Please help me.

A: Simply read it as XML. Anything after the
</rootTag>

will be ignored automatically
If you want to clean the file itself, read it so and write back.


text:
Q: Return all the lines in a file after "chomp"ing them I have a subroutine that is used to read the contents of a file, line by line. Is it possible to continue the process instead of returning only one line?
sub read_lines {
    my ($file) = @_;
    if (open(my $fh, "<", $file)) {
        while (my $data = <$fh>)  {
            chomp ($data);
            return $data;
        }
    }
}

A: If you just want to have all the lines of the file in an array, you can also write it like this:
sub read_lines {
    my $file = shift;
    if (open(my $fh, "<", $file)) {
        my @lines = <$fh>;
        chomp(@lines);
        close $fh;
        return @lines;
    } else {
        die "Failed to open Filehandle for '$file': $!\n";
    }
}

or using File::Slurp (faster):
use File::Slurp;
my @lines = read_file($file);
chomp(@lines);

A: Don't return from inside the loop. vOv
sub read_lines {
    my $file = shift;
    my @result = ();
    if (open(my $fh, "<", $file)) {
        while (<$fh>) {
            chomp;
            push @result, $_;
        }
    }
    @result;
}

my @lines = read_lines($file);

Or a shorter equivalent.
sub read_lines {
    my $file = shift;
    open(my $fh, "<", $file) or return;
    my @lines = <$fh>;
    chomp @lines;
    return @lines;
}

my @lines = read_lines($file);