text:
Q: Add temporary additonal Memory Logger on nlog I have nlog configuration working fine on a C# program.
the nlog config is done via standalone file nlog.config
In a specific part of the code I want however to create an additional memory logger target in order to save this specific part of logs in a buffer ( i will later attach this  buffer to a specific object in the  database).
To do so i try to add programmatically the logger and its config.
I check that the logger is added and the rule is added, however nothing comes to the newly created logger.
I think i miss something to tell nlog to actually take in consideration the new logger .
once the target function is executed i want to stop to log this piece of code, stil use the other loggers, and do the same thing on a next item.
I add the memory logger with this lines of code:
                MemoryTarget memoryLogger = new MemoryTarget("memoryTarget");
                memoryLogger.Layout = "${message}";
                LogManager.Configuration.AddTarget(memoryLogger);
                LogManager.Configuration.AddRule(LogLevel.Trace, LogLevel.Fatal, memoryLogger);

below you see the nlog config before i add the new logger:

below the config after the new logger is added:

*

*LogManager.Configuration.LoggingRules has a new element

*LogManager.Configuration.AllTargets has a new element
however in the details of the target i see:

*IsInitialized to false

*Loging config to null ( while i added the rule to LogManager.Configuration

*the 'Logs' property which should contains all the lines logged is empty

I do not want to reinitialise all the nlog since it would reset my logfile, and i want a new log file at each process startup.

A: Thank you @Rolf Kristensen,
indeed,
LogManager.ReconfigExistingLoggers();

Permits to initialize the memory logger without resetting my other logger on File.
By doing this the ConfigurationChanged/ConfigurationReloaded static events of LogManager are even not trigerred, and it works nicely! Great !
Final code to activate and desactivate temporarily the logs in memory:
                MemoryTarget memoryTarget = new MemoryTarget("memoryTarget");
                memoryTarget.Layout = "${message}";
                LogManager.Configuration.AddTarget(memoryTarget);
                var memoryRule = new LoggingRule("memoryRule");
                memoryRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
                memoryRule.Targets.Add(memoryTarget);
                memoryRule.LoggerNamePattern = "*";
                LogManager.Configuration.LoggingRules.Add(memoryRule);
                LogManager.ReconfigExistingLoggers();
                _log.Debug("this is dumped in memory");
                foreach (string s in memoryTarget.Logs)
                {
                    Console.Write("---------mem dumped: {0}", s);
                }
                LogManager.Configuration.RemoveTarget(memoryTarget.Name);
                bool removed = LogManager.Configuration.LoggingRules.Remove(memoryRule);
                LogManager.ReconfigExistingLoggers();
                _log.Debug("no more in memory");

A: If you read this post, you might be interested to grab this piece of code:
    public class MemoryLogger
    {
        static Logger _log = LogManager.GetCurrentClassLogger();
        MemoryTarget _memoryTarget;
        LoggingRule _memoryRule;

        public void Start()
        {
            _memoryTarget = new MemoryTarget("memoryTarget");
            _memoryTarget.Layout = "${message}";
            LogManager.Configuration.AddTarget(_memoryTarget);
            _memoryRule = new LoggingRule("memoryRule");
            _memoryRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
            _memoryRule.Targets.Add(_memoryTarget);
            _memoryRule.LoggerNamePattern = "*";
            LogManager.Configuration.LoggingRules.Add(_memoryRule);
            LogManager.ReconfigExistingLoggers();
        }

        public StringBuilder Stop()
        {
            LogManager.Configuration.RemoveTarget(_memoryTarget.Name);
            bool removed = LogManager.Configuration.LoggingRules.Remove(_memoryRule);
            if (!removed)
                _log.Error("cannot remove rule "+_memoryRule.RuleName);
            LogManager.ReconfigExistingLoggers();
            var ret = new StringBuilder();
            foreach (string s in _memoryTarget.Logs)
            {
                ret.AppendLine(s);
            }
            return ret;
        }
    }


text:
Q: Use custom widgets kivy I'm trying to build a kivy app using some custom widgets.  However whenever I try to use them they never work with my layout.  Using a normal button:
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty

class RootWidget(Widget):pass

class myApp(App):

    def build(self):
        global rw
        rw  = RootWidget()
        return rw

if __name__ == '__main__':
    myApp().run()

#:kivy 1.8.0

<RootWidget>:

    BoxLayout:
        size: root.size
        orientation: 'horizontal'
        spacing: 10
        padding: 10

        Button:
            id: abut
            text: "Custom Button"

This works as expected, my Button basically takes up the entire window.  However when I try replacing the Button with my custom button
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ListProperty

class MyWidget(Widget):

     pressed = ListProperty([0, 0])

     def on_touch_down(self, touch):
         if self.collide_point(*touch.pos):
             self.pressed = touch.pos
             return True
         return super(MyWidget, self).on_touch_down(touch)

     def on_pressed(self, instance, pos):
         print ('pressed at {pos}'.format(pos=pos))

class RootWidget(Widget):pass

class someApp(App):

    def build(self):
        global rw
        rw  = RootWidget()
        return rw

if __name__ == '__main__':
    someApp().run()

#:kivy 1.8.0

<MyWidget>:
    BoxLayout:
        orientation: 'horizontal'
        spacing: 10

        Button:
            id: abut
            text: "Custom Button"

<RootWidget>:

    BoxLayout:
        size: root.size
        orientation: 'horizontal'
        spacing: 10
        padding: 10

        MyWidget:

it only appears in the bottom left-hand corner of the window and doesn't behave like a button.  What am I missing?
Furthermore, is it even necessary to create a custom button this way?  The kivy tutorials used this sort of method to make their custom button but can't I just do something like this
Button:
    on_press: root.do_action()

to make each button behave differently?

A: Your actual problem is that although your MyWidget is placed in a BoxLayout in the kv file, its child BoxLayout does not have its size set to the MyWidget size, and therefore just maintains the default size and position of (100, 100) in the bottom left of the screen.
You can fix this by giving it the extra size: root.size rule as you did within the <RootWidget> rule, or actually normally it's easier to just use a BoxLayout (i.e. subclass BoxLayout instead of Widget) which of course gives you the automatic resizing/positioning for free.
Also, as Joran said, if you just want to do something when the button is pressed you can use the second method...that's what you're intended to do! I don't know what example you are looking at, but you wouldn't normally need a complex arrangement like yours.
You might also be interested to know that in the most recent release (1.8) the button behavior has been abstracted to a ButtonBehavior class that handles detecting touches and dispatching on_press etc. appropriately. The Behavior isn't a widget, so you can subclass it with any other widget to make anything into a button!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xamarin CarouselViewControl support auto slide to next item? just wonder to know how to set it up to Xamarin CarouselViewControl? I manage to find it in other product but not in Xamarin?
Please help.

A: You can implement this by attaching Behaviour to the CarouselViewControl
XAML:
xmlns:cv="clr-namespace:CarouselView.FormsPlugin.Abstractions;assembly=CarouselView.FormsPlugin.Abstractions"
xmlns:behaviour="clr-namespace:TestApp.Behaviours;assembly=TestApp"

<cv:CarouselViewControl x:Name="carousel"
                        ItemsSource="{Binding MySampleItems}"
                        ShowIndicators="true"
                        Orientation="Horizontal">

    <cv:CarouselViewControl.Behaviors>
         <behaviour:AutoscrollCarouselBehavior />
    </cv:CarouselViewControl.Behaviors>

    <cv:CarouselViewControl.ItemsSource>
       <!--Content of Carousel goes here-->
    </cv:CarouselViewControl.ItemsSource>

</cv:CarouselViewControl>

AutoscrollCarouselBehavior.cs Reference
public class AutoscrollCarouselBehavior : Behavior<CarouselView.FormsPlugin.Abstractions.CarouselViewControl>
{
     /// <summary>
     /// Scroll delay in milliseconds
     /// </summary>
     public int Delay { get; set; } = 3000;

     private bool runTimer;
     private CarouselViewControl attachedCarousel;

     protected override void OnAttachedTo(CarouselViewControl bindable)
     {
        base.OnAttachedTo(bindable);
        runTimer = true;
        attachedCarousel = bindable;

        Device.StartTimer(TimeSpan.FromMilliseconds(Delay), () =>
        {
            MoveCarousel();
            return runTimer;
         });

      }

      protected override void OnDetachingFrom(CarouselViewControl bindable)
      {
          runTimer = false;
          base.OnDetachingFrom(bindable);
      }

      void MoveCarousel()
      {
         if (attachedCarousel.ItemsSource != null)
         {
             if (attachedCarousel.Position < attachedCarousel.ItemsSource.GetCount() - 1)
              {
                  attachedCarousel.Position++;
              }
              else
              {
                  attachedCarousel.Position = 0;
              }
          }
      }
 }

This will auto scroll the carousel page, you can set the Delay as per the requirement.

A: The stock Xamarin.Forms CarouselView does not support this at this time. The team is working on reimplementing the CarouselView from the ground up and "auto slide" is on the list as well.
You can find the full proposal and progress here: https://github.com/xamarin/Xamarin.Forms/issues/4996


text:
Q: how to authenticate on an odata2 service in java? (Basic Auth) I'm trying to make a request with java on this OData2 API => https://scihub.copernicus.eu/dhus/odata/v1/ for a project. But I can't without authentication. I have personal logs, as a user I don't have any problems. When I tried with java it gave an error 401.
I try this:
     String auth = user + ":" + password;
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     String basicAuth = "Basic " + new String(new Base64().encode(auth.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.connect();
    int responseCode = connection.getResponseCode();
    System.out.println(responseCode);
    System.out.println(url.toString());

But it doesn't works. When i print the responseCode i have a 400 error and i try also another code it was a 401 error.
With PostMan i only need the BasicAuth to have an access and it works.
And i'm using Olingo2.
I'm new on java web and i don't have any idea.
In the first step i only want to have the authentication.
And then doing queries.
Thank you!

A: For the 401 case there is something wrong with the authorization,otherwise the general approach is right.
For the 400 case, browsers and tools like postman will automatically send additional headers, which the code will be missing. I reused the about code and passed an additional header Accept : application/xml and was able to retrieve the response. Below is the working code. Cheers!
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Test1 {

    public static void main(String[] args) throws IOException {
        String user = "ENTER YOUR USERNAME";
        String password = "ENTER YOUR PASSWORD";
        String auth = user + ":" + password;
        URL url = new URL("https://scihub.copernicus.eu/dhus/odata/v1/");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/xml");
        String basicAuth = "Basic " + Base64.getEncoder().encodeToString((auth).getBytes(StandardCharsets.UTF_8)); // Java
        connection.setRequestProperty("Authorization", basicAuth);
        connection.connect();
        System.out.println(connection.getResponseCode());
        System.out.println(connection.getContent());

    }

}


text:
Q: open proc/[pid]/stat on forked children I am trying to call fopen("proc/{pid}/stats") on children processes
but the forked children seem to execute too fast in order to open
the data while it's still available.
I have tried the following:
for (int i = 0; i < nprocesses; i++){
    wait(&ids[i]);
    FILE *fd;
    char buf[100];
    char str1[] = "proc/";
    char str2[] = "/stats";
    itoa(ids[i], buf);
    strcat(str1, buf);
    strcat(str1, str2);

    char buf2[BUFSIZ];
    fd = fopen(str1, "r");
    while (fgets(buf2, BUFSIZ, temp) != NULL)
        ;
    printf("%s\n", buf2);
}

Is there any way to give the parent program more time so the data
can be opened and processed?


text:
Q: Possible to convert from decimal in hexadecimal? do there exist $d_i \in \{ 0,1,2,3,..15\}, p \in \mathbb N$
such that $$10^{-1}= d_1 16^{-1}+d_2 16^{-2}+...+d_p 16^{-p}?$$
my approach : $10^{-1}= (d_1 16^{p-1}+d_2 16^{p-2}+...+d_p)\cdot 16^{-p} \Leftrightarrow 16^{p}=10\cdot (d_1 16^{p-1}+d_2 16^{p-2}+...+d_p)$
But on the left side we have a number ending in $6$ while in the right side we have a number that ends in $0$ , so the two can't be equal. Is this a valid reasoning? Also what would be the "standard" way for solving such a question?

A: That is good reasoning. I think you are correct.
I think the "standard" argument would be that the right side is a rational number with a denominator divides some power of 16, and no such fraction is equal to $\frac1{10}$ because 10 does not divide $16^{n}$, since it contains a factor of 5, while $16^n$ does not.
But this is quite similar to your argument.


text:
Q: Bootstrap minimum width grid Using twitter bootstrap using a fluid row setup I have

...

...

What I want is to give the first div (with class span4) a minimum width of 275px without upsetting the layout of the second. I've tried just adding min-width: 275px but that makes the second div move to the next line. Is there a way to do this properly?

A:

...

...

Worked for me. It moves the second div to the new line only if the second div has less then ~66% of screen space.
http://jsfiddle.net/daniilr/DAw6p/embedded/result/ (get the code)

A: I have similar issue, too. And I try solve this problem with css and bootstrap. But I can't find a solution. So I solved this problem with jQuery.
My Situation

When window width is narrow, then #image will move to next line. Because #text width can not be loosed anymore from 320px. So #image can not occupy its width, and have to move next line.
How I Solved It
Calculate #image width each window size. And CSS is not proper for this work. So I should use jQuery.
$(window).ready(function() {
    resizeImageWidth();
});

$(document).ready(function() {
    $(window).resize(function() {
        resizeImageWidth();
    });
});

var resizeImageWidth = function() {
    var text_minwidth = parseInt($('#text').css('width'));
    var text_marginLeft = parseInt($('#text').css('margin-left'));
    var image_marginLeft = parseInt($('#image').css('margin-left'));

    if ($(window).width() > 768) {
        var image_width = $(window).width() - (text_marginLeft + text_minwidth + image_marginLeft + 32);
        $('#image').width(image_width);
        console.log(image_width);
    } else {
        $('#image').width('');
    }
}

resizeImageWidth function will get #text width, margin-left, #image margin-left and more thing. Of course it can not fit your code. I should subtract these things. Please check what I have subtracted.
After render div can still move to next line. Maybe some elements is missing. So I subtract 30px hardly. But this calculating still have error. So div can move next line in some window width. So I should subtract a further 2px to prevent it. Ideally I should make more exact calculations.
In small display, this calculating did not be needed. So if ($(window).width() > 768) is needed. And this function should load in $(window).ready. If you load in $(document).ready, then CSS property is not incomplete. So calculating error is bigger.

A: Bootstrap columns are flex items. You have to decide on one column which should shrink when the others have reached their min-width. This prevents elements moving to the next line.
here is a pretty codepen i made: https://codepen.io/timar/pen/VQWmQq/
In this case, we take the other span, reduce it to span1. Give it flex-grow and we have to overwrite bootstraps max-width property.

...

...

to be on the safe side you can reduce the second span only as much as necessary. i.e span6 . Adjust the max-width to the amount the normal span had, we had span8 100/12*8 = 66.66%


text:
Q: Spring port Forwarding for remote database before start application Hi I have a database on server that need SSH connection before.
For that i follow instruction of this post To create a tunnel and port forwarding.
I didn't do the same but i implement this class (that i created directely without all dialogs..)
And then in my application.properties I have this line:
spring.datasource.url = jdbc:mysql://localhost:3307/my_database?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8

But this work when manually I launch the first class, and after that i launch my spring boot app.
How can i do that automaticly before application starting this class be instanciate.
That is my PortFrowarding class:
    package com.demo.demo;

/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/**
 * This program will demonstrate the port forwarding like option -L of
 * ssh command; the given port on the local host will be forwarded to
 * the given remote host and port on the remote side.
 *   $ CLASSPATH=.:../build javac PortForwardingL.java
 *   $ CLASSPATH=.:../build java PortForwardingL
 * You will be asked username, hostname, port:host:hostport and passwd.
 * If everything works fine, you will get the shell prompt.
 * Try the port on localhost.
 *
 */
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;

public class PortForwardingLR{
  public static void main(String[] arg){

    int lport;
    String rhost;
    int rport;

    try{
      JSch jsch=new JSch();

      String host=null;
      if(arg.length>0){
        host=arg[0];
      }
      else{
        host="demo@8.8.8.8";
      }
      String user=host.substring(0, host.indexOf('@'));
      host=host.substring(host.indexOf('@')+1);

      Session session=jsch.getSession(user, host, 22);

      String foo="3307:8.8.8.8:3306";
      lport=Integer.parseInt(foo.substring(0, foo.indexOf(':')));
      foo=foo.substring(foo.indexOf(':')+1);
      rhost=foo.substring(0, foo.indexOf(':'));
      rport=Integer.parseInt(foo.substring(foo.indexOf(':')+1));

      // username and password will be given via UserInfo interface.
      UserInfo ui=new MyUserInfo();
      session.setUserInfo(ui);

      session.connect();

      //Channel channel=session.openChannel("shell");
      //channel.connect();

      int assinged_port=session.setPortForwardingL(lport, rhost, rport);
      System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
    }
    catch(Exception e){
      System.out.println(e);
    }
  }

  public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ return passwd; }
    public boolean promptYesNo(String str){
//      Object[] options={ "yes", "no" };
//      int foo=JOptionPane.showOptionDialog(null,
//             str,
//             "Warning",
//             JOptionPane.DEFAULT_OPTION,
//             JOptionPane.WARNING_MESSAGE,
//             null, options, options[0]);
//       return foo==0;
        return true;
    }

    String passwd;
//    JTextField passwordField=(JTextField)new JPasswordField(20);

    public String getPassphrase(){ return null; }
    public boolean promptPassphrase(String message){ return true; }
    public boolean promptPassword(String message){
//      Object[] ob={passwordField};
//      int result=
//    JOptionPane.showConfirmDialog(null, ob, message,
//                  JOptionPane.OK_CANCEL_OPTION);
//      if(result==JOptionPane.OK_OPTION){
    passwd="ItsNotMyPwd";
    return true;
//      }
//      else{ return false; }
    }
    public void showMessage(String message){
      JOptionPane.showMessageDialog(null, message);
    }
    final GridBagConstraints gbc =
      new GridBagConstraints(0,0,1,1,1,1,
                             GridBagConstraints.NORTHWEST,
                             GridBagConstraints.NONE,
                             new Insets(0,0,0,0),0,0);
    private Container panel;
    public String[] promptKeyboardInteractive(String destination,
                                              String name,
                                              String instruction,
                                              String[] prompt,
                                              boolean[] echo){
      panel = new JPanel();
      panel.setLayout(new GridBagLayout());

      gbc.weightx = 1.0;
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.gridx = 0;
      panel.add(new JLabel(instruction), gbc);
      gbc.gridy++;

      gbc.gridwidth = GridBagConstraints.RELATIVE;

      JTextField[] texts=new JTextField[prompt.length];
      for(int i=0; i<prompt.length; i++){
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 0;
        gbc.weightx = 1;
        panel.add(new JLabel(prompt[i]),gbc);

        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weighty = 1;
        if(echo[i]){
          texts[i]=new JTextField(20);
        }
        else{
          texts[i]=new JPasswordField(20);
        }
        panel.add(texts[i], gbc);
        gbc.gridy++;
      }

      if(JOptionPane.showConfirmDialog(null, panel,
                                       destination+": "+name,
                                       JOptionPane.OK_CANCEL_OPTION,
                                       JOptionPane.QUESTION_MESSAGE)
         ==JOptionPane.OK_OPTION){
        String[] response=new String[prompt.length];
        for(int i=0; i<prompt.length; i++){
          response[i]=texts[i].getText();
        }
    return response;
      }
      else{
        return null;  // cancel
      }
    }
  }
}

And i an trying to launch this method before Application is running like that and it s not working:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SymspringdemoApplication {

    public static void main(String[] args) {
        someMethodThatDoesForwarding();
        SpringApplication.run(SymspringdemoApplication.class, args);
    }

    private static void someMethodThatDoesForwarding() {

        PortForwardingLR.main(null);;

    }
}

Thank.

A: It would be easier to help/understand if you actually posted your own code, but nevertheless if you want to establish port forwarding before Spring starts it's own bootstrapping, simply execute the code before Spring starts creating beans (ultimately the DB-related beans).
E.g.:
...
    /* Execute your custom port-forwarding here */
    someMethodThatDoesForwarding();
    /* SpringBoot code continues.. */
    SpringApplication.run(DemoApplication.class, args);
...

A: You have several options.

*

*You can explicitly call PortForwardingLR.main() from your main method.

*You can use a shell script/batch file to call your PortForwardingLR before your program. You can also use OpenSSH to do the port forwarding.

*You can make PortForwardingLR.main() call your main method.

In my opition, it would be best if you reworked the code in PortForwardingLR into two methods: one for opening a connection, and one for closing connection. The goal is to have something like this:
class MyDatabaseWorker {
    public void run() {
        // Do stuff here
    }

    public static void main(String[] args) {
        PortForwardingLR forwarder = new PortForwardingLR(hostname, user, password);
        forwarder.addPortForward(3306);
        forwarder.connect();
        MyDatabaseWorker worker = new MyDatabaseWorker();
        worker.run();
        forwarder.disconnect();
    }
}

This way, you can reuse PortForwardingLR class for different projects, your DB class is minimally polluted, and you ensure that your DB class is never run without port forwarding.
Be careful, though, because if there is another process listening on port you are forwarding to, this scenario will fail.


text:
Q: java pattern match radius client in clients.conf I want to get all radius client in clients.conf. I have tried to use sed, but my java code failed to execute sed, how to use java pattern match to do the same thing?
sed -n '/^[^#]lient \([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/,/}/{p}' /home/clients.conf

client 172.1.1.0/24 {
secret          = bgate
}

Or, maybe someone can tell me what's wrong with my java code to execute sed?
String[] cmdArray = {"sed", "-n", "'/^[^#]lient \\([0-9]\\{1,3\\}\\.\\)\\{3\\}[0-9]\\{1,3\\}/,/}/{p}'","/home/clients.conf"};
Runtime run = Runtime.getRuntime();
Process process = run.exec(cmdArray);

A: Finally got java to excute sed,turned out i have to use bash -c.
String[] cmdArray = {"bash","-c","sed -n '/^[^#]lient \([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/,/}/{p}' /home/clients.conf"};

A: You can try something like this -
sed 's/}/}\n/g' f

And further you can filter as per your filter criteria.

A: It is trivial to do this in Java:
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.FileReader;

public class Clients {

    public static void main(String[] args) throws Exception {
        Pattern pattern = Pattern.compile("^[^#]lient +[0-9./]+ +\\{");
        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        String line;
        boolean inConfig = false;
        while ((line = reader.readLine()) != null) {
            if (pattern.matcher(line).matches()) {
                inConfig = true;
            }
            if (inConfig) {
                System.out.println(line);
            }
            if (line.startsWith("}")) {
                inConfig = false;
            }
        }
    }

}


text:
Q: Network Inspector keep crashing in android studio Its been more than 3 days. I tried a lot of things but the Network Inspector keep crashing after updated to Bumblebee

A: i had the same problem.
https://developer.android.com/studio/archive
I solved the problem by downloading Android Studio Dolphin (2021.3.1) Canary 7.
If the error persists, you can track it here: https://issuetracker.google.com/issues/219563755

A: I also solved, by updating to latest Stable Android version - which is Chipmunk (version 2021.2.1) as of 05/12/2022.
https://developer.android.com/studio/


text:
Q: B&W grating with defined columns widths MATLAB I'd like to create a fullscreen image with black and white grating. The columns of the grating have all the same width and I want to define them with mm.
Furthermore is it possible to have a variable that , depending on its value , offsets the first column by the defined value ? (e.g. if variable OFF= 0,25; then the first column will start 0,25mm distant from the beginning of the image).
Thank you in advance !
EDIT:
This is what i tried but I can only define the number of columns and not the exact width in mm.
nx = 500 ;
ny = 500 ;
A = zeros(nx,ny);
grating = nx/100;
i = 0 ;
C = grating;
D = 2*grating;
fac = D;
while i ~= nx;
    A(1:1:ny,C:1:D) = 1 ;
    C = C + fac;
    D = D + fac;
    i = i + fac;
end
imshow(A,'InitialMagnification','fit');


text:
Q: issues while running node.js project on windows I got node.js project which is developed to run on linux. Now the requirement is to run it on windows. I am facing some issues in that.
On linux, project runs with script which in turn runs below commands
export ABC_ENV=manufacturing; export NODE_ENV=development; npm run dev

package.json
"scripts": {
    "dev": "ts-node-dev --respawn --transpile-only --inspect -- src/app.ts",
    "build": "./node_modules/typescript/bin/tsc"
  },

src/config/app.config.ts
   import {readFileSync} from 'fs';
    import {join} from 'path';

    const secureEnv = require('secure-env');

    /**
     * Decrypt the .env.enc file, bind parsed environment variables to
     * global.env, and expose them centrally as aliased constants
     * for consumption throughout the app.
     */
    try {
        const basePath = join(__dirname, '../../', `.env-${process.env.ABC_ENV}`)
        const secret = readFileSync(`${basePath}.key`, {encoding: 'utf8'}).trim();
        global.env = secureEnv({secret, path: `${basePath}.enc`});
    } catch (e) {
        console.error(`Problem reading encrypted .env variables:\n${e}`);
    }
    if (!global.env) {
        throw new Error('Environment variables were not properly bound to `global` by secure-env.');
    }
    export const operationalMode = global.env.OP_MODE || 'development';
    export const port = global.env.PORT;
    export const databaseHost = global.env.DB_HOST || 'localhost';
    export const database = global.env.DB_NAME;
    export const databaseUser = global.env.DB_USER;
    export const databasePass = global.env.DB_PASS;
    export const twilioAccountSid = global.env.TWILIO_SID;
    export const twilioApiKey = global.env.TWILIO_API_KEY;
    export const twilioApiSecret = global.env.TWILIO_API_SECRET;
    export const awsAccessKey = global.env.AWS_ACCESS_KEY;
    export const awsSecret = global.env.AWS_SECRET;
    export const awsTopBucket = global.env.AWS_TOP_BUCKET;
    export const expressSessionSecret = global.env.EXPRESS_SESSION_SECRET;
    export const jwtAccessSecret = global.env.JWT_ACCESS_TOKEN_SECRET;
    export const sysadminEmail = global.env.SYSADMIN_EMAIL;
    export const loggingEmail = global.env.LOGGING_EMAIL;

To run project in Windows, first I installed packages with npm i. With secure-env, I have created .env.enc file from .env file. Then I excuted below commands
set ABC_ENV=manufacturing;
set NODE_ENV=development;
npm run dev

But by running above commands, it gives error like which is from app.config.ts :
Environment variables were not properly bound to `global` by secure-env.

I tried with nodemon app.js . But facing same error.
I don't know about node.js and so not able to understand what's happening and don't know what will require to run project on Windows.
Any suggestions to trace what's missing or what should I check will be helpful.
Please help and guide to resolve this. Thanks


text:
Q: How to read in special keys with Win32::Console? When I press the Up-key, this script (Term::TermKey) outputs You pressed: <Up> .
#!/usr/bin/env perl
use warnings;
use 5.012;
use Term::TermKey;

my $tk = Term::TermKey->new( \*STDIN );
say "Press any key";
$tk->waitkey( my $key );
say "You pressed: <" . $tk->format_key( $key, 0 ) . ">";

How could I reach the same result with Win32::Console?
I tried this, but it worked only on "normal" keys like l,k, ... but not with keys like Up, Delete, ...
use Win32::Console;

my $in = Win32::Console->new(STD_INPUT_HANDLE);
$in->Mode(ENABLE_PROCESSED_INPUT);
my $result = $in->InputChar(1);
say "<$result>";

How could I make work keys like Up, Delete, ... too with Win32::Console?

A: The up key does not result in a character. InputChar cannot possible return it. You need to use Input.
my $con_in = Win32::Console->new(STD_INPUT_HANDLE);
for (;;) {
   my @event = $con_in->Input();

   my $event_type = shift(@event);
   next if !defined($event_type) || $event_type != 1;  # 1: Keyboard

   my ($key_down, $repeat_count, $vkcode, $vscode, $char, $ctrl_key_state) = @event;
   if ($vkcode == VK_UP && ($ctrl_key_state & SHIFTED_MASK) == 0) {
      if ($key_down) {
         say "<Up> pressed/held down" for 1..$repeat_count;
      } else {
         say "<Up> released";
      }
   }
}

See KEY_EVENT_RECORD for more information about keyboard events.
See Virtual-Key Codes to identify keys.

Headers and definitions for above code:
use strict;
use warnings;
use feature qw( say );

use Win32::Console qw( STD_INPUT_HANDLE );

use constant {
   RIGHT_ALT_PRESSED  => 0x0001,
   LEFT_ALT_PRESSED   => 0x0002,
   RIGHT_CTRL_PRESSED => 0x0004,
   LEFT_CTRL_PRESSED  => 0x0008,
   SHIFT_PRESSED      => 0x0010,

   VK_UP => 0x26,
};

use constant SHIFTED_MASK =>
   RIGHT_ALT_PRESSED |
   LEFT_ALT_PRESSED |
   RIGHT_CTRL_PRESSED |
   LEFT_CTRL_PRESSED |
   SHIFT_PRESSED;


text:
Q: for loop over a list I have a function ask_phone_number() defined and a for loop inside the function. I want the for loop to iterate over a list (the list contains 1 string of characters). I have an elif statement in the for loop for counting the number of characters of the string in phone_number, but its returning 1 as the count. I guess this is happening because python interpreter sees the string itself as the only item in my list. My question is how can I tell python to count the characters of the string in phone_number list and not just the item in phone_number"
PLEASE SEE CODE BELOW:
def ask_phone_number(correct, phone_number):
    while correct == False:
        phone_number = [input("Enter your phone number >>> ")]
        for ch in phone_number:
            if ("+1" not in ch):
                print("Make sure to enter '+1' and your 10 digit US or Canada phone number")
            elif (phone_number.count(ch) < 12):
                print("Your phone number is incomplete")
            else:
                correct = True
    else:
        return phone_number

if __name__ == "__main__"
   ask_phone_number(False, "")

A: Some issues:

*

*Your code creates phone_number as a list. Drop the square brackets.

*Once the above is fixed, your loop takes every character in the phone number and then counts how many times that character occurs in the phone number. So that will be at least 1 (because you took that character from it), but has obviously nothing to do with the number of digits in the phone number.

*I don't see the utility to pass correct and phone_number as argument. The goal of the function is to ask the user for the phone number, so it should not be an argument. And whether it is correct or not is up to the function to determine, not an argument.
So:
def ask_phone_number():
    while True:
        phone_number = input("Enter your phone number >>> ")
        if not phone_number.startswith("+1"):
            print("Make sure to enter '+1' and your 10 digit US or Canada phone number")
        elif len(phone_number) < 12:
            print("Your phone number is incomplete")
        else:
            return phone_number

A: phone_number.count(ch)

counts the number of times the string ch is in the list phone_number. This is always 1.
You should use
elif len(ch) < 12:


text:
Q: Get notifyed at end of animation triggered by getActionBar().hide() & getActionBar().show() When I hide or show the ActionBar with getActionBar().hide() or getActionBar().show() the action bar (dis)appears in a smooth animation.
Is there a way to get notified once this animation is complete?
Implementing a OnLayoutChangeListener doesn't appear to be a good option as onLayoutChange() is sometimes also called during the animation and there is no way to determine which call is the last and final call.

A: You can use ActionBar.getHeight() to find out the height of the action bar, and when your layout height grows by that many pixels you know the animation has finished.
Alternatively, when ActionBar.getHeight() returns 0, you know the action bar is hidden.

A:
Is there a way to get notified once this animation is complete?

Yes, but you'll have to use reflection. ActionBarImpl uses an Animator to monitor the show and hide animation, so you can attach your own AnimatorListener to this Field and receive the callback.
Here's an example:
private void monitorActionBarAnimation() {
    final ActionBar actionBar = getActionBar();
    try {
        // Get the Animator used internally
        final Class<?> actionBarImpl = actionBar.getClass();
        final Field currentAnimField = actionBarImpl.getDeclaredField("mCurrentShowAnim");

        // Monitor the animation
        final Animator currentAnim = (Animator) currentAnimField.get(actionBar);
        currentAnim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                // Do something
            }

        });
    } catch (final Exception ignored) {
        // Nothing to do
    }
}

