text:
Q: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException (Panel displays before fully loaded?) I've been getting this error when I press on a JButton too quickly on a JFrame, so it works if there's a slight delay between compiling the program and pressing on the button. I tried to make a splash screen/loading screen to see if I give the program more time to compile if it will work without the delay, yet thus far it still crashes if pressed too quickly. I was wondering if there is a way to pre-load it such that there doesn't need to be a delay before the button is pressed and so that the error won't exist, thanks!
(relevant pieces of code are listed, but since the entire package has a few thousand lines I'm not going to put all of it here)
This is ran in the main method.
Panels panel = new Panels();
panel.getWindow();

This is in a separate "Window" class
public Window(JPanel panel)
{
    super("Knight Quest");
    //loading screen
    JWindow window = new JWindow();
    window.getContentPane().add(new JLabel("Loading..."));
    window.getContentPane().add(
            new JLabel("", new ImageIcon(getClass().getResource("loading.gif")), SwingConstants.CENTER));
    window.setBounds(600, 300, 400, 300);
    window.setVisible(true);
    try
    {
        Thread.sleep(2500);
    } catch (InterruptedException e)
    {
        e.printStackTrace();
    }
    window.setVisible(false);
    //end of loading screen
    setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600,550);
    setLocation(525, 225);
    setVisible(true);;

}

This is at the top of the Panel class
private Window window = new Window(main());

This is the main() JPanel that starts off the program (just adds stuff to a JPanel)
public JPanel main()
{
    JPanel main = new JPanel();
    check = "main";
    main.setBackground(lightGrey);
    Handler handles = new Handler();

    one = new JButton("Start ");
    two = new JButton("Patch Notes");
    three = new JButton("Exit   ");

    one.addActionListener(handles);
    two.addActionListener(handles);
    three.addActionListener(handles);

    image =  new ImageIcon(getClass().getResource("templar.jpg"));

    JLabel title = new JLabel("Knight Quest");
    title.setFont(new Font("Serif", Font.PLAIN, 45));
    JLabel mainPic = new JLabel(image);
    JLabel versionNum = new JLabel("v1.1.0");
    JLabel credit = new JLabel("Created and developed by Joseph Torres");

    Box panel = Box.createVerticalBox();
    panel.add(title);
    panel.add(Box.createRigidArea(new Dimension(50, 50)));
    panel.add(one);
    panel.add(Box.createRigidArea(new Dimension(50,50)));
    panel.add(two);
    panel.add(Box.createRigidArea(new Dimension(50,50)));
    panel.add(three);
    panel.add(Box.createRigidArea(new Dimension(50,150)));
    panel.add(versionNum);
    panel.add(credit);

    main.add(panel);
    main.add(mainPic);
    return main;
}

And the nullpointerexception is generated at
private class Handler implements ActionListener, KeyListener
{
    public void actionPerformed(ActionEvent event)
    {
        //First Button
        if(event.getSource() == one)
        {
            if(check.equals("main"))
            {
                window.setPanel(prologue());
            }
                    }
            }
     }

and lastly setPanel is a a method made in the windows class that is
public void setPanel(final JPanel panel) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            getContentPane().removeAll();
            add(panel, BorderLayout.CENTER);
            if(Panels.sizeCheck != 1)
            {
                setSize(600, 550);
                setLocation(525, 225);
            }
            else
            {
                setSize(1000, 600);
                setLocation(300, 100);
            }
            revalidate();
            repaint();
        }
    });
}

This is already a huge wall of text, but those are all of the important pieces that I felt were relevant. The code itself works, its just the one issue of it loading too fast or something that I may have overlooked. Let me know if you need any more pieces of code or the full program and I'll be willing to post it. Thanks!
Edit: Stack trace
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Panels$Handler.actionPerformed(Panels.java:1228)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

A: You should not be using Thread.sleep() to delay the loading of your panel. This blocks the UI thread and doesn't do what you want. Instead, use a Swing Timer:
public Window(final JPanel panel)
{
    super("Knight Quest");
    //loading screen
    final JWindow window = new JWindow();
    window.getContentPane().add(new JLabel("Loading..."));
    window.getContentPane().add(
            new JLabel("", new ImageIcon(getClass().getResource("loading.gif")), SwingConstants.CENTER));
    window.setBounds(600, 300, 400, 300);
    window.setVisible(true);
    javax.swing.Timer timer = new javax.swing.Timer(2500,
        new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                window.setVisible(false);
                setLayout(new BorderLayout());
                add(panel, BorderLayout.CENTER);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setSize(600,550);
                setLocation(525, 225);
                setVisible(true);
            }
        }
    );
    timer.setRepeats(false);
    timer.start();
}

EDIT: If the only reason for your splash screen is to give the assignment to window a chance to complete, then there's an easy way to eliminate that: separate construction of the Window object from the display of the panel. You could do something like this:
public Window() {
    super("Knight Quest");
}

public void display(JPanel panel) {
    setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600,550);
    setLocation(525, 225);
    setVisible(true);
}

Then at the top of the Panels class, replace this line:
private Window window = new Window(main());

with a simple declaration:
private Window window;

and move the assignment into the constructor for Panels:
public Panels() {
    // . . . other constructor stuff (if any)

    window = new Window();
    window.display(main());
}

A: The fact that you need a delay to avoid the NullPointerException means that there's an ordering error in your code. It looks like you're just making the Window visible before all your references are set up. Instead of trying to "fix" this with a delay (treating the symptom rather than the underlying problem), you can rework the code a bit so all the references are properly initialized before making the window visible.
Here's an updated Window constructor:
public Window(JPanel panel)
{
    super("Knight Quest");
    // DELETED loading screen
    setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(600,550);
    setLocation(525, 225);
    // DELETED setVisible(true);
}

and an updated Window field initializer in the other class:
private Window window = new Window(main());
// Added initializer to make the Window, then set it as visible
// You could also move this initializer code into the constructor
{ window.setVisible(true); }

Now I believe the Window should be fully constructed, and all the references should be set (including window) before the Window is made visible. That way the user doesn't have a chance to click too early.
If there's actually an issue with the window being invisible for too long, then you might want to do something like suggested in @TedHopp's answer, but rather than adding a delay you can just use invokeLater so that the window updates as soon as it's ready instead of always waiting 2.5 seconds. The fact that it's being scheduled after the current event in the UI event queue should be sufficient without any specific delay.


text:
Q: rmi remote exception. RMI doesnt work I get a remote exception when I try to run my RMI example. I cannot understand why.
I run the program without any arguments to the program itself or to the JVM.
Please help me to get rid of the exception.
Thanks very much
This is the exception I get:
Server exception: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: hello.Hello
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.lang.ClassNotFoundException: hello.Hello

These are the classes I have:
The client class:
package hello;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {

    private Client() {}

    public static void main(String[] args) {

    String host = (args.length < 1) ? null : args[0];
    try {
        Registry registry = LocateRegistry.getRegistry(host);
        Hello stub = (Hello) registry.lookup("Hello");
        String response = stub.sayHello();
        System.out.println("response: " + response);
    } catch (Exception e) {
        System.err.println("Client exception: " + e.toString());
        e.printStackTrace();
    }
    }
}

The remote interace:
package hello;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {
    String sayHello() throws RemoteException;
}

And finally the server:
package hello;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server implements Hello {

    public Server() {}

    public String sayHello() {
    return "Hello, world!";
    }

    public static void main(String args[]) {

    try {
        Server obj = new Server();
        Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

        // Bind the remote object's stub in the registry
        Registry registry = LocateRegistry.getRegistry("localhost");
        registry.bind("Hello", stub);

        System.err.println("Server ready");
    } catch (Exception e) {
        System.err.println("Server exception: " + e.toString());
        e.printStackTrace();
    }
    }
}

A: Either the Registry or the client or both cannot find the class named in the exception. There are several possible solutions:

*

*include that class in the classpath when executing the Registry and the client. And all the classes it depends on, recursively until closure.

*Start the Registry from inside the server JVM, with LocateRegistry.createRegistry(), which solves that classpath problem, and provide the necessary classes on the client's classpath only.

*Use the codebase feature to ensure all the system components can access the required server-side classes.

A: As outlined in the RMI trail
You may need to supply the java.rmi.server.codebase parameter that list all the jars that the RMI server needs to export the objects...
See Running the examples and look at the "Starting the server" section.  Also be sure to check out the section on running the client program for additional suggested parameters

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do all controls have an id in html? For the sampled case:
Does the DOM create an implicit ID to each input object? If so, how can I access this ID?
TIA, here is the code you've requested:

    <INPUT type="button" value="+" onclick="addRow('dataTable')" `enter code here` />

                <INPUT type="text" name="txt[]" />

A: No, id's are assigned by you and you alone.
You could use something like JQuery to implicitily find elements.
$("input").each(function(){});

A: This more specific use of Id
http://api.jquery.com/id-selector/

also add class to your Jquery elements
http://api.jquery.com/class-selector/


text:
Q: system environment variables not working I cannot access my system environment variables from my administrative user account. I am still able to access my user environment variables though. When I try to access SystemPropertiesAdvanced.exe from the Control Panel > All Control Panel Items > System > Advanced system settings, I get an error: "Windows cannot find %windir%\system32\systempropertiesadvance.exe"
From a cmd window, I entered "echo %windir%" and it wasn't set. After that I entered "set" and saw only user environment variables. I navigated to: C:\Windows\System32 and ran SystemPropertiesAdvanced.exe. This worked and I saw my complete list of system variables, but I'm wondering if there is a setting I can adjust which will allow my user account access to the system variables.

A: *

*Go to C:\Windows\System32\ and find SystemPropertiesAdvanced.exe.

*Start the program and click on Environment Variables button.

*Then add new (Name: windir, Value: %SystemRoot%) to system variables.

A: I think I did have access, but the problem was that my user and system %PATH% variables were different. I'm not sure, but I think the user variables are used before system variables. I compared the values of user vs system and my user variable was much smaller. With this I concluded that it mush have been trying to access the wrong variable. Now I don't get the error messages anymore.