Just make sure you use it after you call ActionBar.show or ActionBar.hide because it isn't initialized before those calls. Also, it's released in AnimatorListener.onAnimationEnd so you'll need to call it each time.


text:
Q: Speed up simple distance calculation I'm implementing a simple code that calculates the distance between a point (x_a, y_a) in list_A and all points (x_b, y_b) in list_B and returns the minimum distance found. This is repeated for all points in list_A.
A MWE of my code:
# list_A points defined in array.
list_A = np.array([
    [x_data_a,  # x
     y_data_a]  # y
    ], dtype=float)

# list_B points defined in list.
list_B = [[x_data_b], [y_data_b]]

# Iterate through all data points in list_A
for ind, x_a in enumerate(list_A[0][0]):
    y_a = list_A[0][1][ind]

    # Iterate through all points in list_B.
    dist_min = 1000.
    for ind2, x_b in enumerate(list_B[0]):
        y_b = list_B[1][ind2]
        # Find distance between points.
        dist = (x_a-x_b)**2 + (y_a-y_b)**2
        if dist < dist_min:
            # Update value of min distance.
            dist_min = dist

    print 'Min dist to (', x_a, y_a, '): ', dist_min

The data is formatted like this:
list_A = [[[1.2 2.3 1.5 2.3 5.8 4.6 9.1] [2.5 1.0 4.6 2.4 7.4 1.1 3.2]]]

list_B = [[1.4, 5.8, 7.9], [6.1, 1.2, 3.7]]

For big lists/arrays this can take quite some time to finish. Can this be sped up?

A: Running your code I obtain the following:
Min dist to ( 1.2 2.5 ):  13.0
Min dist to ( 2.3 1.0 ):  12.29
Min dist to ( 1.5 4.6 ):  2.26
Min dist to ( 2.3 2.4 ):  13.69
Min dist to ( 5.8 7.4 ):  18.1
Min dist to ( 4.6 1.1 ):  1.45
Min dist to ( 9.1 3.2 ):  1.69

Converting your array to the following Nx2 arrays:
a
[[ 1.2  2.5]
 [ 2.3  1. ]
 [ 1.5  4.6]
 [ 2.3  2.4]
 [ 5.8  7.4]
 [ 4.6  1.1]
 [ 9.1  3.2]]

b
[[ 1.4  6.1]
 [ 5.8  1.2]
 [ 7.9  3.7]]

Now the following should work:
import scipy.spatial.distance as spdist

dist_arr = spdist.cdist(a,b)

print dist_arr**2
[[ 13.    22.85  46.33]
 [ 26.82  12.29  38.65]
 [  2.26  30.05  41.77]
 [ 14.5   13.69  33.05]
 [ 21.05  38.44  18.1 ]
 [ 35.24   1.45  17.65]
 [ 67.7   14.89   1.69]]