text:
Q: CheckboxListTile has null value using Bloc and Stream on Flutter I am creating register form on my flutter app (version 1.17.4). I am using CheckboxListTile in order to user accept the terms. This widget  is validated by bloc and stream
CheckboxListTile
  Widget _createAcceptConditions(LoginBloc bloc) {
return StreamBuilder(
  stream: bloc.getAcceptCondition,
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    return Container(
      child: Container(
          padding: EdgeInsets.only(left: 5, top: 10),
          child: CheckboxListTile(
              title: Text("I accept the terms"),
              value: bloc.acceptCondition,
              activeColor: Colors.deepPurple,
              controlAffinity: ListTileControlAffinity.leading,
              onChanged: (value) {
                bloc.setAcceptCondition(value);
              })),
    );
  },
);
}

LoginBloc class
  final _acceptCondition = BehaviorSubject<bool>();
  Stream<bool> get getAcceptCondition =>
  _acceptCondition.stream.transform(validAcceptCondition);
//Setter
  Function(bool) get setAcceptCondition => _acceptCondition.sink.add;
//Getter
  bool get acceptCondition => _acceptCondition.value;

This is the validator
final validAcceptCondition =
  StreamTransformer<bool, bool>.fromHandlers(handleData: (accept, sink) {
accept ? sink.add(accept) : sink.addError("You must accept the conditions");
});

When I restart the app an try to register I got
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building StreamBuilder<bool>(dirty, state: _StreamBuilderBaseState<bool, AsyncSnapshot<bool>>#8f6de):
'package:flutter/src/material/checkbox_list_tile.dart': Failed assertion: line 269 pos 15: 'value != null': is not true.

The relevant error-causing widget was
    StreamBuilder<bool>
package:neighbour_mobile/…/pages/register_page.dart:205
When the exception was thrown, this was the stack
#2      new CheckboxListTile
package:flutter/…/material/checkbox_list_tile.dart:269
#3      RegisterPage._createAcceptConditions.<anonymous closure>
package:neighbour_mobile/…/pages/register_page.dart:211
#4      StreamBuilder.build
package:flutter/…/widgets/async.dart:509
#5      _StreamBuilderBaseState.build
package:flutter/…/widgets/async.dart:127
#6      StatefulElement.build
package:flutter/…/widgets/framework.dart:4619
...

It seem the bloc is waiting for any user acction in order to put true or false into CheckboxListTile, how ever the default value is null

A: The value in the CheckBox cannot be null, and when you create a BehaviorSubject  or a Stream they doesn't have any data. So you can work with the snapshot value and defining a initialData property in you StreamBuilder to initialize a default value when the Stream is created, try the next:
Widget _createAcceptConditions(LoginBloc bloc) {
    return StreamBuilder(
      stream: bloc.getAcceptCondition,
      // Add a initialData
      initialData: false,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
         // In this point you can validate the snapshot to show the error you are getting

         /**if(snapshot.hasError){
           // Do or show something, for example a Snackbar
         }*/
        return Container(
          child: Container(
            padding: EdgeInsets.only(left: 5, top: 10),
            child: CheckboxListTile(
              title: Text("I accept the terms"),
              // You don't need to use the acceptCondition in this section, because you have the value in the snapshot
              // value: bloc.acceptCondition,
              // In this part the first time the snapshot will be false
              value: snapshot.hasData && snapshot.data ? true : false,
              activeColor: Colors.deepPurple,
              controlAffinity: ListTileControlAffinity.leading,
              onChanged: (value) {
                bloc.setAcceptCondition(value);
              },
            ),
          ),
        );
      },
    );
  }

Hope it helps.


text:
Q: Working Hours Excel Formula I need to calculate the working hours elapsed between two dates and times, for example:

Holiday taken between 01/09/2014 and 05/09/2014
5 working days @ 8 hours per day.

I need the result to show me how many working hours that would be. For example:
ANNUAL ENTITLEMENT: 89.9 Hours
DATE FROM  DATE TO    RETURN TO WORK HOURS REQUIRED HOURS REMAINING DATE
01/09/2014 05/09/2014 06/09/2014       40                49.90

I have no idea if this is even possible!

A: I am assuming these are given cells. if you type in the date to a cell you can click on a new cell and put uptop by the fx this
for example. In C1 you can type this into the fx. Make sure you put the equal sign.
=B1-A1

This is what is the dates in the cells
A1 = 1/9/2014
B1 = 5/9/2014
This will give you 120 which is the total days inbetween.
You will want to get the number of weeks so you can divide by 7.
You will multiply weeks by number of days worked which is 5
Then you want the weeks times 8 hours you can do this in C1
=(B1 - A1)/7 * 5 * 8

which gives you 685.7143

A: you need to also take into account weekends which a simple subtraction will not do. Firstly find the total number of days:
TOTAL_NUMBER_DAYS = B1-A1 + 1

then calculate how many weekends:
TOTAL_WEEKENDS = WEEKNUM(B1) - WEEKNUM(A1)

finally take the total days and subtract weekends:
NET_TOTAL_DAYS = TOTAL_NUMBER_DAYS - (TOTAL_WEEKENDS * 2)

TOTAL_HOURS = NET_TOTAL_DAYS * 8