ind = np.argmin(dist_arr,axis=1)

print ind
[0 1 0 1 2 1 2]

print dist_arr[np.arange(ind.shape[0]),ind]**2
[ 13.    12.29   2.26  13.69  18.1    1.45   1.69]

Takes ~.3 seconds if a and b are 2X5000 vs ~135 seconds with the original code. A speedup of 450 times.

A: Use scipy.spatial.distance.cdist and you don't need to write your own distance-calculation code at all.
Edit: You need to transpose your data.  It should be in a format like this:
list_A = [
 [1, 2],
 [3, 4],
 [4, 5]
]

list_B = [
 [8, 9],
 [10, 11],
 [11, 12],
 [13, 14]
]

Currently what you have is a list of X coordinates and a separate list of Y coordinates.  You need to reorient these so you have a single list of XY pairs.  If your data are ordinary lists you can transpose them with list_A = zip(*list_A); if they are numpy arrays you can transpose them with list_A = list_A.T.

A: If you want to avoid using scipy to get scipy.spatial.dist
import numpy as np

a = np.random.rand(2,1000)
b = np.random.rand(2,1001)

min_dist = np.sqrt(np.min([np.min(np.sum((b - a[:,i,None])**2, axis=0))
                           for i in range(a.shape[1])]))

If you're looking for min dist for each point in a, then replace the last line with
min_dists = np.sqrt([np.min(np.sum((b - a[:,i,None])**2, axis=0))
                           for i in range(a.shape[1])])


text:
Q: Particular bash completion files not working when in /usr/share/bash-completion/completions but work fine in /etc/bash_completion.d I have a git repository where I keep some statically-linked binaries along with related man files and bash completion files, which are all 'installed' using GNU Stow to make the symlinks.
I have previously put the symlinks for the bash completion files in /etc/bash_completion.d with no issues, but recently I have started putting them in /usr/share/bash-completion/completions instead, as I thought it was a more correct location for them, seeing as the binaries were going in /usr/local/bin and the man files in /usr/local/share/man.
Everything works as before apart from four specific bash completion files, which are no longer working when placed in this new location. These are:

*

*git-identity.bash-completion

*tmux.completion.bash
And these two for fzf:

*

*completion.bash

*key-bindings.bash
I have 20 other bash completion files that work fine. What is it about these specific bash completion files that make them work while in /etc/bash_completion.d with no issues but not in /usr/share/bash-completion/completions?
EDIT:
They also don't work in ~/.local/share/bash-completion/completions either.

Additional information:
The files are sourced by the standard Debian/Ubuntu .bashrc lines:
# Enable programmable completion features
if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

In both locations it is not the contents on directories are that being sourced, but these two files:
/usr/share/bash-completion/bash_completion
/etc/bash_completion
The second file simply points to the first file if NOT shopt -oq posix. On my setup:
$ if ! shopt -oq posix; then echo "not posix"; fi
not posix

I think the answer must be in /usr/share/bash-completion/bash_completion.

More:
I tried replacing bash_completion with the latest version but that doesn't work either.
https://github.com/scop/bash-completion
Also..
These files do not work when placed in ~/.local/share/bash-completion/completions either.

A: Completion files in /etc/bash_completion.d are always sourced immediately by bash_completion for
backwards compatibility. The completions directories, on the other hand, lazily source the scripts
inside, that is, a particular completion file isn't sourced until completion is requested for that
command. The file to source is determined by its name, thus it must have the same name as the
command you're trying to get completions for. So, for example, tmux.completion.bash should be
symlinked as completions/tmux and not completions/tmux.completion.bash.
Finally, as you're putting everything else under /usr/local, note that you can put the completion
scripts there as well: /usr/local/share/bash-completion/completions.


text:
Q: Extremely Large Integers in PHP
Possible Duplicate:
Working with large numbers in PHP.

I run a completely useless Facebook app. I'm having a problem with PHP's support for integers. Basically, users give themselves ridiculous numbers of points. The current "king" has 102,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,002,557,529,927 points.
PHP does not seem to play well with large integers. When someone tries to add more than a certain amount of points it will fail because PHP treats those numbers as infinite.
Is there some math library for working with ridiculously large numbers? Should I treat the numbers as strings and write my own?
We're talking numbers which are 2^20 digits in length or longer. They don't need to be accurate (any errors are chalked up to the low quality of the app in general) nor does it need to be high performance. I just need something which allows much longer numbers.
(For those of you who are curious, we store our numbers in the cloud, so storage cost isn't a huge issue.)

A: PHP uses floats, or signed 32-bit ints to store numbers. Clearly this is not enough. You can use arbitrary precision arithmetic to store these large numbers. See the PHP book on BC Math for more information:
http://php.net/manual/en/book.bc.php

A: Two PHP libraries for working with large numbers are BC Math and GMP.


text:
Q: Populating filename in Save As window when using Electron Dialog module and .showSaveDialog When using the Dialog module in Electron and .showSaveDialog() to save a file, is there a way to make the filename in the Save As window populate with the actual filename?

A: This can be accomplished with the defaultPath property in dialog.showSaveDialog().
It should be noted that, since it's the defaultPath, you must specify the full file path, not just the name+extension:
dialog.showSaveDialog(
  { defaultPath: '/Users/username/Documents/my-file.txt' },
  function (fileName) {
    // do your stuff here
});

A: According to Electron Docs, defaultPath String (optional) - Absolute directory path, absolute file path, or file name to use by default.
This means if you just pass the file name in the defaultPath like the following without using the absolute path, it will still work.
dialog.showSaveDialog({
  defaultPath: `HelloWorld.txt`,
});


text:
Q: How do I put a text on top of the hat? This is what I'm trying to do:

I basically want to put a hat on top of the word and then a text on top of the hat. How do I do this?

A: Hope the below can meets your requirement:
\documentclass{book}
\usepackage{mnsymbol}
\begin{document}

$\overlinesegment{text}$

\end{document}

Output

A: Not sure if I understood your formatting objective, but the \overbracket directive of the mathtools package may be what you're looking for.

Observe that \overbracket is a math-mode command; hence the $ symbols to initiate and terminate inline math mode and the two instances of \text in
$\overbracket{\text{Jeffrey}}^{\text{name}}$

If your document has several instances of such \overbracket-based directives, it's probably worth setting up a dedicated macro to help simplify and streamline entering the required information. E.g.,
\newcommand\myhat[2]{$\overbracket{\text{#1}}^{\text{#2}}$

This would allow you to input \myhat{Jeffrey}{name}.
Section 3.2.2 of the user guide of the mathtools package provides information on customizing (a) the line thickness of the "hat" and (b) the height of the hat above the baseline.
\documentclass{article}
\usepackage{mathtools} % for '\overbracket' macro
\begin{document}
\sffamily % optional

Hello, $\overbracket{\text{Jeffrey}}^{\text{name}}$!
\end{document}

A: With standard fonts and stmaryrd.
\documentclass{article}
\usepackage{stmaryrd} % for the \mapsfrom glyph
\usepackage{amsmath} % for \arrowfill@

\newcommand{\overhat}[2]{% #1 = main word, #2 = label
  \leavevmode\vbox{\offinterlineskip
    \ialign{%
      \hfil##\hfil\cr
      \footnotesize\strut\,#2\,\cr
      \makehat\cr
      \strut#1\cr
    }%
  }%
}
\makeatletter
\newcommand{\makehat}{%
  \arrowfill@{\mapstochar\relbar}\relbar{\relbar\mapsfromchar}{}%
}
\makeatother

\begin{document}

Hello, \overhat{Jeffrey}{name}

Hello, \overhat{A}{y}

Hello, \overhat{A}{zzz}

\end{document}

Without fonts, so the size of the bars are easily customizable. Here the height is 1pt.
\documentclass{article}
\usepackage{l3draw}

\newcommand{\overhat}[2]{% #1 = main word, #2 = label
  \leavevmode\vbox{\offinterlineskip
    \ialign{%
      \hfil##\hfil\cr
      \footnotesize\strut\,#2\,\cr
      \hatbar
      \leaders\hrule height 0.9pt depth -0.5pt\hfill
      \hatbar\cr
      \strut#1\cr
    }%
  }%
}
\ExplSyntaxOn
\newcommand{\hatbar}
 {
  \draw_begin:
  \draw_cap_round:
  \draw_path_moveto:n {0pt,0pt}
  \draw_path_lineto:n {0pt,1pt}
  \draw_path_use_clear:n { stroke }
  \draw_end:
 }
\ExplSyntaxOff

\begin{document}

Hello, \overhat{Jeffrey}{name}

Hello, \overhat{A}{y}

Hello, \overhat{A}{zzz}

\end{document}


text:
Q: How to get Inline-style strip all text except the number? How can I get an inline style and strip all text so i can calculate a number to replace a style?  I created a rotate button that will rotate a div 45%. instead of using
     document.getElementById('toRotate').style.transform += "rotate(45deg)";

which will add an additional rotate to the style each time clicked im tryng to get the rotation number of the style and add 45 to it then replace the amount so i dont end up with this

My Div

I get an error using replace(/[^0-9]/g, '').  Any help with this is appreciated.

function rotateMe() {

  var lineStyle = document.getElementById('toRotate').style;
  var styNum = lineStyle.replace(/[^0-9]/g, '');
  var calAmount = styNum + 45;
  document.getElementById('toRotate').style.transform = "rotate(" + calAmount + "deg)";

  console.log(lineStyle);
  console.log(lineStyle.replace(/[^0-9]/g, ''));
}
.mydiv {
  background-color: blue;
  width: 150px;
  height: 150px;
  float: left;
  color: #ffffff;
}

#rotateButton {
  width: 80px;
  height: 60px;
  float: left;
}

My Div

<button onclick="rotateMe();" id="rotateButton" type="button">rotate</button>

A: Use a variable and add the angle each time you click

var calAmount =0;
function rotateMe() {
  calAmount+=45;
  document.getElementById('toRotate').style.transform = "rotate(" + calAmount + "deg)";
}
.mydiv {
  background-color: blue;
  width: 150px;
  height: 150px;
  float: left;
  color: #ffffff;
}

#rotateButton {
  width: 80px;
  height: 60px float:left;
}

My Div

<button onclick="rotateMe();" id="rotateButton" type="button">rotate</button>

A: Ok, Rotate div using transform

function rotateMe() {
  var lineStyle = document.getElementById('toRotate').style;
  var rotate = document.querySelector('input[name="rotate"]:checked').value;
  var styNum = lineStyle.transform.replace(/[^0-9]/g, '');
  var calAmount = 0;
  var rotateScale = parseInt(document.getElementById('rotatescale').value);

  if(rotate == 'right')
  {
  calAmount = parseInt(styNum) + rotateScale;
  }
  else
  {
  calAmount = (-rotateScale) - parseInt(styNum);
  }

  document.getElementById('toRotate').style.transform = "rotate(" + calAmount + "deg)";

  //console.log(calAmount);
  //console.log(lineStyle.replace(/[^0-9]/g, ''));
}
.mydiv {
  background-color: blue;
  width: 150px;
  height: 150px;
  float: left;
  color: #ffffff;
}

#rotateButton {
  width: 80px;
  height: 60px;
  float: left;
}
Rotate Right<input type="radio" checked name="rotate" value="right"> Rotate Left<input type="radio" name="rotate" value="left">

<input type="text" id="rotatescale" value="45">

My Div

<button onclick="rotateMe();" id="rotateButton" type="button">rotate</button>

A: You can use a CSS variable (--rotation) to store the angle, and use the variable in the CSS as the value of the transform. On each click, get the current value of the variable, add 45 and set it again:

const rotation = '--rotation';
const toRotate = document.querySelector('#toRotate');

function rotateMe() {
  const rotate = parseInt(getComputedStyle(toRotate).getPropertyValue(rotation));
  toRotate.style.setProperty(rotation, `${rotate + 45}deg`);
}
.mydiv {
  background-color: blue;
  width: 150px;
  height: 150px;
  float: left;
  color: #ffffff;
  --rotation: 45deg;
  transform: rotate(var(--rotation));
}

#rotateButton {
  width: 80px;
  height: 60px;
  float: left;
}

My Div

<button onclick="rotateMe();" id="rotateButton" type="button">rotate</button>

A: you actualy so close, all you need to do is add ".transform" and "parseInt" and voila..
checkout my snippet, hopefully you have a nice day..


text:
Q: Filling input values progmatically on Mobile Browsers I have to implement post code lookup on a website that I am implementing. On the Address Form, there is a field for postal code. When the user types in a post code and navigates to the next field, a REST call is made to an API to fetch the city and canton associated with that post code. I then use jQuery to fill in those values in the respective fields.
We have certain cases where a certain postal code can belong to two different cities (within the same country) and we need to handle those, which we do. The code looks as follows:
$.getJSON(requestUrl, function (json) {
    // Clear the list
    $(postCodeList).empty();

    if (!json) {
        return;
    }
    if (json.length > 1) {
        // Fill the list with cities
        for (var i = 0; i < json.length; i++) {
            var item = document.createElement("li");
            item.setAttribute("data-canton", json[i].canton);
            item.appendChild(document.createTextNode(json[i].city));
            if (json[i].plz === parseInt(plz, 10)) {
                postCodeList.appendChild(item);
            }
        }

        // Append the list
        var wrapperDiv = $citySelector.parent();
        $(postCodeList).css("z-index", 100);
        $(wrapperDiv).append(postCodeList).focus();

        // Handle onClick on suggested city
        $("#post-code-list li").on("mousedown touchend", function (evt) {
            var suggestedCity = $(this).text();
            var suggestedCanton = this.getAttribute('data-canton');

            $cantonSelector.val(suggestedCanton).focus().trigger("input").trigger("blur");
            $citySelector.val(suggestedCity).focus().trigger("input").trigger("blur").focus();

            $("#post-code-list").hide();
            evt.preventDefault();
        });

    } else {
        // Don't return an array in this case
        if (json.plz === parseInt(plz, 10)) {
            $cantonSelector.val(json.canton).focus().trigger("input").trigger("blur");
            $citySelector.val(json.city).focus().trigger("input").trigger("blur").focus();

            $("#post-code-list").hide();
        }
    }
});

In case when we receive an array (json.length > 1), our code works exactly as expected. The relevant part is:
$cantonSelector.val(suggestedCanton).focus().trigger("input").trigger("blur");
$citySelector.val(suggestedCity).focus().trigger("input").trigger("blur").focus();

The chain focus().trigger("input").trigger("blur") is needed to trigger the validation for that is how parsley is setup.
Now, we come to the case where we receive single values json.length <= 1. In this case, we execute the following code:
$cantonSelector.val(json.canton).focus().trigger("input").trigger("blur");
$citySelector.val(json.city).focus().trigger("input").trigger("blur").focus();

The code is exactly the same. However, in this instance, we encounter the following problems.
Chrome

*

*The canton value does not get autofilled.

Safari

*

*The values are filled out, but focus (and viewport) remains on the canton select field. And the options for the canton are still displayed.

Firefox

*

*Values are filled out, but focus (and viewport) remains on the canton select field.

The expected behaviour is that both the canton and city are filled out, the canton field is validated and the focus (and the cursor) remains on the city field. This works on desktop, but not on mobile.
Could someone please explain me as to what it is that I am doing incorrectly?
Thanks


text:
Q: Angular ngModel, 3 arrays are affected I am creating a form builder in Angular, I used Lam Phuoc ThinhI work for reference, check his work here
<https://codepen.io/thinhlam/pen/BowEPp>

Now the problem is I have this 3 arrays, Current Field, Form Fields and Draggable Fields. Everytime I dragged a field, like for example the Header Field and then I changed the text or value of that field, the Draggable Fields is also affected. So if i dragged another Header field the value is the same with the first header field that i drag. Please check the image below.
image
    app.component.html
    <div *ngFor="let set of CurrentField.Settings; let i = index; trackBy:trackByIdx" [ngSwitch]="set.Type">
    <div *ngSwitchCase="'textarea'" class="form-group">
    <label for="textarea-{{i}}">{{set.Name}}</label>
    <input [name]="'textarea' + i"  type="text" class="form-control" [(ngModel)]="set.Value">
    </div>
    </div>

    app.component.ts
    FormFields: any;
    CurrentField: any;
    guid: number;
    DragElements = [{
        'Name': "Header",
        "Type": "textLabel",
        'Icon': "fa fa-header",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Header',
            'Type': 'textarea'
        }]
    }, {
        'Name': "Columns",
        "Type": "columns",
        'Icon': "fa fa-columns",
        'Settings': [{
            'Name': 'Number of Columns',
            'Value': 0,
            'PossibleValue': [2,3,4]
        }, {
            'Name': 'Column',
            'Columns': []
        }],
    }, {
        'Name': "Image",
        "Type": "image",
        'Icon': "fa fa-image",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Image',
            'Type': 'textarea'
        }]
    }, {
        'Name': "Single Text",
        'Type': "text",
        'Icon': "fa fa-font",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Single Text',
            'Type': 'text'
        }]
    }, {
        'Name': "Number",
        'Type': "number",
        'Icon': "fa fa-th-large",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Number',
            'Type': 'text'
        }]
    }, {
        'Name': "Date",
        'Type': "date",
        'Icon': "fa fa-calendar",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Date',
            'Type': 'text'
        }]
    }, {
        'Name': "Single Selection",
        "Type": "dropdown",
        'Icon': "fa fa-dot-circle-o",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Single Selection',
            'Type': 'text'
        }]
    }, {
        'Name': "Pagaraph Text",
        "Type": "textarea",
        'Icon': "fa fa-align-left",
        'Settings': [{
            'Name': 'Field Label',
            'Value': 'Paragraph Text',
            'Type': 'text'
        }]
    }];

    constructor(
        private cd: ChangeDetectorRef,
        private zone: NgZone,
    ) {}

    ngOnInit() {
        this.CurrentField = {};
        this.FormFields = [];
        this.guid = 1;
    }

    createNewField = function() {
        return {
            'id': ++this.guid,
            'Name': '',
            'Settings': [],
            'Active': true,
            'ChangeFieldSetting': function(Value, SettingName) {
                switch (SettingName) {
                    // case 'Field Label':
                    //     this.Settings[0].Value = Value;
                    //     // console.log(Value);
                    //     break;
                    case 'Image Alignment':
                        this.Settings[2].DefaultAlignment = Value;
                        break;
                    case 'Columns':
                        let columns : any = {};
                        this.Settings[0].Value = Value;
                        for(let i = 0; i < Value; i++) {
                            columns = {
                                'ID': i + "-" + this.id,
                                'Title': 'Column '+i,
                                'Items': []
                            }

                            this.Settings[1].Columns.push(columns);
                        }
                        console.log(this);
                        break;
                    default:
                        break;
                }
            },
            'GetFieldSetting': function(settingName) {
                let result = {};
                let settings = this.Settings;
                settings.forEach((index, set) => {
                    if (index.Name == settingName) {
                        result = index;
                        return;
                    }
                });

                if (!Object.keys(result).length) {
                    settings[settings.length - 1].Options.forEach((index, set) => {

                        if (index.Name == settingName) {
                            result = index;
                            return;
                        }
                    });
                }
                return result;
            }

        };
    }

    changeFieldName = function(Value) {
        this.CurrentField.Name = Value;
        this.CurrentField.Settings[0].Value = this.CurrentField.Name;
    }

    removeElement = function(idx){
        if(this.FormFields[idx].Active) {
            this.CurrentField = {};
        }
        this.FormFields.splice(idx, 1);
    };

    addElement(ele, idx) {
        // this.zone.run(() => {
            this.CurrentField.Active = false;
            this.CurrentField = this.createNewField();
            Object.assign(this.CurrentField, ele);
            if (idx == null) {
                this.FormFields.push(this.CurrentField);
            } else {
                this.FormFields.splice(idx, 0, this.CurrentField);
            }
        // });
    };

    activeField = function(f) {
        this.CurrentField.Active = false;
        this.CurrentField = f;
        f.Active = true;
    };

A: Wherever you are using
 Object.assign(this.CurrentField,ele);

like operations
deep clone before pushing.
Object.assign(this.CurrentField, JSON.parse(JSON.stringify(ele)));

This is one way of deep cloning which has its pros and cons. But your solution will be to deep clone using any suitable method.