A: I solved this recently and had a working solution initially in Excel 2013. Slightly adapted to work in 2007 (lack of 'Days()' function). We use it for reporting on support tickets (length of time between opening and closing a ticket).
Inputs are "Workday start", "Workday end" from which "Hours worked" and "Hours not worked" are calulated.
Hours worked =HOUR(WorkEnd-WorkStart)+(MINUTE(WorkEnd)+MINUTE(WorkStart))/60
Hours not worked = 24 - Hours worked
Further inputs are a table ("Data") with first two columns "Open" and "Close", which are dateserial cells.
Next column is standard numeric value "Gross hours" =(Data[[#This Row],[Close]]-Data[[#This Row],[Open]])*24
Next column is standard numeric value "Net workdays" =NETWORKDAYS(Data[[#This Row],[Open]],Data[[#This Row],[Close]])
Next column is standard numeric value "Net days" =MAX(1,DAY(Data[[#This Row],[Close]])-DAY(Data[[#This Row],[Open]]))
Next column is standard numeric value "Gross workhours" =IF(Data[[#This Row],[Gross hours]]>0,Data[[#This Row],[Gross hours]]-24*(Data[[#This Row],[Net days]]-Data[[#This Row],[Net workdays]]),0)
Last column is standard numeric value "Total work hours" =IF(Data[[#This Row],[Gross workhours]]<24,Data[[#This Row],[Gross workhours]],Data[[#This Row],[Gross workhours]]-(HoursNotWorked*Data[[#This Row],[Net workdays]]+HoursWorked))
This solution makes it trivial to adjust start and end work times, as well as accounting for any holidays (via a small change to the NETWORKDAYS() function to utilise the optional parameter).


text:
Q: Pass input to CNN iteratively, one image array at a time Is there any possible way to pass the input to a CNN one array at a time rather than making an array of all the arrays?
From all the online examples and tutorials, the CNN input is given as:
X.append(np.array(cv2.resize(cv2.imread(list_of_images+'/'+image), (224,224), interpolation=cv2.INTER_CUBIC)))

where x is a 4-d array containing all 3d arrays, which is then fed to the model as:
model.fit(X, Y, batch_size=128, epochs=25)

Is there a way to pass the array iteratively, for a large dataset as python has an upper limit to the numpy array size.

A: I found the solution for my query from the link:
https://www.kaggle.com/rejpalcz/cnn-128x128x4-keras-from-scratch-lb-0-328
Look at the class: 'ProteinDataGenerator'


text:
Q: Mongoid Criteria: How to count number of documents that have a field with specific value Criteria is as follows:
#<Mongoid::Criteria
  selector: {"_id"=>{"$in"=>["535988c59bb8f9128c000001",
                             "53598a439bb8f9f211000001",
                             "536a9300ae4da1b0a9000002"]}}
  options:  {:limit=>5}
  class:    User
  embedded: false>

I want to traverse these users and get a count of how many have attribute is_active: true.
I'm thinking there has to be another way rather than doing users.each do |user| and keep a running count of whether the user met that criteria. Any suggestions?

A: If you have that criteria in a variable:
query = User.where(:id.in => ids).limit(5)

then you can add another condition by calling where:
query = query.where(:is_active => true)

and then count them:
n = query.count


text:
Q: R occurrences of word in Character list I have a character list filled with years
: chr "2010"
: chr "2011"
: chr "2010"
: chr "2012"

and I want the occurences of each year, so for the above I would have
"2010", 2
"2011", 1
"2012", 1

Like what I would expect to get from the table command. How can I get counts of each word in my character list?

A: Try
 table(unlist(lst))
 #  2010 2011 2012
 #  1    1    1

Or count from plyr
 library(plyr)
 count(unlist(lst))
 #     x freq
 #1 2010    1
 #2 2011    1
 #3 2012    1

data
 lst <- list("2010", "2012", "2011")


text:
Q: Image preprocessing before sending it to Tesseract OCR I'm cropping a part of an image using cropper.js and then trying to extract the text from it using Tesseract js. My issue is that in some cases it does not recognizes simple text, samples below.
sample-1
sample-2
I also did some tests on Amazon Textract with the same samples and still got the same problems, so my gues is there is something wrong with the cropped images. Does anyone have any experience with preprocessing images before OCR, this also needs to happen with the help of JS

A: Have you tried to isolate just the words? Removing borders or any other kind of noise can improve OCR performance.
The following javascript snippet segments just the letters.
Result:

Snippet:

// Canvas and Images
var canvas1 = document.getElementById("canvas_1");
var canvas2 = document.getElementById("canvas_2");

// Load Road image
var imageRoad = new MarvinImage();
imageRoad.load("https://i.imgur.com/9cuE5AR.png", imageRoadLoaded);

// Load Passport image
var imagePassport = new MarvinImage();
imagePassport.load("https://i.imgur.com/cl637On.png", imagePassportLoaded);

// Find Text regions in the road image
function imageRoadLoaded(){
    var segments = Marvin.findTextRegions(imageRoad, 40, 40, 50, 190);
    drawSegments(segments, imageRoad);
    imageRoad.draw(canvas1);
}

// Find Text regions in the passport image
function imagePassportLoaded(){
    var segments = Marvin.findTextRegions(imagePassport, 40, 40, 50, 190);
    drawSegments(segments, imagePassport);
    imagePassport.draw(canvas2);
}

function drawSegments(segments, image){
    for(var i in segments){
        var seg = segments[i];
    // Skip segments that are too small
        if(seg.height >= 5){
            image.drawRect(seg.x1, seg.y1-5, seg.width, seg.height+10, 0xFFFF0000);
            image.drawRect(seg.x1+1, seg.y1-4, seg.width-2, seg.height+8, 0xFFFF0000);
        }
    }
}
body{font-size:12px;}
by www.marvinj.org

    <canvas id="canvas_1" width="500" height="300"></canvas>

  <canvas id="canvas_2" width="601" height="400"></canvas>


text:
Q: Read a provider inside a FutureProvider When we need to read (not watch) a provider inside another one the documentation is clear:
"DON'T CALL READ INSIDE THE BODY OF A PROVIDER"
final myProvider = Provider((ref) {
  // Bad practice to call `read` here
  final value = ref.read(anotherProvider);
});

And it suggest to pass to the value exposed the Reader function: https://riverpod.dev/docs/concepts/combining_providers#can-i-read-a-provider-without-listening-to-it
final userTokenProvider = StateProvider<String>((ref) => null);

final repositoryProvider = Provider((ref) => Repository(ref.read));

class Repository {
  Repository(this.read);

  /// The `ref.read` function
  final Reader read;

  Future<Catalog> fetchCatalog() async {
    String token = read(userTokenProvider);

    final response = await dio.get('/path', queryParameters: {
      'token': token,
    });

    return Catalog.fromJson(response.data);
  }
}

And that's ok, but what is the best practice when I need to read a provider inside a FutureProvider?
I find myself in this situation many time because I expose the api as providers and inside the FutureProvider I call watch to get the api I need.
But I noticed that, because I'm watching the Api provider inside the userProvider, this won't gets disposed after been used.
Here's an example of what I'm trying to say:
API CLASS
final userApiProvider = Provider((ref) => UserApi(ref.read));
class UserApi {

  final Dio _dio;

 const UserApi(Reader read):
   _dio = read(dioProvider);

  Future<Response> getUser(String id, { CancelToken? cancelToken }) async{
    final _url = '$URL_TO_API/$id';
    return _dio.get(_url, cancelToken: cancelToken);
  }

}

When using the API inside a FutureProvider
final userProvider = FutureProvider.autoDispose.family<User, int>((ref, userId) async {
  final userApi = **ref.watch(userApi);**
  final cancelToken = CancelToken();
  ref.onDispose(() { cancelToken.cancel(); });

  final user = await userApi.getUser(cancelToken: cancelToken);
  return user;
});

A: The same logic applies.
By "Don't use read inside a provider", it isn't talking about the class Provider specifically, but any provider – so FutureProvider included.
In general, you should avoid using read as much as possible.


text:
Q: Boost Test entry/exit fixture with manual registration I am using Boost 1.61 and I am working with the following type of Boost Test setup where I am manually registering tests:
// testsuite.cpp
#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;

test_suite* init_unit_test_suite(int, char* []) {
    test_suite* test = BOOST_TEST_SUITE("TestSuiteName");
    test->add(FooTest::suite());
    return test;
}

// foo.hpp
#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;

class FooTest {
public:
    static void testFoo1();
    static void testFoo2();
    static test_suite* suite();
}

// foo.cpp
#include <foo.hpp>

void FooTest::testFoo1() {
    // testFoo1 implementation
}
void FooTest::testFoo2() {
    // testFoo2 implementation
}

test_suite* FooTest::suite() {
    test_suite* suite = BOOST_TEST_SUITE("FooTest");
    suite->add(BOOST_TEST_CASE(&FooTest::testFoo1));
    suite->add(BOOST_TEST_CASE(&FooTest::testFoo2));
    return suite;
}

I would like to add an entry/exit fixture, as described here, to the FooTest test suite. The Boost Test documentation describes this feature in the context of automatically registered tests.
Can I use this entry/exit fixture feature with my setup where I am manually registering tests? If not, does anyone have a suggestion as to how I could mimic this behavior i.e. have an object constructed once on entry in to the FooTest test suite, available to all tests in the test suite and then destructed on exit from the FooTest suite?
A similar question was asked here but I could not find an answer that I could use.

A: Just in case it is useful to someone, from looking in some of the Boost Test source files, I came up with the following that seems to meet my requirements i.e. using an entry/exit fixture with manual registration.
// testsuite.cpp
#include "foo.hpp"

#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;

test_suite* init_unit_test_suite(int, char*[]) {
    test_suite* test = BOOST_TEST_SUITE("TestSuiteName");
    test->add(FooTest::suite());
    return test;
}

// bar.hpp (The class to be tested)
class Bar {
public:
    Bar(int x, int y) : x_(x), y_(y) {}

    int x_;
    int y_;
};

// foo.hpp
#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;

class FooTest {
public:
    static void testFoo1();
    static void testFoo2();
    static test_suite* suite();
};

// foo.cpp
#include "foo.hpp"
#include "bar.hpp"

#include <boost/make_shared.hpp>

#include <vector>

using boost::unit_test::test_unit_fixture_ptr;
using std::vector;

namespace {
boost::shared_ptr<Bar> bar;

void setup() {
    BOOST_TEST_MESSAGE("Creating Bar Instance");
    bar = boost::make_shared<Bar>(1, 2);
}

void teardown() {
    BOOST_TEST_MESSAGE("Destroying Bar Instance");
    bar.reset();
}
}

void FooTest::testFoo1() {
    BOOST_TEST_MESSAGE("In testFoo1");
    BOOST_CHECK_MESSAGE(bar->x_ == 1, "Checking x_");
}
void FooTest::testFoo2() {
    BOOST_TEST_MESSAGE("In testFoo2");
    BOOST_CHECK_MESSAGE(bar->y_ == 2, "Checking y_");
}

test_suite* FooTest::suite() {
    test_suite* suite = BOOST_TEST_SUITE("FooTest");

    // Manually add an entry/exit fixture to the test suite
    vector<test_unit_fixture_ptr> fixtures {
        boost::make_shared<boost::unit_test::function_based_fixture>(setup, teardown)};
    suite->p_fixtures.set(fixtures);

    suite->add(BOOST_TEST_CASE(&FooTest::testFoo1));
    suite->add(BOOST_TEST_CASE(&FooTest::testFoo2));
    return suite;
}

This code gives the following output when run with log_level=message
 Running 2 test cases...
 Creating Bar Instance
 In testFoo1
 In testFoo2
 Destroying Bar Instance

 *** No errors detected

Let me know if you think there are flaws with this approach or if you feel there is a better method for achieving what I want.


text:
Q: Pipeline pow operator issue with i want to write the next function using pipeline:
A = 1/Sum[1-k](x^2)

so when i write:
//Adaptive step
let a_Adaptive x =
    x
    |> Array.map (fun x -> x ** 2.0)
    |> Array.sum
    |> (**) -1.0

f# interpretes (**) as a multiline comment, but i want use it as a function.
Any suggestions?

A: You just need to add a space before the **:
let a_Adaptive x =
    x
    |> Array.map (fun x -> x ** 2.0)
    |> Array.sum
    |> ( ** ) -1.0

From the F# specification:

To define other operators that begin with *, whitespace must follow
  the opening parenthesis; otherwise (* is interpreted as the start of a
  comment:
let ( *+* ) x y = (x + y)


text:
Q: Sinatra post redirect get, always forward to the get with the same name with post Here is my code:
post '/pathA' do
  redirect '/pathB'
end

get '/pathB' do
  do something
end

get '/pathA' do
  do something
end

First, if I didn't specify a redirect in postA, it will redirect to getA, I don't understand this already; Now, I want to redirect to getB, the result looks like this:
127.0.0.1  "POST /pathA HTTP/1.1" 303 - 0.0330
127.0.0.1  "GET /pathB HTTP/1.1" 200 15877 0.0229
127.0.0.1  "GET /pathA HTTP/1.1" 200 26017 0.0281
127.0.0.1  "GET /css/reset.css HTTP/1.1" 304 - 0.0020
......(some more resources)

the code in getB won't be executed. The getA page is showing. How would this happen? How can I redirect to getB?
I think the problem is I'm using ajax to send post request.

A: Two ways to solve this problem:

*

*Change postA to return a notifier but not a redirect, and redirect from ajax code according to the notifier.

*Post from a form.

A: If you're using reload function after ajax returns success, obviously you will have the same path where you execute your ajax.
It's either you POST to a new  path/url after ajax returns success, or redirect it:
Sample Pseudocode:
$('#my_form').submit( function(event){      //or

$('#btn_submit').click( function(event){
  event.preventDefault();

  $.ajax({
    url: 'http://my_path',
    type: 'POST', #GET
    data:  $('#my_form').serialize(),
    success: function(data){
      // redirect_to_new_path
    }
  });
});

Change the code the way you want function to execute.


text:
Q: Deleting a node in a Binary Search Tree(BST) is causing seg faults I'm having trouble with removing a node from my BST and I can't seem to find the culprit to my seg faults. Every other part of my BST I've tested and it runs smoothly. I've also tried deleting nodes with different conditions but it's all the same result.
template <typename object>
bool BST<object>::remove(object& data)
{
    if (nodes == 0)
    {
        return false;
    }
    else
    {
        return remove(root_, data);
    }
}

template <typename object>
bool BST<object>::remove(node<object>* current_node_, object& data)
{
    if (current_node_ == NULL)
    {
        return false;
    }

    int relation = compare(data, current_node_->get_data());

    //if you need to keep searching right
    if (relation > 0)
    {
        remove(current_node_->get_right(), data);
    }
    else if (relation < 0)
    {
        remove(current_node_->get_left(), data);
    }
    else
    {
        //LEAF CASE
        if (current_node_->is_leaf())
        {
            //root case
            if (compare(root_->get_data(), data) == 0)
            {
                root_ = NULL;
            }

            else
            {
                if (current_node_->is_right_child())
                {
                    current_node_->get_parent()->set_right(NULL);
                }
                else
                {
                    current_node_->get_parent()->set_left(NULL);
                }
            }

            //release from memory
            delete current_node_;
            nodes--;
        }
        //ONE CHILD CASE
        else if (current_node_->has_one_child())
        {
            //root node
            if (compare(root_->get_data(), data) == 0)
            {
                if (current_node_->get_right() != NULL)
                {
                    current_node_->get_right()->set_parent(NULL);
                    root_ = current_node_->get_right();
                }
                else
                {
                    current_node_->get_left()->set_parent(NULL);
                    root_ = current_node_->get_left();
                }
            }

            //node with right child
            else if(current_node_->get_right() != NULL)
            {
                current_node_->get_right()->set_parent(current_node_->get_parent());
                if (current_node_->is_right_child())
                {
                    current_node_->get_parent()->set_right(current_node_->get_right());
                }
                else
                {
                    current_node_->get_parent()->set_left(current_node_->get_right());
                }
            }
            //node with left child
            else
            {
                current_node_->get_left()->set_parent(current_node_->get_parent());
                if (current_node_->is_right_child())
                {
                    current_node_->get_parent()->set_right(current_node_->get_left());
                }
                else
                {
                    current_node_->get_parent()->set_left(current_node_->get_left());
                }
            }

            //release from memory
            delete current_node_;
            nodes--;
        }
        //TWO CHILDREN CASE
        else
        {
            node<object>* temp_node_ = find_min(current_node_->get_right());
            object* temp_object_ = new object(temp_node_->get_data());

            remove(temp_node_, temp_node_->get_data());
            current_node_->set_data(*temp_object_);
        }
        return true;
    }
    return false;
}

template <typename object>
node<object>* BST<object>::find_min(node<object>* current_node_)
{
    if(current_node_->get_left() != NULL)
    {
        find_min(current_node_->get_left());
    }
    else
    {
        return current_node_;
    }
}

A: Write
current_node_=NULL;

After each line
delete current_node_;

in remove function. Let me inform if its work.


text:
Q: Callback parameters using lambda I started Python(2.7.3) two days ago and I need to use parameters in my GUI callbacks functions. I've been looking for any information here and on effbot, but I cant find out what is wrong in my case.
from Tkinter import *
fenetre = Tk()
var_texte = StringVar()
ligne_texte = Entry(fenetre, textvariable=var_texte ,width=30)

def callback(s):
    print("we got there with :"+s)

trace_name = var_texte.trace_variable("w",lambda: callback(ligne_texte.get()))
ligne_texte.pack()
fenetre.mainloop()

I tried to use lambda to get my param passed but i get this error when I type text into the Entry:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
TypeError: <lambda>() takes no arguments (3 given)

I found a post here which proposed to replace lambda: with lambda x:, but I get another error with TypeError: <lambda>() takes exactly 1 argument (3 given)
Any explanation or source or information would be very appreciated :)

A: As the error message says, StringVar.trace_variable is called with three argument by the framework. So your lambda function should accept those three argument:
lambda name, idx, mode: ...

From http://staff.washington.edu/rowen/ROTKFolklore.html here is the description of the arguments:

*

*The name of the Tk variable. This is not the Tk variable object itself, but you can use the name to get or set the value via root.globalgetvar(name) and root.globalsetvar(name). Unfortunately, I have not found any way to obtain the actual Tk variable object from its name; root.nametowidget(varName) does not seem to work for Tk variables.

*The variable index, if the Tk variable is an array, else an empty string. I have no idea how to create a Tk variable array in Tkinter (but it is easy in Tk). If you figure it out, you can then determine if the index is a string representation of an integer, or an integer (my guess is it's a string).

*The access mode, one of "w", "r" or "u".

A: If you are not interested in the parameters being passed to the callback, you can use:
lambda *args: callback(ligne_texte.get())

The documentation for the so-called "splat" operator (*) can be found here.


text:
Q: Array compare with for each performance issue I have two arrays with array of objects as follows and one array will have more than 10k records and other have below 100 records
let bigArray = [{id:1, name:"Raj", level:0}, {id:2, name:"sushama", level:2}, {id:3, name:"Sushant", level:0}, {id:4, name:"Bhaskar", level:2},....upto 30k records]

let smallArray = [{id:2, name:"sushama"}, {id:3, name:"Sushant"}....upto 100 records]

I want to find where in the index of bigArray in which the object from smallArray resides and add to another array say indexArray I tried below
let indexArray = [];
bigArray.forEach((element, i) => {
  smallArray.forEach(ele => {
    if (element.name == ele.name && element.id == ele.id) {
      indexArray.push(i); return;
    }
  });
});

But it takes time. What would be the fastest approach?

A: You can turn your O(N^2) approach into an O(N) approach by reducing the bigArray into an object indexed by a key made up from the name and id. Join the name and id by a character that isn't contained in either, such as _:
const indexArray = [];
const bigArrayIndiciesByNameAndId = bigArray.reduce((a, { name, id }, i) => {
  a[name + '_' + id] = i;
  return a;
}, {});

smallArray.forEach(ele => {
  const keyToFind = ele.name + '_' + ele.id;
  const foundIndex = bigArrayIndiciesByNameAndId[keyToFind];
  if (foundIndex) {
    indexArray.push(foundIndex);
  }
});

A: You could take a Map and map the found indices.

const getKey = ({ id, name }) => [id, name].join('|');

let bigArray = [{ id: 1, name: "Raj", level: 0 }, { id: 2, name: "sushama", level: 2 }, { id: 3, name: "Sushant", level: 0 }, { id: 4, name: "Bhaskar", level: 2 }],
    smallArray = [{ id: 2, name: "sushama" }, { id: 3, name: "Sushant" }],
    map = new Map(bigArray.map((o, i) => [getKey(o), i]))
    indexArray = smallArray.map((o) => map.get(getKey(o)));

console.log(indexArray);

A: return will not "break" the forEach loop. A forEach can't be stopped. The forEach callback function will be called one time per items always. When you find the element, continue running the forEach loop is a waste of resouces.
You should use for instead:
let indexArray = [];
bigArray.forEach((element, i) => {
    for (var ii = 0; ii < smallArray.length; ii++) {
        var ele = smallArray[ii];
        if (element.name == ele.name && element.id == ele.id) {
            indexArray.push(i);
            break; // This will break the "for" loop as we found the item
        }
    }
});

TIP: Always have a good indentation in your code. Actually your code is really bad indented to identify code blocks at first sight. I fixed it in this example.


text:
Q: Linux Grep Command - Extract multiple texts between strings Context;
After running the following command on my server:

zgrep "ResCode-5005" /loggers1/PCRF*/_01_03_2022 > analisis.txt

I get a text file with thousands of lines like this example:

loggers1/PCRF1_17868/PCRF12_01_03_2022_00_15_39.log:[C]|01-03-2022:00:18:20:183401|140404464875264|TRACKING: CCR processing Compleated for SubId-5281181XXXXX, REQNO-1, REQTYPE-3,
SId-mscp01.herpgwXX.epc.mncXXX.mccXXX.XXXXX.org;25b8510c;621dbaab;3341100102036XX-27cf0XXX,
RATTYPE-1004, ResCode-5005 |processCCR|ProcessingUnit.cpp|423

(X represents incrementing numbers)
Problem:
The output is filled with unnecessary data. The only string portions I need are the MSISDN,IMSI comma separated for each line, like this:
5281181XXXXX,3341100102036XX
Steps I tried

zgrep "ResCode-5005" /loggers1/PCRF*/_01_03_2022| grep -o -P
'(?<=SubId-).*?(?=, REQ)' > analisis1.txt

This gave me the first part of the solution

5281181XXXXX

However, when I tried to get the second string located between '334110' and "-"

zgrep "ResCode-5005" /loggers1/PCRF*/_01_03_2022| grep -o -P
'(?<=SubId-).?(?=, REQ)' | grep -o -P '(?<=334110).?(?=-)' >
analisis1.txt

it doesn't work.
Any input will be appreciated.

A: To get 5281181XXXXX or the second string located between '334110' and "-" you can use a pattern like:
\b(?:SubId-|334110)\K[^,\s-]+

The pattern matches:

*

*\b A word boundary to prevent a partial word match

*(?: Non capture group to match as a whole

*

*SubId- Match literally

*| Or

*334110 Match literally

*) Close the non capture group

*\K Forget what is matched so far

*[^,\s-]+ Match 1+ occurrences of any char except a whitespace char , or -
See the matches in this regex demo.
That will match:
5281181XXXXX
0102036XX

The command could look like
zgrep "ResCode-5005" /loggers1/PCRF*/_01_03_2022 | grep -oP '\b(?:SubId-|334110)\K[^,\s-]+' > analisis1.txt


text:
Q: Ограничение полей, получаемых от MongoDB, в соответствии с GraphQL запросом Используемые модули:
apollo-server-express@3.6.2
express@4.17.2
mongoose@6.2.0

Модель коллекции Category предусматривает несколько полей:
name, decription, itemsInCategory
Клиент через GraphQL запрашивает данные:
query {
    item {
        category {
            description
        }
    }
}

Нет никакого смысла делать выборку всех полей из базы данных на такой запрос, поэтому ограничиваю выборку следующим образом:
/graphQL/resolvers/category.js
module.exports = {
    category: async (parent, args, { models, fieldsFilter }, gqlModel ) => {
        return await models.Categories.findById( parent.category, fieldsFilter(gqlModel) );
    },
};

index.js
const fieldsFilter = function( gqlModel ) {
    let res = [];
    gqlModel.fieldNodes.forEach( fNode => {
        res = res.concat( fNode.selectionSet.selections.map( el=>el.name.value ) );
    } );
    return res;
};
const server = new ApolloServer( {
    typeDefs,
    resolvers,
    context: ()=> {
        return { models, fieldsFilter }
    }
} );

Всё работает как и хочется - от базы данных запрашиваются только те поля, которые нужно будет вернуть клиенту, ничего лишнего.
Вот только не покидает чувство, что это велосипед (функция fieldsFilter).
Есть ли готовые решения?


text:
Q: How to unisolate an particular input inside an isolate() function in R shiny dashboard I'am on the process of building a shiny dashboard about the electoral behavior,
I have 3 widgets: Gender, Region and Political parti, the user can choose a gender or/and a region or/and political parti and the dashborad will show a plot based on the input chosen, and I put a radio buttom inside the box of the plot that allows to the user to choose the type of the stacked bar chart: position="stack" or "fill", I add an actionbuttom and the isolate() function so that all the inputs on the page do not send updates to the server until the button is pressed. However I want the radio buttom that indicate the type of the stacked bar chart not to be isolated: this is the code R that i used:
Data frame
       pff <- read.table(header=TRUE, text='
                 REGION Q99 Q101
              Tunis  Nahdha Femme
              Tunis Jabha Femme
              Tunis  NidaaTounes Homme
              Tunis  Nepasvoter Femme
              Tunis  Nepasvoter Homme
              Tunis  Nepasvoter Femme
              Tunis  NidaaTounes Homme
              Tunis  Nepasvoter Homme
              Tunis        Nahdha Femme
              Tunis  NidaaTounes Femme
              Tunis           CPR Femme
              Tunis        Nahdha Femme
              Tunis        Autres Homme
              Tunis  Nepasvoter Homme
              Tunis  Nepasvoter Femme
              Tunis        Nahdha Homme
              Tunis Jabha Homme
              Tunis  Nepasvoter Femme
              Tunis        Nahdha Homme
              Tunis        Nahdha Femme
              Tunis JabhaChaabia Homme
              Tunis        Autres Femme
              Tunis  Nepasvoter Femme
              Tunis  NidaaTounes Femme
              Tunis  Nepasvoter Homme
              Tunis  NidaaTounes Femme
              Tunis  Nepasvoter Homme
              Tunis  NidaaTounes Homme
              Tunis Jabha Femme
              Tunis  NidaaTounes Homme
              Tunis        Autres Homme
              Tunis        Nahdha Femme
              Tunis        Nahdha Homme
              Tunis        Autres Femme
              Tunis Jabha Homme
              Tunis  Nepasvoter Femme
              Tunis  Nepasvoter Homme
              Tunis           CPR Femme
              Tunis        Nahdha Homme
              Tunis  Nepasvoter Femme
              Tunis  Nepasvoter Homme
              Tunis  Nepasvoter Femme
              Tunis        Nahdha Homme
              Tunis  NidaaTounes Femme
              Tunis           CPR Homme
              Tunis           CPR Femme
              Tunis  Nepasvoter Homme
              Tunis        Autres Homme
              Tunis        Nahdha Homme
              Tunis  NidaaTounes Homme
              Tunis        Nahdha Femme
              Tunis        Autres Femme
              Tunis  Nepasvoter Femme
              Ariana        Nahdha Femme
              Ariana           CPR Femme
              Ariana        Nahdha Femme
              Ariana  Nepasvoter Homme
              Ariana  NidaaTounes Homme
              Ariana           CPR Homme
              Ariana  Nepasvoter Homme
              Ariana        Nahdha Homme
              Ariana  Nepasvoter Femme
              Ariana  NidaaTounes Homme
              Ariana           CPR Homme
              Ariana  NidaaTounes Homme
              Ariana  NidaaTounes Homme
              Ariana  NidaaTounes Homme
              Ariana           CPR Femme
              Ariana        Nahdha Femme
              Ariana           CPR Femme
              Ariana        Nahdha Homme
              Ariana        Nahdha Homme
              Ariana           CPR Homme
              Ariana        Nahdha Homme
              Ariana  Nepasvoter Homme
              Ariana  NidaaTounes Homme
              Ariana  NidaaTounes Homme
              Ariana        Nahdha Homme    ')

server
     library(shiny)
     library(ggplot2)
     library(ggalt)
     library(dplyr)
     library(foreign)
     library(plotly)
     library(scales)

     shinyServer(function(input, output) {
     dataa<-reactive({
     within(as.data.frame(pff),
       Q99 <- factor(Q99,
                     levels=names(sort(table(Q99),
                                       decreasing=FALSE))))})
     partii2=reactive({
     filter(dataa(), Q99 %in% input$parti, REGION %in% input$region)
})
     output$plot1=renderPlotly({
     input$action
     isolate(
        if(!is.null(input$parti) && !is.null(input$region) && input$genre=="Tous"){
        if((length(input$region))==1)
         {
           g <- ggplot(partii2(), aes(x = Q99, y =(..count..)/sum(..count..)))
           g <- g + geom_bar(fill="#0f00ee") + labs(title=paste("Vote dans la région de", input$region,"pour",input$parti,sep = " ")) +labs(x="Parti politique", y="")+coord_flip()+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))
           }
      else{
        g <- ggplot(dataa(), aes(x = REGION, y =(..count..)/1200, fill=Q99))
        g <- g + geom_bar(position=input$position) + labs(title="vote") +labs(x=" ", y=" ")+labs(fill="Parti Politique")+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))  +coord_flip() + geom_text(aes( label = scales::percent(round((..count..)/1200,3 )),y=(..count..)/1200 ),stat= "count", size=4, position = "stack")

         }
        }
       )
     })
   })

Ui
  library(shiny)
  library(shinydashboard)
  library(foreign)
  library(plotly)

  shinyUI(dashboardPage(skin = "blue",
                  dashboardHeader(title = h4("Élections",style = "color:white"),

                                  titleWidth = 300
                  ),
                  dashboardSidebar(id="",
                                   tags$head(
                                     tags$script(
                                       HTML(
                                         "
                                         $(document).ready(function(){
                                         // Bind classes to menu items, easiet to fill in manually
                                         var ids = ['Enquête','dashboard','Prédiction','Données','Échantillon'];
                                         for(i=0; i<ids.length; i++){
                                         $('a[data-value='+ids[i]+']').addClass('my_subitem_class');
                                         }

                                         // Register click handeler
                                         $('.my_subitem_class').on('click',function(){
                                         // Unactive menuSubItems
                                         $('.my_subitem_class').parent().removeClass('active');
                                         })
                                         })
                                         "
                                       )
                                     )),
                                   sidebarMenu(
                                     menuItem(h4(strong("Enquête")), tabName = "Enquête",
                                              menuSubItem("Données",tabName = "Données"),
                                              menuSubItem("Échantillon",tabName = "Échantillon")),
                                     menuItem(h4(strong("Dashboard")), tabName = "dashboard"),
                                     menuItem(h4(strong("Prédiction")), tabName = "Prédiction"))

                                     ),

                  dashboardBody(
                    tabItems(
                      tabItem(tabName = "dashboard",h2("Le comportement électoral des citoyens tunisiens", align="center",style = "color:blue"),

                              fluidRow(
                                tiltle="filtre",
                                column(width=4,
                                       box(
                                         title = "Filtre",
                                         status = "primary",
                                         width = 8,
                                         solidHeader = TRUE,
                                         background="navy",
                                         box(

                                           solidHeader = FALSE,
                                           width = 8,
                                           background = "navy" ,
                                           radioButtons("genre", "Genre", c("Homme","Femme","Tous"),"Tous")

                                         ),

                                         box(
                                           solidHeader = FALSE,
                                           width = 12,
                                           background = "navy",
                                           selectizeInput("region", label = "Région",
                                                          choices = levels(pff$REGION),
                                                          selected = "Ariana", multiple=TRUE)

                                         ),

                                         box(
                                           solidHeader = FALSE,
                                           width = 12,
                                           background = "navy",
                                           selectizeInput("parti", label = "Parti politique",
                                                          choices = levels(pff$Q99),
                                                          selected = "CPR", multiple=TRUE)

                                         ),
                                         box(
                                           actionButton("action","Mettre à jour!"),
                                           #submitButton("Mettre à jour!",icon("refresh")),
                                           background = "navy"

                                         )

                                       )

                                ),

                                box(
                                  solidHeader = FALSE ,width = 8,height = 500,
                                  collapsible = TRUE,align="center",
                                  radioButtons("position", "", c("fill","stack"), selected = "fill", inline = TRUE, width = NULL),
                                  plotlyOutput('plot1', height = 400,width = "100%")

                                )

                              )# end of fluidrow

                      )

                         ))))

A: Does this help you? I changed the server side a little, according to this question here: Convert ggplot object to plotly in shiny application
Also, each time a relevant user interaction takes place, the input are being shown in the console by the server.
observeEvent(c(input$action,input$position), {
    output$plot1<-renderPlotly({
      getGgplot <- function(inputObj){
        g <- ggplot(data.frame())
        if(!is.null(inputObj$parti) && !is.null(inputObj$region) && inputObj$genre=="Tous"){
          # generate proper ggplot
          if((length(inputObj$region))==1)
          {
            g <- ggplot(inputObj$partii2, aes(x = Q99, y =(..count..)/sum(..count..)))
            g <- g + geom_bar(fill="#0f00ee") + labs(title=paste("Vote dans la région de", inputObj$region,"pour",inputObj$parti,sep = " ")) +labs(x="Parti politique", y="")+coord_flip()+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))
          }
          else{
            g <- ggplot(inputObj$dataa, aes(x = REGION, y =(..count..)/1200, fill=Q99))
            g <- g + geom_bar(inputObj$position) + labs(title="vote") +labs(x=" ", y=" ")+labs(fill="Parti Politique")+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))  +coord_flip() + geom_text(aes( label = scales::percent(round((..count..)/1200,3 )),y=(..count..)/1200 ),stat= "count", size=4, position = inputObj$position)
          }
        }
        return (
          g
        )
      }
      inputs <- list(
        "parti" = isolate( input$parti ),
        "region" = isolate( input$region ),
        "genre" = isolate( input$genre ),
        "position" = input$position,
        "dataa" = dataa(),
        "partii2" = partii2(
          partiArg = isolate( input$parti ),
          regionArg = isolate( input$region )
                            )
      )
      print("inputs:")
      print(str(inputs))
      g <- getGgplot(inputs)

      # return ggplot to ggplotly
      print(
        ggplotly(g)
      )
    })
  })

There seem to be some other issues with your code also, but I was not really able to figure out what the problem is. I.e., I received the following warning when situation "Genre = Tous, Region = Ariana and Parti politique = CPR, JabhaChaabia":
Warning in if (nchar(p$labels$title %||% "") > 0) { :
the condition has length > 1 and only the first element will be used

So here is my comprehensive code, what do you say?
library(shiny)
library(shinydashboard)
library(ggplot2)
library(ggalt)
library(dplyr)
library(foreign)
library(plotly)
library(scales)

pff <- read.table(header=TRUE, text='
                 REGION Q99 Q101
                  Tunis  Nahdha Femme
                  Tunis Jabha Femme
                  Tunis  NidaaTounes Homme
                  Tunis  Nepasvoter Femme
                  Tunis  Nepasvoter Homme
                  Tunis  Nepasvoter Femme
                  Tunis  NidaaTounes Homme
                  Tunis  Nepasvoter Homme
                  Tunis        Nahdha Femme
                  Tunis  NidaaTounes Femme
                  Tunis           CPR Femme
                  Tunis        Nahdha Femme
                  Tunis        Autres Homme
                  Tunis  Nepasvoter Homme
                  Tunis  Nepasvoter Femme
                  Tunis        Nahdha Homme
                  Tunis Jabha Homme
                  Tunis  Nepasvoter Femme
                  Tunis        Nahdha Homme
                  Tunis        Nahdha Femme
                  Tunis JabhaChaabia Homme
                  Tunis        Autres Femme
                  Tunis  Nepasvoter Femme
                  Tunis  NidaaTounes Femme
                  Tunis  Nepasvoter Homme
                  Tunis  NidaaTounes Femme
                  Tunis  Nepasvoter Homme
                  Tunis  NidaaTounes Homme
                  Tunis Jabha Femme
                  Tunis  NidaaTounes Homme
                  Tunis        Autres Homme
                  Tunis        Nahdha Femme
                  Tunis        Nahdha Homme
                  Tunis        Autres Femme
                  Tunis Jabha Homme
                  Tunis  Nepasvoter Femme
                  Tunis  Nepasvoter Homme
                  Tunis           CPR Femme
                  Tunis        Nahdha Homme
                  Tunis  Nepasvoter Femme
                  Tunis  Nepasvoter Homme
                  Tunis  Nepasvoter Femme
                  Tunis        Nahdha Homme
                  Tunis  NidaaTounes Femme
                  Tunis           CPR Homme
                  Tunis           CPR Femme
                  Tunis  Nepasvoter Homme
                  Tunis        Autres Homme
                  Tunis        Nahdha Homme
                  Tunis  NidaaTounes Homme
                  Tunis        Nahdha Femme
                  Tunis        Autres Femme
                  Tunis  Nepasvoter Femme
                  Ariana        Nahdha Femme
                  Ariana           CPR Femme
                  Ariana        Nahdha Femme
                  Ariana  Nepasvoter Homme
                  Ariana  NidaaTounes Homme
                  Ariana           CPR Homme
                  Ariana  Nepasvoter Homme
                  Ariana        Nahdha Homme
                  Ariana  Nepasvoter Femme
                  Ariana  NidaaTounes Homme
                  Ariana           CPR Homme
                  Ariana  NidaaTounes Homme
                  Ariana  NidaaTounes Homme
                  Ariana  NidaaTounes Homme
                  Ariana           CPR Femme
                  Ariana        Nahdha Femme
                  Ariana           CPR Femme
                  Ariana        Nahdha Homme
                  Ariana        Nahdha Homme
                  Ariana           CPR Homme
                  Ariana        Nahdha Homme
                  Ariana  Nepasvoter Homme
                  Ariana  NidaaTounes Homme
                  Ariana  NidaaTounes Homme
                  Ariana        Nahdha Homme    ')

dataa<-function(){
  return (
    within(as.data.frame(pff),
           Q99 <- factor(Q99,
                         levels=names(sort(table(Q99),
                                           decreasing=FALSE)))
    )
  )
}

partii2<-function(partiArg,regionArg){
  return(
    filter(dataa(), Q99 %in% partiArg, REGION %in% regionArg)
         )
}

server <- shinyServer(function(input, output) {
  observeEvent(c(input$action,input$position), {
    output$plot1<-renderPlotly({
      getGgplot <- function(inputObj){
        g <- ggplot(data.frame())
        if(!is.null(inputObj$parti) && !is.null(inputObj$region) && inputObj$genre=="Tous"){
          # generate proper ggplot
          if((length(inputObj$region))==1)
          {
            g <- ggplot(inputObj$partii2, aes(x = Q99, y =(..count..)/sum(..count..)))
            g <- g + geom_bar(fill="#0f00ee") + labs(title=paste("Vote dans la région de", inputObj$region,"pour",inputObj$parti,sep = " ")) +labs(x="Parti politique", y="")+coord_flip()+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))
          }
          else{
            g <- ggplot(inputObj$dataa, aes(x = REGION, y =(..count..)/1200, fill=Q99))
            g <- g + geom_bar(inputObj$position) + labs(title="vote") +labs(x=" ", y=" ")+labs(fill="Parti Politique")+scale_y_continuous(labels = percent)+ theme_bw()+theme(panel.border = element_rect(colour = "white"))  +coord_flip() + geom_text(aes( label = scales::percent(round((..count..)/1200,3 )),y=(..count..)/1200 ),stat= "count", size=4, position = inputObj$position)
          }
        }
        return (
          g
        )
      }
      inputs <- list(
        "parti" = isolate( input$parti ),
        "region" = isolate( input$region ),
        "genre" = isolate( input$genre ),
        "position" = input$position,
        "dataa" = dataa(),
        "partii2" = partii2(
          partiArg = isolate( input$parti ),
          regionArg = isolate( input$region )
                            )
      )
      print("inputs:")
      print(str(inputs))
      g <- getGgplot(inputs)

      # return ggplot to ggplotly
      print(
        ggplotly(g)
      )
    })
  })
})
ui <- shinyUI(dashboardPage(skin = "blue",
                            dashboardHeader(title = h4("Élections",style = "color:white"),
                                            titleWidth = 300
                            ),
                            dashboardSidebar(id="",
                                             tags$head(
                                               tags$script(
                                                 HTML(
                                                   "
                                                   $(document).ready(function(){
                                                   // Bind classes to menu items, easiet to fill in manually
                                                   var ids = ['Enquête','dashboard','Prédiction','Données','Échantillon'];
                                                   for(i=0; i<ids.length; i++){
                                                   $('a[data-value='+ids[i]+']').addClass('my_subitem_class');
                                                   }
                                                   // Register click handeler
                                                   $('.my_subitem_class').on('click',function(){
                                                   // Unactive menuSubItems
                                                   $('.my_subitem_class').parent().removeClass('active');
                                                   })
                                                   })
                                                   "
                                                 )
                                               )),
                                             sidebarMenu(
                                               menuItem(h4(strong("Enquête")), tabName = "Enquête",
                                                        menuSubItem("Données",tabName = "Données"),
                                                        menuSubItem("Échantillon",tabName = "Échantillon")),
                                               menuItem(h4(strong("Dashboard")), tabName = "dashboard"),
                                               menuItem(h4(strong("Prédiction")), tabName = "Prédiction"))
                                               ),
                            dashboardBody(
                              tabItems(
                                tabItem(tabName = "dashboard",h2("Le comportement électoral des citoyens tunisiens", align="center",style = "color:blue"),
                                        fluidRow(
                                          tiltle="filtre",
                                          column(width=4,
                                                 box(
                                                   title = "Filtre",
                                                   status = "primary",
                                                   width = 8,
                                                   solidHeader = TRUE,
                                                   background="navy",
                                                   box(
                                                     solidHeader = FALSE,
                                                     width = 8,
                                                     background = "navy" ,
                                                     radioButtons("genre", "Genre", c("Homme","Femme","Tous"),"Tous")
                                                   ),
                                                   box(
                                                     solidHeader = FALSE,
                                                     width = 12,
                                                     background = "navy",
                                                     selectizeInput("region", label = "Région",
                                                                    choices = levels(pff$REGION),
                                                                    selected = "Ariana", multiple=TRUE)
                                                   ),
                                                   box(
                                                     solidHeader = FALSE,
                                                     width = 12,
                                                     background = "navy",
                                                     selectizeInput("parti", label = "Parti politique",
                                                                    choices = levels(pff$Q99),
                                                                    selected = "CPR", multiple=TRUE)
                                                   ),
                                                   box(
                                                     actionButton("action","Mettre à jour!"),
                                                     #submitButton("Mettre à jour!",icon("refresh")),
                                                     background = "navy"
                                                   )
                                                 )
                                          ),
                                          box(
                                            solidHeader = FALSE ,width = 8,height = 500,
                                            collapsible = TRUE,align="center",
                                            radioButtons("position", "", c("fill","stack"), selected = "fill", inline = TRUE, width = NULL),
                                            plotlyOutput('plot1', height = 400,width = "100%")
                                          )
                                        )# end of fluidrow
                                )
                              ))))
shinyApp(server = server, ui = ui)

A: If you inspect g$labels, what do you see?
It looks like you are allowing multiple selections for input parti.
The paste statement for the title is most likely picking these up and giving you more than one title, which is what the error is stating.
You can make the parti vector a character by wrapping it in an additional paste statement with collapse="," or by making all the inputs into the original paste a vector c("My title is",c(1,2)) with collapse=" ".
labs(title=paste("Vote dans la région de", inputObj$region,"pour",paste(inputObj$parti,collapse=","),sep = " "))


text:
Q: Summary output to independent dataset Im working with a twitter dataset i got with rtweet. I worked to create a state variable based on the coordinates (when available).
my output is this so far
> summary(rt1$state)
             alabama              arizona             arkansas           california             colorado          connecticut
                   3                    6                    2                  104                    5                    1
            delaware district of columbia              florida              georgia                idaho             illinois
                   1                    0                   17                    7                    0                   12
             indiana                 iowa               kansas             kentucky            louisiana                maine
                   4                    1                    2                    3                    2                    1
            maryland        massachusetts             michigan            minnesota          mississippi             missouri
                   1                    2                    9                    6                    0                    2
             montana             nebraska               nevada        new hampshire           new jersey           new mexico
                   0                    3                    5                    1                    4                    7
            new york       north carolina         north dakota                 ohio             oklahoma               oregon
                  25                    8                    1                    3                    2                    4
        pennsylvania         rhode island       south carolina         south dakota            tennessee                texas
                  22                    0                    2                    1                    3                   35
                utah              vermont             virginia           washington        west virginia            wisconsin
                   2                    1                    3                    5                    0                    2
             wyoming                 NA's
                   1                17669

can you please advise on how can i create an independent dataset from the output above so i have 2 columns (state and n) ?
thanks

A: We can wrap with stack to create a two column data.frame from the OP's code
out <- stack(summary(rt1$state))[2:1]
names(out) <- c("state", "n")

Or another option in base R is
as.data.frame(table(rt1$state))

A reproducible example
data(iris)
out <- stack(summary(iris$Species))[2:1]

Or with table
as.data.frame(table(iris$Species))

Or enframe from tibble
library(tibble)
library(tidyr)
enframe(summary(rt1$state)) %>%
   unnest(c(value))

A: Or maybe you can work directly on your rt1 dataframe:
dplyr::count(rt1, state)


text:
Q: How could a photo prove that Diana wasn't a normal human? In Batman V Superman movie, Diana received an email from Bruce Wayne:

How could a photo prove anything about her? The similar looking woman in the photo could be her grandmother. Or, it could be a photoshoped image.

A: The photo doesn't have to prove anything. The fact that somebody suspects is already bad news.
Diana has been living in secret for 100 years. She doesn't want anyone to know her true identity or history. So when somebody approaches her and says they know who she is, it doesn't matter whether they can prove it to the world or not. Just the fact that somebody suspects her is unsettling.
Think about it this way: if you were trying to hide something about your past, and somebody told you they knew what you were hiding, would it really matter whether they could prove it?

A: Well, one assumes perhaps some of the following:

*

*Bruce already had suspicions

*Bruce has other sources of information

*There was other information on Luthor's drive

In particular, it was shown that there are entire files on potential metahumans.

These files clearly show the Flash employing his speed powers, Aquaman underwater without breathing for an extended period, and the transformation of Victor Stone by the Mother Box into Cyborg.   While Diana's superpowers are not explicitly depicted (besides long life) it is implied that the files contain much more material.
In short, he is presenting the photo as quick evidence that he has reliable information to gain her attention by email, not necessarily presenting it as the only evidence he has that she is metahuman.  The additional evidence is attached.
TL;DR It's basically clickbait.

A: The photo was clearly from another historical era. Looking at the uniforms and such details you could figure out that it was probably one of the World Wars which could be almost a century ago. The fact that someone looks exactly as they a hundred years ago should already trigger the alarms.


text:
Q: How to access the subscriptions from the given publisher? (combine kit) Is there any way to get the subscriptions by accessing the publisher?
In the below example, I created a publisher, and had it subscribed by two subscribers and had the publisher send a value.
Here in this simple scenario, all works are thrown together in a couple of lines of code. It is easy to notice who subscribed the publisher. In real world application, however, each work is compartmentalized and hard to notice the subscribers from the publisher's standpoint.
So, does a publisher has properties to get access to the subscribers or subscriptions?
Or, do you suggest a design pattern to make publisher-subscriber data flow more obvious?
final class IntSubscriber: Subscriber {

  typealias Input = Int
  typealias Failure = Never

  func receive(subscription: Subscription) {
      print("receive subscription")
    subscription.request(.max(3))
  }

  func receive(_ input: Int) -> Subscribers.Demand {
    print("Received value", input)
    return .none
  }

  func receive(completion: Subscribers.Completion<Never>) {
    print("Received completion", completion)
  }
}

let subject = PassthroughSubject<Int, Never>()
let subscriber1 = IntSubscriber()
let subscriber2 = IntSubscriber()
subject.subscribe(subscriber1)
subject.subscribe(subscriber2)

// send a value without knowing who might get the value?
subject.send(3)

A: No, you cannot ask a publisher for its existing subscribers or subscriptions.
As for design patterns, I'm not sure what your goal is.

*

*If you want to be able to find the subscribers while debugging, then I'd say Combine is lacking in that department. Maybe Apple will delight us with better debugging tools at next week's WWDC.

*If you want to be able to statically see the overall flow, then I don't think you need any special patterns. You need to apply the same skills you would use to write a clear, understandable program that doesn't use Combine. Consider that other, much older APIs like NotificationCenter provide a very similar decoupling of signal emitters and signal receivers.
Keep in mind that Combine is "just" Apple's implementation of the Rx (Reactive Extensions) paradigm. Since Apple is so late to the Rx game (Microsoft released Rx.NET 1.0 in 2011!), there is a lot of advice available on how to use Rx that is applicable to Combine.


text:
Q: Create Word Meaning HTML page using HMTL5 and compare answers from xml I have a list of word and correspondingly meanings
What i want is to design the page in HTML5 in the following manner :

Also want to check the answers from xml file using javascript. But the problem here can be how do i get the draggable value from the draggable location of corresponding word.
Please help.

A: HTML code :
<!DOCTYPE html>

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 Word Meaning :

Astonish

Loony

          <input type="submit" value="Submit Answers" onclick="checkAnswers();"/>

 Select the meaning from the below list :

              Crazy
              Amazing

xml is in this format :
<?xml version="1.0" encoding="UTF-8"?>
<word-list>
    <word>
        <name>Astonish</name>
        <meaning valid="true">Amazing</meaning>
    </word>
    <word>
        <name>Loony</name>
        <meaning valid="true">Crazy</meaning>
    </word>
</word-list>

A: JSFIDDLE
U can use text, either an image

I think this is what you need.
Enjoy WebDesigning. :)


text:
Q: javascript date on custom button issue..? When i click on this custom button i need to fill a field with the current date and time.But some times its giving me a previous date i.e  exactly 1 day prior to current date..i dont know why this is happpening..can some help me out in this..may be there is some issue with javascript...or timezone issue..as its not happening everytime...but sometime..
var SO = new sforce.SObject("Sales_Order__c");

    function fixTime(time){
       if(time < 10) {time = "0" + time};
       return time;
    }
     function fixDate(date){
      var Month = fixTime(date.getMonth() + 1);
      var Day = fixTime(date.getDate());
      var UTC = date.toUTCString();
      var Time = UTC.substring(UTC.indexOf(':')-2, UTC.indexOf(':')+6);
      var Minutes = fixTime(date.getMinutes());
      var Seconds = fixTime(date.getSeconds());
      return date.getFullYear() + "-" + Month + "-" + Day + "T" + Time;
    }

    SO.date__c = fixDate(new Date());
updateSO = sforce.connection.update([SO]);

A: You're getting the local time zone year, month and day, but UTC time hours and minutes. When it's today here and tomorrow in UTC, your date calculations will become a day behind. Example follows:
Local time: 2013-12-31 22:00 -05:00
UTC time: 2014-01-01 03:00 -00:00

Year = 2013
Month = 12
Day = 31
Time = 03:00

So, you're committing the value of '2013-12-31T03:00Z' instead of '2014-01-01T03:00Z'.
There is no need for any of this code at all. The function sforce.internal.dateTimeToString automatically converts the date/time coordinate to the correct value for you as long as it is a native Date object.
In other words, change your code to:
var SO = new sforce.SObject("Sales_Order__c");
SO.Date__c = new Date();
SO.Id = "{!Sales_Order__c.Id}";
updateSO = sforce.connection.update([SO]);

Do not call sforce.internal.dateTimeToString, as it is already called for you, and as the "internal" suggests, you should not be using that function explicitly.
Edit You need to include the ID value to update a record. This is most likely the problem.

A: Javascript Date() instance has different behavior across browsers and not recommended for correct timing entry. It has mixed result between browsers, so even you are using it correctly you may get unexpected results and validating it is difficult. read here
Executing new Date() always returns current local time zone date and time.
However, setting date manually from javascript you can just use toISOString() method of Date API
SO.date__c = new Date().toISOString(); // return ISO 8601 Extended Format date in UTC

Internally it works as sample:
if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      var r = String(number);
      if ( r.length === 1 ) {
        r = '0' + r;
      }
      return r;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear()
        + '-' + pad( this.getUTCMonth() + 1 )
        + '-' + pad( this.getUTCDate() )
        + 'T' + pad( this.getUTCHours() )
        + ':' + pad( this.getUTCMinutes() )
        + ':' + pad( this.getUTCSeconds() )
        + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
        + 'Z';
    };

  }() );
}

A: The client (browser) and server (salesforce) are unlikely to be set to the same timezone. The clean solution to that problem is to avoid it and just use the server timezone.
If you have control over the definition of Sales_Order__c.date__c, why not just set the default value of that field to "TODAY()"? (That is assuming you are creating the object not updating it.)
If not, you can expose WebService method on a controller that sets the date and do a sforce.apex.execute on your button click to call that.

A: Your datetime is being returned in GMT and you need a Javascript method to convert from GMT to local time. This code sample may be of help:
http://bytes.com/topic/javascript/answers/478296-utc-date-time-local


text:
Q: How to count number of E-mails sent from a single account in Postfix? I am using Postfix mail server. How can I count number of E-mails sent from a single account in an hour?

A: Give a look at pflogsumm
It can show a per-email-count sorted list of both sent and received email.

A: # now=`date '+%b %d %H:%M'`
# prev=`date '+%b %d %H:%M' -d  "1 hour ago"`
# sed -n "/$prev/,/$now/p" /var/log/mail.log | egrep 'from.*someuser' | wc -l


text:
Q: Java string spilt not working My String as given below
     PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
    1 root      20   0 24416 2408 1360 S   0.0  0.2   0:00.88 init
   10 root      20   0     0    0    0 S   0.0  0.0   0:00.00 kdevtmpfs
  171 root       0 -20     0    0    0 S   0.0  0.0   0:00.00 mpt_poll_0
  818 messageb  20   0 23940 1260  920 S   0.0  0.1   0:00.97 dbus-daemon
  995 whoopsie  20   0  185m 4224 3000 S   0.0  0.4   0:00.06 whoopsie
 1000 daemon    20   0 16908  156    0 S   0.0  0.0   0:00.19 atd
24043 root      20   0  570m 3952 2780 S   0.0  0.4   0:04.28 console-kit-dae
24110 root      20   0  182m 3032 2484 S   0.0  0.3   0:01.66 polkitd
26310 root      20   0     0    0    0 S   0.0  0.0   0:00.00 flush-8:0
30081 root      20   0     0    0    0 S   0.0  0.0   0:00.02 kworker/0:1
31381 root      20   0     0    0    0 S   0.0  0.0   0:00.00 kworker/0:2
31511 root      20   0 81900 3904 3048 S   0.0  0.4   0:00.03 sshd
31646 root      20   0 19228 1376 1060 R   0.0  0.1   0:00.00 top

now I want splits this string so I used following java function
for(int i = 0; i < mystring.length; i++){
    String[] values = mystring.split("\\s+");
    System.out.println(values[0]);
}

but when I check values[0] it shows only 31646 not display other? I think it wrong with my regular expression in split so I also tried this "\\t\\n\\x0B\\f\\r" but it not work. If any one knows how to manged this?

A: I don't know what output you want, but try this code instead.
String[] values = mystring.split("\\s+");
for(int i=0; i<values.length;i++)
{
    System.out.println(values[i]);
}

This will split and display everything separated in a space in mystring.
Edit: Now that I know what you want, I can help you a little more. What you want is a 2d array so you can have it the way you want it. If you do this:
String[] values = mystring.split("\\s+");
String[][12] output;
for(int i = 0; i < (values.length)/12 ;i++)
{
    for(int i = 0; j < 12; j++)
    {
        output[i][j] = values[i*12 + j];
    }
}

Since there are 12 commands, the array will be an x by 12. Now you can print them in another loop.
for(int i = 0; i < output.length; i++)
{
    for(int j = 0; j < 12; j++)
    {
        System.out.print(output[i][j] + " ");
    }
    System.out.println(" ");
}

You can also just create a class and store each value as a variable. What you want to do just is more fit for an array of objects.

A: Well I believe \s should be sufficient enough to do the job. I would suggest you remove the plus. Try this.
String[] values = mystring.split("\\s+");

for(int i=0; i<mystring.length;i++){
    System.out.println(values[0]);
}

you kept the array in the for clause which is wrong. This should work.
If you have questions, pls ask. And mark as answer if it helps you

A: You are trying to print the first element I have tried below code and it worked perfectly fine
String mystring = "1111    2222   eeeeeee  www          eeeeee";
        String[] values = mystring.split("\\s+");
        for(int i=0; i< values.length;i++){
        System.out.println(values[i]);
        }


text:
Q: Getting the current URL in an Android browser I'm searching for a way to get the current URL a user is visiting on the android browser application.
I figured out that I can get the last visited URL from the Browser.BOOKMARKS_URI database using the following technique:
Cursor cursor = context.getContentResolver().query(Browser.BOOKMARKS_URI,
        Browser.HISTORY_PROJECTION, null, null,
        Browser.BookmarkColumns.DATE + " DESC");
cursor.moveToNext();
String url = cursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
cursor.close();

The problem with this, is that the Browser.BOOKMARKS_URI db doesn't get updated when the user presses back in order to navigate to the previous page in the browser, and the query returns incorrect results.
See the following example:

*

*user navigates to www.google.com -> Query returns "www.google.com"

*user navigates to www.imdb.com -> Query returns "www.imdb.com"

*user presses back to return to www.google.com -> Query returns "www.imdb.com" (!!)
Does anyone have any idea how to return the correct url a user is viewing?

A: I think you did not have gone through the following approah. once try it!
You can access Browsing history the same way you do that for other ContentProviders. Besides browsing history you can also get list of Bookmarks.
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();

int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);

if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0))
{
    webLinksCursor.moveToFirst();
    while (webLinksCursor.isAfterLast() == false)
    {
        if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1)
        {
            if (!webLinksCursor.isNull(url_column_index))
            {
                Log.i("History" , "Last page browsed " + webLinksCursor.getString(url_column_index));
                break;
            }
        }
        webLinksCursor.moveToNext();
    }
}
webLinksCursor.close();

and you need the permission also
com.android.browser.permission.READ_HISTORY_BOOKMARKS


text:
Q: Firefox on Linux always shows history dropdown when clicking back button When I left-click on the back button in Firefox on Linux, I go back 1 page and then a dropdown with my browsing hisrory appears. Always. And then I have to click some place else to make it go away.
On Windows, same Firefox version, I only go back and there is no history drop down. Just like I want it.
Is there some config switch to avoid the drop-down? Anything else I can check?
I'm using Firefox 44.0.2 on Linux and Windows, but its been like this for a while now.


text:
Q: ADB debugging in Android Studio - some basic issues Ok, I've squeaked by not needing to use ADB in the Studio, since back
in the 'beta' days of AS. (Just lucky, I guess.)  But now, I need to
debug a crashing app.
I've gotten this far:
  Learned how to put adb.exe on my Window's 'PATH'
  (so that it's invokable from cmd-window):
     My path-entry was: C:\Users\David\AppData\Local\Android\sdk\platform-tools
Am assuming that 'logcat' lives on Android device (I was incorrectly guessing it lives on the development machine).  I'm assuming this, because when I dis-connect
the USB-cable and enter 'adb logcat' is says waiting for device.
Ok, now my (next) issue: When I fire up the app-being-developed, I'm getting
"Unfortunately  has stopped"...which I'm assuming is an app-crash.
And, while I'm looking at 'logcat', I can see a stack-trace flow by.  But
as I try to scroll-back to read it, logcat keeps dribbling in more data.
So, how do I tell it to shutup...so that I can look at a static copy
of logcat and see what has happened (without more data dribbling in)?
[If there is other beginner related info, beyond this question, feel free to
to add that info...I'm clearly in need of basic 'adb-related' enlightenment.]
TIA.
Cheers...


text:
Q: Terraform: List of AMI specific to ubuntu 20.08 LTS AWS Problem: I am using terraform to get a list of AMI for a specific OS - ubuntu 20.08
I have checked different examples link
When I use the script this does not give me list of AMI
Script
data "aws_ami" "ubuntu" {
    most_recent = true

    filter {
        name   = "name"
        values = ["ubuntu/images/hvm-ssd/ubuntu-xenial-20.08-amd64-server-*"]
    }

    filter {
        name = "virtualization - type"
        values = ["hvm"]
    }

    owners = ["AWS"]
}

I have referred the below link as well
How are data sources used in Terraform?
Output:
[ec2-user@ip-172-31-84-148 ~]$ terraform plan
provider.aws.region
  The region where AWS operations will take place. Examples
  are us-east-1, us-west-2, etc.

  Enter a value: us-east-1

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

data.aws_ami.std_ami: Refreshing state...

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your configuration and real physical resources that exist. As a result, no actions need to be performed.

i am not sure where am I going wrong i have checked a lot of links some i have listed below.

A: Your data should be:
data "aws_ami" "ubuntu" {

    most_recent = true

    filter {
        name   = "name"
        values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
    }

    filter {
        name = "virtualization-type"
        values = ["hvm"]
    }

    owners = ["099720109477"]
}

output "test" {
  value = data.aws_ami.ubuntu
}

The owner of Ubuntu is not AWS, and the image is ubuntu-focal-20.04-amd64-server-, not ubuntu-xenial-20.08-amd64-server-.
The above results in (us-east-1):
 {
  "architecture" = "x86_64"
  "arn" = "arn:aws:ec2:us-east-1::image/ami-0dba2cb6798deb6d8"
  "block_device_mappings" = [
    {
      "device_name" = "/dev/sda1"
      "ebs" = {
        "delete_on_termination" = "true"
        "encrypted" = "false"
        "iops" = "0"
        "snapshot_id" = "snap-0f06f1549ff7327c9"
        "volume_size" = "8"
        "volume_type" = "gp2"
      }
      "no_device" = ""
      "virtual_name" = ""
    },
    {
      "device_name" = "/dev/sdb"
      "ebs" = {}
      "no_device" = ""
      "virtual_name" = "ephemeral0"
    },
    {
      "device_name" = "/dev/sdc"
      "ebs" = {}
      "no_device" = ""
      "virtual_name" = "ephemeral1"
    },
  ]
  "creation_date" = "2020-09-08T00:55:25.000Z"
  "description" = "Canonical, Ubuntu, 20.04 LTS, amd64 focal image build on 2020-09-07"
  "filter" = [
    {
      "name" = "name"
      "values" = [
        "ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*",
      ]
    },
    {
      "name" = "virtualization-type"
      "values" = [
        "hvm",
      ]
    },
  ]
  "hypervisor" = "xen"
  "id" = "ami-0dba2cb6798deb6d8"
  "image_id" = "ami-0dba2cb6798deb6d8"
  "image_location" = "099720109477/ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-20200907"
  "image_type" = "machine"
  "most_recent" = true
  "name" = "ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-20200907"
  "owner_id" = "099720109477"
  "owners" = [
    "099720109477",
  ]
  "product_codes" = []
  "public" = true
  "root_device_name" = "/dev/sda1"
  "root_device_type" = "ebs"
  "root_snapshot_id" = "snap-0f06f1549ff7327c9"
  "sriov_net_support" = "simple"
  "state" = "available"
  "state_reason" = {
    "code" = "UNSET"
    "message" = "UNSET"
  }
  "tags" = {}
  "virtualization_type" = "hvm"
}