text:
Q: Using custom directive date formatter on angular-bootstrap datepicker Can some one with angular expertise help me on this one. I have a custom directive that modifies the date from mmddyyyy format to mm/dd/yyyy format. It works fine in simple models.
app.directive('bsDateFormatter', function() {
    return {
        restrict:'A',
        require: 'ngModel',
        scope : false,
        link: function(scope, element, attrs, modelCtrl) {

            var dateCheckRegex=new RegExp(/\d{8}/);

            var dateFormatter = function(dateValue) {
                if(dateValue == undefined){
                    dateValue = '';
                }
                var dateFormatted = dateValue;

                if (dateValue.length==8 && dateCheckRegex.test(dateValue)){
                        var mm=dateValue.substr(0,2);
                        var dd=dateValue.substr(2,2);
                        var yy=dateValue.substr(-4);
                        dateFormatted = mm+'/'+dd+'/'+yy;
                        modelCtrl.$setViewValue(mm+'/'+dd+'/'+yy);
                        modelCtrl.$render();
                }

                return dateFormatted;
            };
            modelCtrl.$parsers.push(dateFormatter);
            dateFormatter(scope[attrs.ngModel]);
        }
    };
});

The problem comes when I use the same directive in angular-bootstrap datepicker-popup. The contents do not get reformatted.
EDIT:
here is the plunker for what I am trying to achieve.
https://plnkr.co/edit/xbu308o4GEBST0yrom19?p=preview
The custom directives work on the input text box. Does not work with the input box with the datepicker-popup directive.


text:
Q: file_get_contents permission denied for external wsdl I have three boxes in my network
Box#1 - a RHEL box with apache and php (basically a LAMP box)
Box#2 - a windows box with JBoss hosting a WSDL using apache axis 2
Box#3 - another windows box (basically a XAMPP box -- more on the third box later)
When I try to run a PHP script on box#1 that uses a SoapClient object to access box#2's  WSDL in a browser it returns:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://XXX.XXX.XXX.XXX:8080/axis2/services/TheService?wsdl' : failed to load external entity

I then tried on box#2 just to simply file_get_contents of the wsdl file I get back:

Warning: file_get_contents(http://XXX.XXX.XXX.XXX:8080/axis2/services/TheService?wsdl): failed to open stream: Permission denied in /application/test.php on line 4

HOWEVER! when I run the last script (file_get_contents) via telnet (command line) when logged in as the same user running apache it returns the WSDL's contents... (!)
--
I tried running the same code on a windows box (box #3) with what appears to be very similar PHP.ini settings to box#2 if not as identical as they could be and I was able to use the wsdl and get the contents of the WSDL file without a problem.
--
I searched (stackoverflow and google) and saw other people had the same issues and tried solutions where listed including:

*

*My PHP.ini's max_file_size is set to 128M (larger than the wsdl)

*allow_url_fopen is set to on

Just to see if it worked on box#1 I tried using cURL to get the contents of the file and it did not return anything.
If anyone can give me any insight it would be greatly appreciated. I'm sure there's a setting in PHP.ini that I am missing or something pretty minor.

A: I ran across this same issue today, after several hours and after trying file_get_contents on my WSDL URL, I noticed that I was getting a permission denied error in my apache error log.  I figured out that SELinux was the culprit.  I believe by default, SELinux blocks httpd from making its own network requests (at least on Fedora).
The fix was: setsebool -P httpd_can_network_connect 1, which then allowed Apache to connect to the remote service (it worked for both SSL and non-SSL requests).
Also answered here: SOAP-ERROR: Parsing WSDL: Couldn't load from url


text:
Q: Field and algebraic extension. How to prove that $[K: F]$ is finite?
If $K$ is a field extension of $F$, then $\alpha \in K$ is algebraic over $F$ if and only if $[F(\alpha):F] < \infty$. Moreover, $K$ is algebraic over $F$ if $[K:F] < \infty$

$\it{Proof}.$
$(\Longrightarrow)$ Suppose that $\alpha \in K$ is algebraic over $F$. Thus, theres exists $\min(F,\alpha)$ and $\deg(\min(F, \alpha)) < \infty$. By the Result 1, $[F(\alpha):F] = \deg(\min(F, \alpha)) < \infty$.
$(\Longleftarrow)$ I couldn't do it. $\square$
Some of the results that I proved:

*

*$\bf{Result\; 1:}$ Let $K$ is a fiel extension of $F$ and let $\alpha \in K$ be algebraic over $F$. Then

If $n=\deg(\min(F,\alpha))$, then the elements $1, \alpha, ..., \alpha^{n-1}$ form a basis for $F(\alpha)$ over $F$, so $[F(\alpha):F] = \deg(\min(F, \alpha)) < \infty$. Moreover, $F(\alpha) = F[\alpha]$.

*

*$\bf{Result\; 2:}$ If $K$ is a finite extension of $F$, then $K$ is algebraic and finitely generated over $F$.

*$\bf{Result\; 3:}$ Let $F \subseteq L \subseteq K$ be fields. Then
$$[K:F] = [K:L].[L:F].$$

*$\bf{Result\; 4:}$ Let $K$ be a field extension of $F$. If each $\alpha_{i} \in K$ is algebraic over $F$, then $F[\alpha_{1}, ..., \alpha_{n}]$ is a finite dimensional field extension of $F$ with
$$[F[\alpha_{1}, ..., \alpha_{n}]:F]\leq \prod\limits_{i=1}^{n}[F(\alpha_{i}):F].$$
I know it's something small I can't see. I liked any hint, no complete solutions. I think it's enough to use Results 2 and 4. But I don't know how.

A: Hint: if $[F(\alpha) : F] < \infty$, the elements $1, \alpha, \alpha^2, \ldots$ cannot be linearly independent in $F(\alpha)$ viewed as a vector space over $F$.


text:
Q: BigNum Class String Constructor Error So i am implementing a BigNum Class to deal with large integers and am currently trying to fix my string constructor class. I have to be able to read Strings such as "-345231563567" in an array with the numbers being read in backwards (i.e. 765365132543). The first part of the code attached checks the first character to see if it is positive or negative and sets positive to true or false. The next part of the code checks for leading zeros in the number that may occur as well as if the number is zero itself. the last part is what is loading the number into the array and for some reason i can not get the code to work. any help with a solution is much appreciated.
    BigNum::BigNum(const char strin[])
{
size_t size = strlen(strin);
positive = true;
used=0;
if(strin[0] == '+')
{
    positive = true;
    used++;
}
else if(strin[0] == '-')
{
    positive = false;
    used++;
}
else
{
    positive = true;
}

// While loop that trims off the leading zeros
while (used < size)
{
    if (strin[used] != '0')
    {
    break;
    }

    used++;
}

// For the case of the number having all zeros
if(used == size)
{
    positive = true;
    digits = new size_t[1];
    capacity = 1;
    digits[0] = 0;
    used = 1;
}
// Reads in the digits of the number in reverse order
else
{
    int index = 0;
    digits = new size_t[DEFAULT_CAPACITY];
    capacity = size - used;

    while(used < size)
    {
    digits[index] = strin[size - 1] - '0';
    index++;
    size--;
    }
    used = index + 1;
}
}

The BigNum.h can be found here
http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/hw2/revised/BigNum.h
and the Test file i am trying to use can be found here. I fail test 7
http://csel.cs.colorado.edu/%7Eekwhite/CSCI2270Fall2011/hw2/revised/TestBigNum.cxx

A: Seems like you allocate DEFAULT_CAPACITY bytes which you have defined as 20 and continue to put 22 digits in it.

A: I just tried to run your code and there seems to be a problem with the digit= line. It is a pointer that you are setting equal to a value. Might that be your problem?


text:
Q: Actual electricity usage to maintain a constant water temperature How can I easily measure (or determine) the actual electrical usage necessary to keep a constant temperature for my water heater?

A: The easiest way I can think of to get some idea of this is to sit by your water heater and listen to it. Assuming you (and no one else) has used any hot water recently (like, within the last hour or so), and that no one uses any more hot water for the duration of this experiment, then the water heater will turn on only to maintain a relatively constant temperature of the water. So, if you can determine how long the water heater runs, and how often it runs, you should be able to determine the approximate energy consumption to maintain the temperature.
For instance, let's say you sit down next to your water heater when it happens to be running. As soon as you hear it turn off, start your stopwatch. As soon as you hear it turn on again (which might be hours later), note the time on the stopwatch, but keep the timer going until you finally hear the water heater turn off again. Now, determine how long it ran, and the "period" of the complete cycle (time elapsed from when it first turned off until it turns off again). Next, if you look around on the water heater, you should be able to find some information about the power consumption in watts or kW (either J/s or kJ/s). The energy consumption per cycle will be that power rating times the amount of time it ran during the cycle. Or, if you want the average power required to keep the water warm, you could take the power rating of the water heater times the amount of time it was on during one cycle divided by the period of the entire cycle. That should give a decent estimate of what you want.
Again, note that it is very important that no one uses hot water during this experiment. And it might take quite a while to do this. Here's some information on water heaters that you might find useful if you want to just do some estimating instead of experimenting:
https://en.wikipedia.org/wiki/Water_heating
http://homeguides.sfgate.com/many-hours-day-hot-water-heater-run-89124.html


text:
Q: IntelliJ-IDEA's Python type checker - incorrect expected type? In the following code:
from typing import List
def test() -> List[str]:
    ret = ["Hi", "Hi"]
    return ret

I'm receiving the following warning on the function definition line:
Expected type 'Integral", got 'str' instead

I can't see any reason why IntelliJ-IDEA's python module would interpret this simple function as returning an list of Integral rather than str. Is this a type checker bug?

A: Pycharm only have some preliminary support for type hints.

A: Note that typing.List is a simple wrapper class that extends builtin list class. It helps in type hinting and doesn't allow creation of new list using itself.
Here is the current code for typing.List:
class List(list, MutableSequence[T], extra=list):

    __slots__ = ()

    def __new__(cls, *args, **kwds):
        if _geqv(cls, List):
            raise TypeError("Type List cannot be instantiated; "
                            "use list() instead")
        return _generic_new(list, cls, *args, **kwds)

By doing typing.List[str], you are trying to call the method __getitem__ on an object typing.List (which is a type). Also note that
This translates to following:
typing.List.__getitem__(str)
# or
list.__getitem__(str)

Now if you see, what does list indexing method expect, it expects an integer like a[0], a[1]. In this case instead of an int like 0, 1, it received a type str
Hope this gives you a more holistic view of typing.List.


text:
Q: GTKmm header files seem to be missing when I try to compile my program I am trying to compile a GTKmm C++ program using g++ (clang), however I can't seem to find the header files that I need. I have run the installation .sh file for GTK+, and I have also tried directly installing GTKmm via Homebrew, but I am still getting this error:
fatal error: 'gtkmm/button.h' file not found

I thought it would be as simple as adding an include directory, but I have tried searching my hard drive for GTK-related things and am still not finding anything. What should I do?
I am using a Macbook running MacOS Big Sur.
Update:
My code is this:
helloworld.h
#ifndef GTKMM_EXAMPLE_HELLOWORLD_H
#define GTKMM_EXAMPLE_HELLOWORLD_H

#include <gtkmm/button.h>
#include <gtkmm/window.h>

class HelloWorld : public Gtk::Window {
    public:
        HelloWorld();
        virtual ~HelloWorld();

    protected:
        //Signal handlers:
        void on_button_clicked();

        //Member widgets:
        Gtk::Button m_button;
};

#endif

helloworld.cpp
#include "helloworld.h"
#include <iostream>

HelloWorld::HelloWorld()
: m_button("Hello World")   // creates a new button with label "Hello World".
{
    // Sets the border width of the window.
    set_border_width(10);

    // When the button receives the "clicked" signal, it will call the
    // on_button_clicked() method defined below.
    m_button.signal_clicked().connect(sigc::mem_fun(*this,
              &HelloWorld::on_button_clicked));

    // This packs the button into the Window (a container).
    add(m_button);

    // The final step is to display this newly created widget...
    m_button.show();
}

HelloWorld::~HelloWorld()
{
}

void HelloWorld::on_button_clicked()
{
    std::cout << "Hello World" << std::endl;
}

main.cpp
#include "helloworld.h"
#include <gtkmm/application.h>

int main (int argc, char *argv[]) {
    auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

    HelloWorld helloworld;

    //Shows the window and returns when it is closed.
    return app->run(helloworld);
}

This code comes from here.
I am compiling by first navigating to the directory of the files listed above, and running g++ main.cpp -o helloworld.
Because I have installed Homebrew, g++ uses clang++.

A: Ok, I have figured it out.
I needed to install both GTK+ and GTKmm via Homebrew. This put the library into /usr/local/include. Note that the question code still won't work, because it is using the wrong directory (I installed gtk+3 and gtkmm3). Refer to this answer for more information.


text:
Q: linkings several docker containers together My current docker images
tutum/rabbitmq                          latest              2b111aa3d5e9        3 days ago          379.1 MB
stackbrew/ubuntu                        12.04               74fe38d11401        2 weeks ago         209.6 MB
ubuntu                                  trusty              99ec81b80c55        2 weeks ago         266 MB
damm/java8                              latest              2fea811f78ac        7 weeks ago         759.5 MB
aglover/java8                           latest              931742e1ae7d        7 weeks ago         1.186 GB
vvoyer/docker-selenium-firefox-chrome   latest              61b0381789d1        5 months ago        1.087 GB

I started the selenium-firefox-chrome container by running
  docker run -p 4444:4444 -p 5999:5999 -d vvoyer/docker-selenium-firefox-chrome

To this container, I wanted to link, damm/java8, and tutum/rabbitmq, I was having trouble with the command to link them.
mycont = my running selenium-firefox-chrome container
So far I have tried something along the following
docker run -d --link mycont:db damm/java8

How do I properly link damm/java8 and tutum/rabbitmq? not sure if I am using the correct commands


text:
Q: Error al hacer una resta en DAO JAVA jpa Tengo un DAO (Data Access Object) para crear un historial. Lo que busco hacer es al momento de crear un historial haga una resta y ese valor se lo ponga a una variable.
Sin embargo, me arroja nullpointerexception. ¿Hay algún problema en mi código?
   public boolean crearHistorial2(Equipo equipo, Usuario usuario, Integer kilo, String ubi, Integer kilore) {
    Historial historial = new Historial();
    historial.setEquipo(equipo);
    historial.setUbicacion(ubi);
    historial.setUsuario(usuario);
    historial.setKilometrost(kilo);
    int valor1;
    valor1= Integer.parseInt(equipo.getKilometrost());
    historial.setKilometros(kilo - valor1);
    historial.setFecha(new Date());
    return jpam.persistirEntidad(historial);
}

El error me lo arroja en la resta y quiero que el valor de esa resta lo tengo el atributo kilómetros.

A: si el error te da aquí historial.setKilometros(kilo - valor1);
Y te da un nullPointer, entiendo que alguno de los dos valores es nulo, usa el debugger y mira que valor tienen los dos campos antes de ejecutar la resta.
Ahora bien, yo veo un comportamiento extraño en tu código, si kilo es un Integer y valor1 un int, ¿Por qué los restas?, quizás es más fácil si creas valor1 como Integer directamente y te evitas el casteo extraño que tuviste que hacer para asignarle valor a valor1.
Yo miraría el valor de los dos campos para comprobar que ninguno sea nulo y trataría de hacer valor1 Integer para hacer la resta Integer - Integer y no int - Integer.
Saludos.


text:
Q: How to get only latest record on filter of foreign key I have a table like this
Event table

id
status
date
order(FK)

1
Planned
05-02-2015
1

2
Delivered
04-02-2015
2

3
Packed
03-02-2015
3

4
Return
06-02-2015
1

I want output like this

id
status
date
order(FK)

2
Delivered
04-02-2015
2

3
Packed
03-02-2015
3

4
Return
06-02-2015
1

I tried with
query = Event.objects.annotate(order_num=Max('date'))

but didn't get the expected result.
How can I achieve this output?

A: Try using the following:
from django.db.models import Max

Event.objects.annotate(max_date=Max('order__event__date')) \
             .filter(date=F('max_date'))


text:
Q: Symfony2 Delete Record I am having issues removing a record from my db using Symfony2. Hoping someone can help me out.
Here is my code:
// Get user's account
$account = $this->getUser()->getAccount();

// Get manager
$em = $this->getDoctrine()->getManager();

// Get entity
$entity = $em->getRepository('WICPurchaseOrderLineItemBundle:PurchaseOrderLineItem')->findBy(array('account'=>$account->getId(), 'id'=>$id));

// If not entity
if (!$entity) {
throw $this->createNotFoundException('Unable to find this entity.');
}

// Remove the record...
$em->remove($entity);
$em->flush();

// Go to this url...
return $this->redirect($this->generateUrl('purchaseOrder_view', array('id' => '8')));

When this is run, I get this error:
 EntityManager#remove() expects parameter 1 to be an entity object, array given.

My URL look like this:
 {{ path('purchase_order_remove_line_item', { 'id': purchaseOrderLineItem.id }) }}

Does my "id" number need to be turned into an object first? Not sure how to fix this, still learning Symfony.
Anyone have any suggestions?

A: You just need to use the findOneBy method instead of the findBy method.
$entity = $em->getRepository('WICPurchaseOrderLineItemBundle:PurchaseOrderLineItem')->findOneBy(array('account'=>$account->getId(), 'id'=>$id));


text:
Q: How to join factors from different rows under multiple loops I'm trying to take a table that has columns (brand, name, id, time, price) and add to it in the same row the price at the time before, so the new column (brand, name, id, time, price, prev_price). In this price and prev_price are both integers.
The challenge I'm running into is that the database I'm working with has a host of different variables for each.
For example:
brands A, B, C, D
name: 1 - 100 (each different for brand)
id: 80 - 300 (also each different for brand)
Example Table with brand and name held constant & what I would want the prev_price factor to contain

brand   name   id   time   price   prev_price
A         25    80   1       103       NULL
A         25    80   2       105       103
A         25    81   1       24        NULL
A         25    81   2       24        0
A         25    81   3       14        -10

Can anyone help recommend how to do this?

A: I think you need to first determine the previous time for each (brand,name,id) triple, then make a self-join on that time to extract the prev_time:
SELECT mytable.*, prev.price AS prev_price
FROM   mytable
  LEFT JOIN (
    SELECT   mytable.*, MAX(t2.time) AS prev_time
    FROM     mytable LEFT JOIN mytable AS prev ON
             prev.brand = mytable.brand
         AND prev.name  = mytable.name
         AND prev.id    = mytable.id
         AND prev.time  < mytable.time
    GROUP BY mytable.brand, mytable.name, mytable.id, mytable.time
  ) AS pairs USING (brand, name, id, time)
  LEFT JOIN mytable AS prev ON
        prev.brand = pairs.brand
    AND prev.name  = pairs.name
    AND prev.id    = pairs.id
    AND prev.time  = pairs.prev_time

A: In that case, try this:
Select mytable.*, x.price AS prev_price
FROM mytable LEFT JOIN
    (SELECT * FROM mytable) AS x ON
    mytable.id = x.id
    AND mytable.brand = x.brand
    AND mytable.name = x.name
    AND mytable.time = x.time + 1


text:
Q: How to correct this solder? I have repaired this circuit from a fridge but the soldering that I have marked in red seems to have pulled away from the copper track. That is because when I tried to replace the capacitor that was there, I had to pull and that was the problem. I have almost cut the track.
The circuit is now working, but I don't know if I can repair this in some way.

A: Make sure that any components that are attached to the pad are attached to the board in a mechanically sound manner.  A little dot of epoxy glue or hot glue should do.  You'll have to use your judgement.
Then make sure that the trace has enough copper to carry the current it used to.  Use your judgement -- usually this is repaired with a bit of bare wire, or copper foil.
If it won't move, and it won't burn up, you're done.


text:
Q: There are AlamManager, SmsManager etc. in Android. Is there also a Manager for managing calls? In Android there are AlamManager:
AlarmManager alarmanager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmanager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+(i*1000),pendingIntent);

and SmsManager:
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(senderNumber, null, "Sorry, I'm kind of busy right now, call u l8r.", null, null);

and so on. I would like to manage calls? Is there also something like 'CallManager'?

A: You're probably looking for TelephonyManager


text:
Q: Trying to push to different viewControllers/view based on what button is pressed I am new to Flutter and am struggling with what seems to be a simple thing.
I have a few buttons in my view, each corresponding to a different (view controller) widget. Depending on what button is pressed I would like to navigate to the corresponding view.
Please see below for a better explanation.
Future navigateToPage(context, vc) async {

  Navigator.push(context, MaterialPageRoute(builder: (context) => vc()));
}

class CircularView extends StatelessWidget {

   @override
  Widget build(BuildContext context) {

    StatelessWidget vc;

    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    Widget bigCircle = Container(
      width: (width * 0.9),
      height: (height * 0.5),
      decoration: BoxDecoration(
        color: Colors.white,
        shape: BoxShape.circle,
      ),
    );

    return Material(
      color: Colors.white,
      child: Center(
        child: Stack(
          children: <Widget>[
            bigCircle,
                Positioned(
                  child: CustomFloatingActionButton(
                   onPressed: () {
                      vc = MoneyView(); // < -- Here is where I am assigning the vc variable to a view.
                      navigateToPage(context, vc);
                   },
                buttonType: ButtonType.money,
                    buttonImage: FontAwesomeIcons.moneyBill,
                    label: '',
                  ),
                  top: ((height * 0.5) * 0.175),
                  left: ((width * 0.9) * 0.12),
                ),
                Positioned(
                  child: CustomFloatingActionButton(
                    onPressed: () {
                       vc = SchedulesView(); // < ---- And here
                      navigateToPage(context, vc);
                    },
                    buttonType: ButtonType.schedules,
                    buttonImage: FontAwesomeIcons.database,
                    label: '',
                  ),
                  top: ((height * 0.5) * 0.123),
                  left: ((width * 0.9) * 0.559),
                ),
                Positioned(
                  child: CustomFloatingActionButton(
                    onPressed: () {
                       vc = VisitsView; // < ---- And here
                      navigateToPage(context, vc);
                    },
                    buttonType: ButtonType.keyDates,
                    buttonImage: FontAwesomeIcons.calendar,
                    label: '',
                  ),
                   top: ((height * 0.5) * 0.434),
                   left: ((width * 0.9) * 0.729),
                ),
                Positioned(
                  child: CustomFloatingActionButton(
                     onPressed: () {
                      vc = RequestsView(); // < ---- And here
                      navigateToPage(context, vc);
                    },
                    buttonType: ButtonType.requests,
                    buttonImage: FontAwesomeIcons.question,
                    label: '',
                  ),
                  top: ((height * 0.5) * 0.687),
                  left: ((width * 0.76) * 0.53),
                ),
                Positioned(
                   child: CustomFloatingActionButton(
                    onPressed: () {
                      vc = KeyDatesView(); // < ---- And here
                      navigateToPage(context, vc);
                    },
                    buttonType: ButtonType.visits,
                    buttonImage: FontAwesomeIcons.handshake,
                    label: '',
                  ),
                  top: ((height * 0.5) * 0.53),
                  left: ((width * 0.76) * 0.051),
                ),
          ],
        ),
      ),
    );
  }
}

The error I am receiving on the simulator states that the No such method error: 'MoneyView' has no instance method 'call'.
So perhaps I am doing something wrong in the 'MoneyView' class.
Thanks for any help you can offer.

A: *

*Add the constructor to the VisitsView object.

*Actually don't call the constructor of vc object in the lambda of the navigateToPage method, cause when you use this function you pass the object inside the function. This is already created object, it doesn't need a constructor.

As advice you can use the named params in your method and functions. It will simplify your life in the future :)


text:
Q: Log4j - How to scan for log4j usages in maven projects along with project name? As part Log4jshell problem, we are trying to analyze which projects use which version of Log4j. I did try the following maven commands
mvn dependency:list | grep log4j
mvn dependency:tree -Dverbose
mvn dependency:tree -Dverbose | grep log4

But it lists information only like this
mvn dependency:tree | grep log4
[INFO] \- org.apache.logging.log4j:log4j-api:jar:2.13.1:provided
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.13.1:provided
[INFO] |  |  +- log4j:log4j:jar:1.2.16:compile
[INFO] |  |  +- log4j:log4j:jar:1.2.16:compile
[INFO] |  +- log4j:log4j:jar:1.2.17:provided
[INFO] +- log4j:log4j:jar:1.2.17:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.13.1:compile
[INFO] \- org.apache.logging.log4j:log4j-core:jar:2.13.1:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.13.1:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.13.1:compile
[INFO] +- org.springframework.boot:spring-boot-starter-log4j2:jar:2.1.8.RELEASE:compile
[INFO] |  +- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.11.2:compile
[INFO] |  +- org.apache.logging.log4j:log4j-jul:jar:2.11.2:compile
[INFO] +- org.springframework.boot:spring-boot-starter-log4j2:jar:2.1.8.RELEASE:compile

I cannot find which project in our workspace it points to. Can anyone please help on this?
Note: There are several maven projects and there is a parent pom.xml for all the pom.xml files. So want to identify which maven projects are using log4j along with the name.

A: Use the includes option
 mvn dependency:tree -Dincludes=org.apache.logging.log4j

example output:
[INFO] com.test:test:jar:0.0.1-SNAPSHOT
[INFO] \- org.springframework.boot:spring-boot-starter-security:jar:2.5.3:compile
[INFO]    \- org.springframework.boot:spring-boot-starter:jar:2.5.3:compile
[INFO]       \- org.springframework.boot:spring-boot-starter-logging:jar:2.5.3:compile
[INFO]          \- org.apache.logging.log4j:log4j-to-slf4j:jar:2.14.1:compile
[INFO]             \- org.apache.logging.log4j:log4j-api:jar:2.14.1:compile

documentation

A: Thanks for the answer. Yes it did answer my question. I used the command below and got the result.
mvn dependency:tree -Dincludes=org.apache.logging.log4j -DoutputFile=`pwd`/maven-report-log4j.txt -DappendOutput=true


text:
Q: How to answer OData sample questions The below question is based in OData.
The service root - https:IIODataDemo:80801MyService.svc
Customerlnvoices and Customers are two entity sets based on the CustomerInvoice and Customer entity types.

It is a big help if anyone can provide answers to the questions below.

*

*Retrieve Customer No and Billing Address of the Customer Invoice where InvoiceId is 15104.

*Retrieve all the Customer Invoices ordered by Invoiceld (Ascending) and CustomerNo(Descending).

*Retrieve all Customers placed between 50th and 1ooth positions when ordered by Customer No in ascending order.

Thanks in advance.

A: *

*serviceroot/CustomerInvoice('15104')?$select=CustomerNo,BillingAddress

*serviceroot/CustomerInvoice?$orderby=InvoiceId asc, CustomerNo desc

*serviceroot/CustomerInvoice?@skip=49&$top=50&CustomerNo asc


text:
Q: Grails Unit Test fails: String-based queries like [executeQuery] are currently not supported in this implementation of GORM There are other questions on SO about this, but they are pretty old and none offer solutions to my issue.
I'm getting the following error from a unit test:
java.lang.UnsupportedOperationException: String-based queries like [executeQuery] are currently not supported in this implementation of GORM. Use criteria instead.
at org.grails.datastore.gorm.GormStaticApi.unsupported(GormStaticApi.groovy:984)
at org.grails.datastore.gorm.GormStaticApi.executeQuery(GormStaticApi.groovy:896)
at org.grails.datastore.gorm.GormStaticApi.executeQuery(GormStaticApi.groovy:892)
at org.grails.datastore.gorm.GormEntity$Trait$Helper.executeQuery(GormEntity.groovy:1026)
at com.mycompany.SomeService.$tt__getSomeThing(SomeService.groovy:54)
at com.mycompany.SomeService.getSomeThing_closure1(SomeService.groovy)
at groovy.lang.Closure.call(Closure.java:414)
at groovy.lang.Closure.call(Closure.java:430)
at grails.transaction.GrailsTransactionTemplate$2.doInTransaction(GrailsTransactionTemplate.groovy:96)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.transaction.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:93)
at com.mycompany.SomeServiceSpec.nominal getSomeThing(SomeServiceSpec.groovy:45)

The line that is breaking the test is:
def something = SomeDomain.executeQuery("some HQL string")

The test looks like this currently (just tracing data currently):
    @TestFor(SomeService)
    @Mock(SomeDomain)
    class SomeServiceSpec extends Specification {

        def setup() {
        }

        def cleanup() {
        }

        void "nominal getSomeThing"() {
            setup:
            def args = ['thingId':1l]

            when:
            def something = service.getSomething(args)

            then:
            println "Thing: ${something}"
        }
    }

My Setup:
Grails 3.1.12
Hibernate 4 (I upgraded to 5 with no change in behavior)
Java 1.8
Groovy 2.4.7

A: Try using the HibernateTestMixin. It supports string-based HQL queries with Hibernate 4.
import grails.test.mixin.TestMixin
import grails.test.mixin.gorm.Domain
import grails.test.mixin.hibernate.HibernateTestMixin

@TestFor(SomeService)
@Domain(SomeDomain)
@TestMixin(HibernateTestMixin)
class SomeServiceSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "nominal getSomeThing"() {
        setup:
        def args = ['thingId':1l]

        when:
        def something = service.getSomething(args)

        then:
        println "THING: ${something}"
    }
}

You will also need to add to your build.gradle:
dependencies {
    testCompile 'org.grails:grails-datastore-test-support'
}


text:
Q: Git ssh url to a specific folder I am setting up my build in TeamCity and it needs an ssh path to the repository.  Usually when I do this, I have one repository per autobuild.  But in my current case, I need to have several autobuilds pulling from the same project (I am building container images).
This is the example ssh I have:

ssh://git@ssh.code.mydomain.net/myproject/container-images.git

But the actual path I want to check out all the files under is:

code.mydomain.net/myproject/container-images/base-build/aspdotnetcore_3.1.10.debian_10.6.build

Is there a way to make an SSH path to that folder only?  (So I get that checked out specifically and only.)

A: No, Git does not allow repository URLs to specify a particular folder for any protocol.  You cannot clone just a particular folder, since commits always refer to the top-level tree.  Git must have those objects in order to keep the objects you care about reachable.
You have a couple of options:

*

*Check out the entire repository.

*Check the repository out somewhere else and create a symlink to the folder you want.

*Clone the repository with the --sparse flag and update the patterns to check out only the files you want (which you can do with git sparse-checkout in recent versions of Git).


text:
Q: How to fetch data in a Single SSRS report using Multiple Dataset I was trying to create SSRS report with a country map and a table. Country Map for showing total Number of Cases state wise and a table to show the total number of Cases in the whole country on the Top Middle side of the Report. Both (Map and Table) Using Different Datasets.
When I run the report to preview the data, It gives me an error:
The Endvalue expression for the map uses an aggregate expression without a scope. A Scope is required for all the aggregates used outside of a Data region
However, I have also tried to use the first dataset to calculate the Sum of all cases in the country.
But it shows the data in the table state wise not the Complete Sum.
=Sum(Fields!Total_Cases.Value)
I have read some issue similar to this topic but unable to implement them.
For displaying total cases in the table I have also mention the dataset name but not getting result.
=(Fields!Total_Cases.Value, "Dataset2")
Please suggest the correct way..


text:
Q: Probability of i.i.d. continuous random variables being the maximum
Let $X_1, X_2, \ldots , X_n$ be i.i.d. continuous random variable with common probability density $f_X$. What is:

*

*$P(X_2 = \max\{X_1,X_2\})$?

*$P(X_n = \max\{X_1,X_2,X_3,\ldots, X_n\})$?

Are these the same as saying $P(X_2 > X_1)$ and $P(X_n > X_1,X_2,X_3, \ldots, X_{n-1})$?  I am also confused about the difference between $P(X_2 = \max\{X_1,X_2\})$ and $P(Y = \max\{X_1,X_2\})$. Any help would be much appreciated.

A: Here is a straightforward proof.
Let $f(x)$ be the pdf, $F(x)$ be the cdf.
$P(X_n \ge \max_{1\le i\le n-1}X_i) = P(X_n \ge X_i, 1\le i\le n-1) = \int_{-\inf}^{+\inf} f(x_n)dx_n \; \Pi_{i=1}^{n-1} \int_{-\inf}^{x_n}f(x_i)dx_i = \int_{-\inf}^{+\inf} f(x_n)dx_n F^{n-1}(x_n)=\frac{1}{n}F^n(x_n)|_{-inf}^{+inf} = \frac{1}{n}.$
Since the random variable is continuous, it makes no difference between equality and inequality. So $P(X_n \ge \max_{1\le i\le n-1}X_i) = P(X_n >\max_{1\le i\le n-1}X_i) = P(X_n = \max_{1\le i\le n}X_i) = \frac{1}{n}.$


text: Q: Test for paired data on categorical variable with >2 levels I am looking for the appropriate statistical test to compare frequencies over a categorical variable with >2 classes, for paired data (in practice, each individual has been labelled A, B, C or D before and after intervention)...I saw that McNemar test works on 2x2 contingency tables. Is there an equivalent test for a 2 x >2 table?


text:
Q: Word VBA: how to pull data from multiple text controls into one body text in the same document? How to pull text from multiple text controls into a single body text in the same document?
Document contains multiple (about 30) text controls, I need to pull data (if data is there) from all of them onto one body of text.
Please help!
Thanks!