text:
Q: Non-standard character prevents me from reading in full csv file in R My csv file (accessible through link and viewable through screenshot) has 8 observations. Obs #5 has a non-standard character in the "author" column. I've shaded this yellow.
https://docs.google.com/spreadsheets/d/1-douIz03OQqahG6WCWY-irOE52oXtDDc4fJ6myMwJDk/edit?usp=sharing

When I run the following:

data1<-read.csv("Book1.csv",colClasses=c("end_date_n"="character","start_date_n"="character"),stringsAsFactors=FALSE)

I get this warning message and only the first 4 rows and a partial 5th row are imported. The import stops at the point where the non-standard character appears in col 5.

In scan(file = file, what = what, sep = sep, quote = quote, dec = dec,
  :   EOF within quoted string

When I delete the "author" column from my csv source file, the import works fine.
How can I import the full file without having to delete the problem column?

A: A colleague came up with this solution:
"The original character is ^z, which for decades was used by DOS/Windows as an end of file marker. Because UNIX systems never used ^z, the read-in problem is Windows-specific. Windows systems often direct users to enter non-ASCII characters (like é) using "ALT" codes. This may be where the ^z originates."
"Use a utility to translate ^z to something innocuous. The killZ function below takes the name of a file, translates ^z to *, then write the results in the same directory as the original file but with a -noz inserted just before the .txt or .csv (or whatever) filetype. You can then read the -noz file in the same way you have been reading the original .txt or .csv file."
killZ <- function(fname) {
  # open in binary mode
  f <- file(fname, "rb")
  res <- readLines(f)
  # translate the ^Z to *
  res <- gsub("\032", "*", res, fixed = TRUE)
  # Create the new file name
  ftype <- stringr::str_extract(fname, "\\..{1,3}$")
  new_name <- paste0(gsub(ftype, "", fname), "-noz", ftype)
  writeLines(res, con = new_name)
  close(f)
  return(new_name)
}


text:
Q: Ruby Trouble Interacting with Filesystem when run from LaunchAgent I have a Ruby script that I am triggering with an OS X launchagent. The script reads a bunch of files (21 total) from disk, does some processing, compiles them into an RSS feed, and uploads it to a remote machine using scp. The script works fine when I run it from the command line. However, when I run it with a launchagent I run into some very strange issues. I have isolated the problem to this line:
match = @content.match(/(?<=^ID: )\d+/)

@content here refers to the contents of a file, read in earlier. This line is embedded in a class which serially processes each file. Something about this line is somehow causing execution to be dropped-- when I put a log statement after this line, it is triggered only for 16/21 of the files when running as launchagent. When running from the command line, there is no issue.
I also have noticed that these 5 files are almost, but not exactly, the five largest of the 21 files. What could possibly be going on? Any well-known typical issues when working with LaunchAgents?
UPDATE: this is one of the files that is breaking the code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: trouble installing 16.04-system installation When trying to install 16.04, I get a message that I have 3 broken packages that need to be fixed but when I click on Fix Broken Packages I get an error message saying I have "held packages". Point is, how do I go about installing the new upgrade and fix this problem ?

A: Did you turn off all the extra ppas you might have added before the upgrade?  Did you remove the hold on the packages which are "held"?
For example:
sudo apt-mark unhold package_name

see How to prevent updating of a specific package? for other package managers.

Yes assuming dbus is the first package to unhold.


text:
Q: How to get shortcut target I need to be able to read the target of a shortcut (a .lnk file).
I have Googled this and found numerous results that I have found to be helpful:
http://cboard.cprogramming.com/windows-programming/62962-ishelllink-getpath-dev-cplusplus.html
http://www.go4answers.com/Example/get-shortcut-target-cpp-win64-216615.aspx
http://msdn.microsoft.com/en-us/library/bb776891%28VS.85%29.aspx
http://www.codeproject.com/KB/shell/create_shortcut.aspx
Some of these web pages don't mention which header files I need, and I am unaware how to find this information out.
The code that I am currently trying to get working is this:
#include <windows.h>
#include <string>

#include <objidl.h>   /* For IPersistFile */
#include <shlobj.h>   /* For IShellLink */

using namespace std;

int main(void)
{

IShellLink* psl;
wchar_t* tempStr = new wchar_t[MAX_PATH];
string path = "E:\\shortcuts\\myshortcut.lnk";

HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*) &psl);

if (SUCCEEDED(hr))
{
    IPersistFile* ppf;
    hr = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
    if (SUCCEEDED(hr))
    {
        hr = ppf->Load(path.c_str(), STGM_READ);

        if (SUCCEEDED(hr))
        {
            WIN32_FIND_DATA wfd;
            psl->GetPath(tempStr, MAX_PATH, &wfd, SLGP_UNCPRIORITY | SLGP_RAWPATH);
        }
    }
}
    return 0;
}

You can probably see that this is mainly from one of the websites above, however they did not mention which headers they used, so I had a good guess (which seems to be working) at which ones to use.
Currently the errors I am getting are:
In function 'int main()':
24|error: no matching function for call to 'IPersistFile::Load(const char*, int)'
29|error: no matching function for call to 'IShellLinkA::GetPath(wchar_t*&, int, WIN32_FIND_DATA*, int)'
||=== Build finished: 2 errors, 0 warnings ===|

I was hoping that someone may be able to give me some advice on this, whether it is just pointing me to some better links or, even better, possibly explaining the above code, how to find out which headers to use and where I am going wrong, or an entirely different solution that achieves the same result.

A: All headers are fine, but you are using wide (wchar_t based) and 'normal' (char based) strings incorrectly: IPersistFile::Load takes a wide string while IShellLinkA::GetPath takes a normal string.
Using this should compile:
IShellLinkA* psl; //specify the ansi version explicitely
CoInitialize( 0 ); //you forgot this, needed for all COM calls to work
char* tempStr = new char[ MAX_PATH ];
std::wstring path = L"E:\\shortcuts\\myshortcut.lnk";

Also if you just want the path, you can just pass 0 instead of a pointer to a WIN32_FIND_DATA.


text:
Q: Problem with full-screen applications and fractional scaling for HiDPI monitors This is another problem I experience with fractional scaling/HiDPI and Ubuntu 20.10.
I have a setup with 2 normal DPI monitors and one HiDPI with 150% zoom.
The problem is when an application requests full screen (i.e. firefox and a video in youtube, VLC, or even a wine game). Then the application changes (properly) to full screen, there's a flicker, the resolution changes, the screen flickers again, another resolution change and the monitors are left in a total mess.
With firefox/youtube things are even worse. The screen goes into infinite loop of changing resolutions.
If I disable fractional scaling and put everything into 100% or 200%, no problem appears. Even if I keep on fractional scaling, but put either 100% or 200%, still not problem appears. Same, if I use fullscreen on a monitor with no fractional scaling. But, when I try to put full screen for a fractional scaling monitor, chaos emerges.
I am really confused on how to approach this problem... any ideas?
EDIT I am using X11 backend, not wayland and Ubuntu's Gnome as Window manager.
EDIT 2 When I change from default Gnome to Budgie, there I can launch fullscreen apps correctly. So it looks like a Gnome issue. Any hint how to solve it or where should I report it?


text:
Q: How to hold the value in source variable while changing in destination (grid store) I have some data in like this.
var myData = [{"name" : "David", "Country":"India"},{"name" : "Paul", "Country":"USA"}]

in my extJS grid I am loading data like this :
_this.getView().getStore().loadData(myData);

This is my editable grid. Now when I change the data in extJS grid ex : "country : USA" to "Country : England", How it will get update in myData Variable as well. How can do the copy of myData as store which change the value at both the places.

A: var myData = [{"name" : "David", "Country":"India"},{"name" : "Paul", "Country":"USA"}];

_this.getView().getStore().loadData(Ext.Array.clone(myData));

The clone method will clone your myData variable and return a new Array.
Clone method


text:
Q: C#/WPF: Why is TabItem.IsFocused returning null i have code like
e.CanExecute = tabEditor.IsFocused;

but at runtime, i get a null reference exception error. but in the docs, IsFocused returns only true or false, why is this happening? btw, tabEditor is a <TabItem>

A: Chances are that either e or tabEditor is null, i.e., they weren't assigned to an object anywhere (or otherwise explicitly assigned to null). If the code is in an event handler, it's possible that the framework hasn't initialized all the variables by the time the event handler is called, in which case you might want to check for null.


text:
Q: Calculating the limit of a product Question: Let $a_1=1$ and $a_n=n(a_{n-1} +1)$ for $n=2,3, \ldots$
Define $P_n= (1+\frac{1}{a_1})(1+\frac{1}{a_2}) \cdots (1+\frac{1}{a_n}) ; \;\;\; n=1,2, \ldots$
Find $\lim_{n \to \infty} P_n$.
[I have outlined my (tedious) approach below, I'm merely curious whether there is a more elegant way to arrive at the result]
My Approach: I was able to arrive at the fact that $P_n=\frac{a_{n+1}}{(n+1)!}$
Then I expanded $a_{n+1}$ as follows
$$ a_{n+1}=(n+1)[a_n+1]$$
$$ = (n+1)[n(a_{n-1}+1)+1]$$
$$ = (n+1)(n)a_{n-1} + (n+1)(n)+(n+1)$$
$$ = (n+1)(n)[(n-1)\{a_{n-2}+1\}] + (n+1)(n)+(n+1)$$
$$ = (n+1)(n)(n-1)a_{n-2} + (n+1)(n)(n-1) + (n+1)(n)+(n+1)$$
Proceeding similarly, we arrive at the expansion
$$ a_{n+1} = (n+1)!a_1 + (n+1)! + \frac{(n+1)!}{2!} + \frac{(n+1)!}{3!} + \cdots + \frac{(n+1)!}{n!}$$
and thus $$ P_n= \frac{a_{n+1}}{(n+1)!}= 1+ \frac{1}{1!} + \frac{1}{2!} +  \cdots + \frac{1}{n!}$$
$$ \lim_{n\to\infty} P_n = 1+ \frac{1}{1!} + \frac{1}{2!} + \cdots = e$$

A: Note that $$\frac{a_{n+1}}{(n+1)!}=\frac{a_n}{n!}+\frac{1}{n!}$$ this gives your final equation.


text:
Q: How to apply dark theme to this calendar view t?
When I switched to dark mode appearance on ubuntu and for some reasons checked my calendar the dark theme was not there. I think it's a bug. Is there any workaround for this?

A: I'd install Tweaks and select another Shell Appearance. Yaru Dark should work.


text:
Q: Unable to rename/copy the root field name in logstash Here is my sample config LS 7.9.
input {
  jdbc { ... }
}

filter {
json {

    #It's JSON field from DB, including only two for reference.
    source => "tags_json"

    #Need it as Sub-field like tags.companies, tags.geographies in ES
    add_field => {
      "[tags][companies]" => "%{companies}"
      "[tags][geographies]" => "%{geographies}"
    }

output {
  elasticsearch { ... }
}

JSON structure in DB field tags_json
{"companies": ["ABC","XYZ"],
 "geographies": [{"Market": "Group Market", "Region": "Group Region", "Country": "my_country"}],
 "xyz":[]...
}

Logstash prints root geographies field correctly, this is what I need as sub-field under tags.
"geographies" => [
        [0] {
            "Market" => "Group Market",
            "Region" => "Group Region"
        },

## But as sub-field under the tags, only geographies is nil
"tags" => {
         "companies" => [
            [0] "ABC",
            [1] "XYZ"
        ],
        "geographies" => nil
    }

I tried below copy, ruby, but doesn't seem to fix it :
mutate {  copy => { "%{geographies}" => "[tags][geographies]"} }
Also tried Ruby
ruby {  code => " event.set('[tags][geographies]', event.get('%{geographies}')) " }
Any help please. Thanks.

A: Resolved it with ruby event.
ruby {
    code => 'event.set("[tags][geographies]", event.get("geographies"))'
  }


text:
Q: My UI did not response for orientation change I am developing a native mobile app for all platforms. I have created my own theme content page. Then after deployment on android when I make phone landscape it did not respond. what's the reason here.
Here is my base content page.
   public abstract class BaseContentPage : ContentPage
{
    public readonly BaseViewModel BaseViewModel;

    protected bool _isNavigated = false;

    public BaseContentPage(BaseViewModel baseViewModel)
    {
        BaseViewModel = baseViewModel;
    }

    public abstract void Navigate(SelectedItemChangedEventArgs e);
    protected abstract override void OnAppearing();
    protected override void OnDisappearing()
    {
        _isNavigated = true;
    }

    public BaseContentPage()
    {

    }
}

here Xaml
        <views:BaseContentPage
xmlns:views="clr-namespace:DipsDemoXaml.Views"

            xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:Resource="clr-namespace:DipsDemoXaml.Resources"

            x:Class="DipsDemoXaml.Views.WardListPage" Title="{x:Static Resource:AppResources.WardListPageTitle}">
    <StackLayout BackgroundColor="{StaticResource DefaultBackgroundColor}" Orientation="Vertical" x:Name="s1">

I even try this also in code behind constructor I call size changed and create a method called Wardpagesizechanged.
        public WardListPage(WardListPageViewModel wardListViewModel) : base(wardListViewModel)
    {
        InitializeComponent();
        this.SizeChanged += wardpagesizechanged;

    }

Wardpagesizechanged method
      private void wardpagesizechanged(object sender, EventArgs e)
    {
       if(this.Width> this.Height)
        {
            s1.Orientation = StackOrientation.Horizontal;
        }
        else
        {
            s1.Orientation = StackOrientation.Vertical;
        }
    }

what is the problem here, I am clueless


text:
Q: Java Jframe is displaying but the contents (Panel) is not showing properly I've developed a small application to track my daily work activities, this tool contains two classes:

*

*Executor

*UIProgress

My objective was to create a ProgressBar which updates the status of the execution, the logic used is given below,

*

*From executeTask () defined in Executor class, I'have created
UIProgress object.

*The UIProgress class extends JFrame. Create a panel which contains
a label with one image and the progress bar. I've defined a
method updateProgress in this class which set the value for
progressbar.

*In executeTask () method (in Executor class), created UIProgress
object. In executeTask (), am calling different functions to execute
the tasks and after each function am invoking
UIProgress.updateProgress () method with integer vale to update progressbar.

*But while running the program, the JFrame UI is transparent means it didn't show the contents instead contains the background data in the frame, Only progressbar is showing and it updating but the entire JFrame is transparent. We are not seeing the panel (image) and it shows as a transparent mode.

Note: setVisible (true) called after added panel into JFrame.
Executor.java
public void executeTask  ()
{

     /* Create and display the form */

    progress = new UIProgress();
    progress.prepareGUI();

    progress.updateProgress (10);
    getWorkedItems ();
    //progress.pack ();

    progress.updateProgress  (30);
    getWorkedTickets ();

    progress.updateProgress (50);
    getRemainTickets ();

    progress.updateProgress (70);
    jf.postTriagedTicketDetailsDaily();
    ...
}

UIProgress.java
public class UIProgress extends javax.swing.JFrame {
    public UIProgress() {

           try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
        }
        initComponents();

    }

    private void initComponents() {

        panelHeading = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        progress_cntrl = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        panelHeading.setBackground(new java.awt.Color(204, 204, 204));
        panelHeading.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        panelHeading.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        panelHeading.setOpaque(false);

        jLabel1.setBackground(new java.awt.Color(0, 0, 0));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/devtriagerepot_daily/Background-20.jpeg"))); // NOI18N

        javax.swing.GroupLayout panelHeadingLayout = new javax.swing.GroupLayout(panelHeading);
        panelHeading.setLayout(panelHeadingLayout);
        panelHeadingLayout.setHorizontalGroup(
            panelHeadingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelHeadingLayout.createSequentialGroup()
                .addContainerGap(29, Short.MAX_VALUE)
                .addComponent(progress_cntrl, javax.swing.GroupLayout.PREFERRED_SIZE, 651, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27))
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        panelHeadingLayout.setVerticalGroup(
            panelHeadingLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelHeadingLayout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(progress_cntrl, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 31, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(panelHeading, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 4, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(panelHeading, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        getAccessibleContext().setAccessibleParent(this);

        pack();
    }
   public  void prepareGUI ()
    {
        progress_cntrl.setMaximum(120);
        progress_cntrl.setStringPainted(true);

        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - this.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - this.getHeight()) / 2);
        this.setLocation(x, y);

        pack ();
        setVisible(true);
    }

    public void updateProgress (int val)
    {

        progress_cntrl.update(progress_cntrl.getGraphics());
        progress_cntrl.setValue(val);

    }

A: The key is likely in these methods here:
getWorkedItems ();

getWorkedTickets ();

getRemainTickets ();

If they take any time to perform at all, your calling them on the Swing event thread will block the thread and freeze your GUI completely, rendering it unable to draw itself properly. The solution is to call any long-running methods in a background thread, such as a SwingWorker's doInBackground() method, and make Swing calls only on the Swing event thread. Again a SwingWorker would work well for this, and in fact it has its own "bound" progress property that can be used. Within the worker simply call setProgress(value) where value is your int from 0 to 100. Then attach a PropertyChangeListener to the worker so that the GUI can be notified of these changes when the progress property is updated.
A caveat: be sure to listen for the worker to finish its run so that you can call get() on the worker as this ill allow you to trap and respond to any exceptions that might have been called during its run.
For example, your code could look something like:
public void executeTask() {
    progress = new UIProgress();
    progress.prepareGUI();

    final SwingWorker<Void, Void> myWorker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            // progress.updateProgress (10);
            setProgress(10); // sets the worker's "bound" progress property
            getWorkedItems();

            setProgress(30);
            getWorkedTickets();

            setProgress(50);
            getRemainTickets();

            setProgress(70);

            // ... only further background work goes here
            // no direct Swing calls
            return null;
        }
    };
    myWorker.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {

            if ("progress".equals(evt.getPropertyName())) {
                // if the progress property has been changed
                // get its value and use it to update the GUI
                progress.updateProgress((int) evt.getNewValue());
            } else if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                // worker is done then here notify the GUI
                // perhaps call:
                // jf.postTriagedTicketDetailsDaily();

                // call get() on worker to catch and handle exceptions
                try {
                    myWorker.get();
                } catch (InterruptedException | ExecutionException e) {
                    // TODO handle the excpetions here
                    e.printStackTrace();
                }
            }
        }
    });
    myWorker.execute();
}

Note: code not tested.

*

*Please check out Lesson: Concurrency in Swing

*Also check out the Swing Tutorials
If this doesn't solve your problem, then you will likely have to create and post a sscce or a minimal example program/mcve where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem.
For example, this small program demonstrates the above code in a working GUI:
import java.awt.*;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import javax.swing.*;

public class TestWorker {
    private UIProgress progress;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new TestWorker().executeTask();
        });
    }

    public void executeTask() {
        progress = new UIProgress();
        progress.prepareGUI();

        final SwingWorker<Void, Void> myWorker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                // progress.updateProgress (10);
                setProgress(10); // sets the worker's "bound" progress property
                getWorkedItems();

                setProgress(30);
                getWorkedTickets();

                setProgress(50);
                getRemainTickets();

                setProgress(70);

                TimeUnit.SECONDS.sleep(2);

                // ... only further background work goes here
                // no direct Swing calls
                return null;
            }
        };
        myWorker.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {

                if ("progress".equals(evt.getPropertyName())) {
                    // if the progress property has been changed
                    // get its value and use it to update the GUI
                    progress.updateProgress((int) evt.getNewValue());
                } else if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                    // worker is done then here notify the GUI
                    progress.updateProgress(100);
                    // perhaps call:
                    // jf.postTriagedTicketDetailsDaily();

                    // call get() on worker to catch and handle exceptions
                    try {
                        myWorker.get();
                    } catch (InterruptedException | ExecutionException e) {
                        // TODO handle the exceptions here
                        e.printStackTrace();
                    }
                }
            }
        });
        myWorker.execute();
    }

    // dummy methods just to demonstrate long-running code
    private void getRemainTickets() {
        mySleep(3);  // emulate long-running code
    }

    private void getWorkedTickets() {
        mySleep(4);
    }

    private void getWorkedItems() {
        mySleep(2);
    }

    private void mySleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {}
    }

    @SuppressWarnings("serial")
    private class UIProgress extends JPanel {
        private static final int PREF_W = 400;
        private static final int PREF_H = 100;
        private JProgressBar progressBar = new JProgressBar(0, 100);
        private JLabel statusLabel = new JLabel(" ");

        public UIProgress() {
            JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
            statusPanel.add(new JLabel("Status:"));
            statusPanel.add(Box.createHorizontalStrut(4));
            statusPanel.add(statusLabel);

            setLayout(new BorderLayout());
            setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
            add(statusPanel, BorderLayout.PAGE_START);
            add(progressBar, BorderLayout.PAGE_END);
        }

        public void prepareGUI() {
            JFrame frame = new JFrame("UI Progress");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(this);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

        @Override
        public Dimension getPreferredSize() {
            if (isPreferredSizeSet()) {
                return super.getPreferredSize();
            }
            return new Dimension(PREF_W, PREF_H);
        }

        public void updateProgress(int prog) {
            String text = String.format("Current Progress is %d%%", prog);
            statusLabel.setText(text);
            progressBar.setValue(prog);
        }

    }
}


text:
Q: unable to flash micropython to esp 32: open serial error issue: unable to flash micropython to esp 32: open serial error, please try again. hope to connect internet and try again.
pretty new to micropython - want to flash micropython to esp 32 ( resp 8266) board.
cf this docs: https://maker.pro/esp8266/tutorial/using-micropython-on-an-esp8266-with-upycraft
getting this errors all the time.
open serial error, please try again.
hope to connect internet and try again.
current version only open py txt json ini file.
hope to connect internet and try again.
hope to connect internet and try again.

i run Win 7
the hardware:
a. Joy-IT-Node MCU ESP8266
.. and besides that i also tried it with the following
b. ESP32-T Development Board CP2102 with Espressif ESP-WROOM-32 IoT WLAN & BLE Modul
yes: i have installed the > CP210x_Universal_Windows_Driver.zip
by the way: i could try to do all that on a linux machine. - on a MX-Linux-Sytem
any idea;
many thanks for any and all help in advance.

A: As of my opinion, You don't necessarily depend on the uPyCraft IDE. So there are several other ways to develop scripts and uploading them to Your board.
Some days ago I was facing problems with Python on the NodeMcu as well. Since I didn't like the tutorials around the web, I've set up one on GitHub, covering the end-to-end process (required software, drivers, firmware images, developing, flashing, uploading, etc.): python2nodemcu.
It depends on Mac and the NodeMcu board, but some of the topics may apply to other operating systems and boards as well.
And I think it covers the most relevant parts of the whole process, using the easiest tools around the web. Please have a look at it, but all in all it goes like this (short version of the linked documentation above):

*

*Install Python 3

*

*Verify with python --version

*Or python3 --version

*Install the correct SiLabs driver to enable serial USB-to-UART communication

*

*See here

*Find the device file (representing the interface to the physical device)

*

*Try it using ls -la /dev/tty.*

*Download the recent MicroPython firmware

*

*You need the right one for Your board

*Install the two Python-based libraries EspTool and PySerial

*Try to erase the flash of Your device

*

*Run python3 esptool.py --port /dev/tty.{device-file} erase_flash

*Try to flash the original image or the MicroPython firmware to the board

*

*Run python3 esptool.py --port /dev/tty.{device-file} write_flash 0x00000 {micropython-image-or-original-firmware}.bin

*Try to connect to the board via the REPL prompt

*

*Run screen /dev/tty.{device-file} 115200

*You maybe need to try different baud rates (depending on Your driver, cable, etc.)

*Connect to the board using Ampy

*

*For example, try to list the files on Your device executing python3 ampy/cli.py --port /dev/tty.{device-file} --baud 115200 ls

*Again, try other baud rates

Anyway, I've noticed that You do not necessarily need to push the physical flash button on the device.


text:
Q: Erro de parâmetros no MySQL com C# string sql = @"UPDATE ivendas SET nritem=(@rank:=(@rank+1)) where id_venda = 20";
try
{
    MySQLBase basemysql = new MySQLBase();
    MySqlCommand cmd = basemysql.connection.CreateCommand();
    cmd.CommandText = sql;
    cmd.CommandTimeout = 1000;
    cmd.Parameters.AddWithValue("@rank",0);
    cmd.ExecuteNonQuery();
    basemysql.Closer();
}
catch (Exception erro)
{
    string teste = erro.ToString();
    Console.WriteLine(teste);
}

Lembrando que meu RANK e meu contador. Por isso um parâmetro ou variável.
Meu erro e esse daqui ->

"MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error
  in your SQL syntax; check the manual that corresponds to your MySQL
  server version for the right syntax to use near ':=(0+1)) where
  id_venda = 20' at line 1\r\n   em
  MySql.Data.MySqlClient.MySqlStream.ReadPacket()\r\n   em
  MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow,
  Int64& insertedId)\r\n   em
  MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32&
  affectedRows, Int64& insertedId)\r\n   em
  MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean
  force)\r\n   em
  MySql.Data.MySqlClient.MySqlDataReader.NextResult()\r\n   em
  MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior
  behavior)\r\n   em
  MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()\r\n   em
  Restaurante.Ivendas.OrganizarItensdaVenda(String idvenda)"

Meu banco
nritem | id_venda
 2     | 20
 3     | 20
 4     | 20

Preciso que fique assim:
nritem | id_venda
 1     | 20
 2     | 20
 3     | 20

A: Após o AP esclarecer melhor a resposta teria que ser diferente do abaixo:
Não é possível sem algum truque com o próprio SQL. Poderia usar uma stored procedure que tenha uma variável que vá sendo incrementada. Ou poderia usar uma tabela temporária auxiliar que pegue os valores já incrementados.
E não precisaria parametrizar a consulta.
Talvez possa fazer algum alguma função de janela, mas não sei o quanto o MySQL é capaz de lidar om isto ou como fazer já que não tenho experiência este mecanismo.

Provavelmente quer isto:
@"UPDATE ivendas SET nritem = @rank + 1 where id_venda = 20"

Porém, se o valor for 0 mesmo, então faça isto, e nem precisa de parâmetros:
@"UPDATE ivendas SET nritem = 1 where id_venda = 20"

Coloquei no GitHub para referência futura.
Esta captura de exceção não faz sentido aí, só causa problema, e o fechamento da conexão desta forma pode causar problemas em algumas situações. Falo disto o tempo todo.

A: Tente com o seguinte código:
  update itens set nritem =
  (
      select
          aux.iterator
      from (
          select
          @i:=@i+1 AS iterator,
          nritem,
          venda
          from itens, (SELECT @i:=0) AS foo
          where venda = 20) as aux
      where aux.venda = itens.venda
      and aux.nritem = itens.nritem)
  where venda = 20;

Antes da execução:

SQLFiddle: http://sqlfiddle.com/#!9/fcd41/1

Após a execução:

SQLFiddle: http://sqlfiddle.com/#!9/5c0b6d/1


text:
Q: Double received unexpected message despite of stubbing Double received unexpected message failure/error is reported when attempting to run the following spec:
MyKlass
  does something
  does something again (FAILED - 1)

Failures:

  1) MyKlass does something again
     Failure/Error: MyKlass.do_something
       Double "OtherKlass" received unexpected message :closed? with (no args)
     # ./lib/my_klass.rb:5:in `do_something'
     # ./spec/my_klass_spec.rb:17:in `block (2 levels) in <top (required)>'

Finished in 2.05 seconds
2 examples, 1 failure

Failed examples:

rspec ./spec/my_klass_spec.rb:16 # MyKlass does something again

Here is a minimal example to easily reproduce this issue...
Spec file spec/my_klass_spec.rb:
 1 require "spec_helper"
 2
 3 class OtherKlass; end
 4
 5 describe MyKlass do
 6   let(:objekt) { double("OtherKlass", closed?: "NOT REALLY") }
 7
 8   before :each do
 9     OtherKlass.stub(:get_objekt).and_return(objekt)
10   end
11
12   it "does something" do
13     MyKlass.do_something
14   end
15
16   it "does something again" do
17     MyKlass.do_something
18     MyKlass.do_something
19   end
20 end

And code lib/my_klass.rb:
1 class MyKlass
2   @@klass_var = nil
3
4   def self.do_something
5     if @@klass_var.blank? || @@klass_var.closed?
6       @@klass_var ||= OtherKlass.get_objekt
7     end
8   end
9 end

I cannot understand why closed? is reported to be an unexpected message, when it is stubbed in my spec file on line 6.
Many thanks in advance for your assistance!

A: In RSpec 3, you can use class_double, which allows you to create a double of a class. Combined with as_stubbed_const, you can replace the original implementation of a class:
RSpec.describe MyKlass do
  let(:objekt) do
    double(OtherKlass, closed?: 'NOT REALLY')
  end

  before do
    class_double(OtherKlass, get_objekt: objekt).as_stubbed_const
  end

  it 'does something' do
    MyKlass.do_something
  end
end

In Rspec 2 the following should work:
RSpec.describe MyKlass do
  let(:objekt) do
    double('OtherKlass', closed?: 'NOT REALLY')
  end

  before do
    fake_klass = Class.new
    fake_klass.stub(:get_objekt) { objekt }
    stub_const('OtherKlass', fake_klass)
  end

  it 'does something' do
    MyKlass.do_something
  end
end

A: Setting a class variable explicitly before each test solves the problem:
before(:each) do
  MyKlass.class_variable_set :@@klass_var, nil
end

Probably somebody can find a better solution, however this one has worked for me.


text:
Q: Laravel 4 shows no errors at all I have received a Laravel 4.1 codebase completely hacked, meaning Laravel standards aren't followed or used. The only thing used are routes, not even Eloquent is being used.
The scariest problem for the moment is this, when something breaks, at any level, I always receive a blank screen with the text:
@extends('layouts.page')

debug at app.php is set to true, I have error_reporting(E_ALL) in public/index.php, nothing gets written to the laravel.log (it can't be permissions problem as it's a Windows machine with Homestead).
I hope someone had this awful experience before and can help me on this.

A: First check your browser inspect element and see which status code are you receive. Then check your web-server access and error logs. If you dont understand the error where is from, check your composer file.
Finally give some more information about the structure of your customized laravel project.


text:
Q: Rename multiple files according to the given situation in cmd I have several files like the following:
fluxes_30.880_77.040
fluxes_30.880_77.050
fluxes_30.900_77.020

Here the numerical values are latitude and longitude.
I need to change the name of all the files in the form:
fluxes_30.88_77.04
fluxes_30.88_77.05
fluxes_30.90_77.02

Simply, I need the latitude and longitude values in two digits, How to rename all these in command prompt?

A: @echo off
setlocal EnableDelayedExpansion

for /F "tokens=2,3 delims=_" %%a in ('dir /B /A-D fluxes_*') do (
   set "lat=%%a"
   set "long=%%b"
   ren "fluxes_%%a_%%b" "fluxes_!lat:~0,-1!_!long:~0,-1!"
)

I don't think this simple code needs further explanations...


text:
Q: Proving that an SVM problem with a complex loss function is convex The end goal, along with proving that the problem is convex, is to be able to get the problem into a form that can be coded in CVX.
I have m positively
labeled data points $x_i$ $\in$ $\mathbb{R}^n, i = 1,2,...m$
and a negative class summarized by a random variabe
$x$ $\in$ $\mathbb{R}^n$ with mean $\hat{x}$ $\in$ $\mathbb{R}^n$, and covariance matrix C
The objective function is of the form: $\min_{w,b} L(w,b) + p(w)$
The loss function L(w,b) is a sum of: 1) the mean empirical hinge-loss error on the positive class; and 2) the worst case (w.r.t the class of
random variables x with mean $\hat{x}$ and covariance matrix C) mean error on the negative class
I.e. $L(w,b) =$ ${1}\over{m}$ $\sum_{i=1}^m (1 - x_i^Tw - b)_+ + sup_{x \sim (\hat{x},C)} E_x(1 - x_i^Tw - b)_+$
And the penalty function p(w) = $\lambda ||w||_1, \lambda \geq 0 $
I guess the obvious approach is to prove that the Hessian of the objective function is p.s.d, but I'm having trouble deriving the Hessian. Could anyone help me with how to proceed on this?


text:
Q: How to transition from activity 3rd to 1st? I have a problem with Shared Element Activity Transition between activities. I have MainActivity, it has a recyclerview with boxes (recyclerview.horizontal). Each box when clicked will go to the corresponding activity. The problem that appears when I click on a box, I switch to the second activity, in the second activity I press a button to switch to the third activity. And here I swipe to right to return to the MainActivity with transition and I want it to transition right to the box corresponding to the 3rd activity in the recyclerview in MainActivity. So, my purpose is:

MainActivity (Shared Element Activity Transition)-> Second Activity ->
  Third Activity (Shared Element Activity Transition)-> MainActivity
  (exactly scroll to position for Third Activity in RecyclerView).

My MainActivity
I hope everyone offer me the solution. Thank you so much.

A: You can use startActivityForResult instead of startActivity in SecondActivity when you are going to start ThirdActivity.Like this :
Intent i = new Intent(this, ThirdActivity.class);
startActivityForResult(i, 1);

And when you are finishing your ThirdActivity
Intent returnIntent = new Intent();
returnIntent.putExtra("activity_finish",true);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you use startActivityForResult() then it gives callback in the Activity who started it,so as soon as ThirdActivity finishes, it will return to the onActvityResult() in SecondActivity.Where you have to check result_code and request code like this :
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {
    if(resultCode == Activity.RESULT_OK){
        boolean isActivityFinish=data.getBooleanExtra("activity_finish");
         if(isActivityFinish){
          // finish your Second Activity here
          }

    if (resultCode == Activity.RESULT_CANCELED) {
        //Write your code if there's no result
    }
}

}
For more info : How to manage `startActivityForResult` on Android?


text:
Q: Nodes of a UK street by name of road AND town/city/county Is it possible to get nodes of a particular street of a particular town/city/county/country? This is not enough.
[out:json][timeout:25];
way["name"="Kennington Road"]; //all roads named such on the planet
//how do I limit it further?
// I know I can do add this
// way["name"="Kennington Road"](around:500,51.49595,-0.11124);
// that is OK but not ideal.

out body;
>;
out skel qt;

A: Rushed asking the question, if duplicate, please mark it so and happy to delete/remove it.
This is what I was looking for:
[out:json][timeout:25];
area[name="London"]->.a;

way(area.a)["name"="Kennington Road"]; // only roads contained in "london"

out body;
>;
out skel qt;


text:
Q: Adding rows after groupby condition is met I am trying to find the number of consecutive negative values of 20 rows or more for a column in a dataframe. However, once it groups in chunks of 20 or more, I want to add corresponding 30 rows of the original dataframe after each chunk.
This is my attempt (got help from a posted question here):
n = df['Slope'].lt(0)
mask = n.ne(n.shift()).cumsum()[n]
dfL = [g for i, g  in df.groupby(mask) if (len(g[g['Slope'] < 0]) >= 20)]
df_cn = pd.concat(dfL)

I get the chunks of consecutive negative values, but I do not know how to now add corresponding 30 rows after each chunk.

A: Please try to provide a minimal reproducible example next time and a small sample of the desired output
I created a random dfL of mine and it worked well
n = df['Slope'].lt(0)
mask = n.ne(n.shift()).cumsum()[n]
dfL = [g for i, g  in df.groupby(mask) if (len(g[g['Slope'] < 0]) >= 20)]

From here I created the code:
for x in range(len(dfL)): # dfL is reaturning a list of dfs with each chunk
  if len(dfL)>0: # here I want to be sure, that we have a chunk in the dfL
     df_cn= dfL[x] # selecting chunk from dfL
     print('Chunk: df_cn_' + str(x) + ' created') # feedback for testing
     idx=dfL[x].index # last index from chunk # since chunk size >=20, we need to be sure to get the last index of it.
     print('Chunk from ' + str(min(idx)) + ' to ' + str(max(idx)) + ' total ' + str(len(dfL[x]))+' indexes in the chunk') # feedback with size of chunk
     df_rest=df.loc[max(idx)+1:max(idx)+31] # get the next 30 rows from original df based on max index from last chunk
     df_cn_ext = pd.concat([df_cn, df_rest]) # concatenate (join on Y-Achse) the chunk and 30rows of original df, if the
     exec(f'df_cn_ext_{x}=df_cn_ext[:]') # creating separated dataframes trough suffixes for each chunk + 30 rows groups
     print('Dataframe df_cn_ext_' + str(x) + ' created from index ' + str(min(idx)) + ' to ' + str(max(idx)+31))
  else:
    print('no chunks in the df found')

Please note:
1- I've separated each chunk+30 rows in new dfs with suffixes (df_cn_ext_suffix)
2- If the last value of chunk is near the end of dfL, it won't add 30 rows, but the maximum number of rows available.
here some output of my code:
Chunk: df_cn_0 created
Chunk from 3 to 39 total 37 indexes in the chunk
Dataframe df_cn_ext_0 created from index 3 to 70
Chunk: df_cn_1 created
Chunk from 41 to 66 total 26 indexes in the chunk
Dataframe df_cn_ext_1 created from index 41 to 97


text:
Q: Uncaught OAuthException matter I'm building an application on Facebook, which gives me this error:

"Fatal error: Uncaught OAuthBaseException: An active access token
  must be used to query information about the current user. Thrown in
  /membri/mercatinoalto/base_facebook.php on line 1254"

when clicking a button that brings up a file inside it calls the file 'facebook.php'.
This file recalls another file, 'base_facebook.php':
...
require_once "base_facebook.php";
...
In 'base_facebook.php', at line 1254 I find this function:

   protected function throwAPIException ($ result) {
     $ e = new FacebookApiException ($ result);
     switch ($ e-> getType ()) {
         // OAuth 2.0 draft 00 style
       case 'OAuthException':
         // OAuth 2.0 draft 10 style
       case 'invalid_token':
         // REST server errors are just Exceptions
       case 'Exception':
         $ message = $ e-> getMessage ();
         if ((strpos ($ message, 'Error validating access token')! == false) ||
             (strpos ($ message, 'Invalid OAuth access token')! == false) ||
             (strpos ($ message, 'An active access token must be used')! == false)
         ) {
             $ this> destroySession ();
           }
         break;
       }

I can't find wher I'm going wrong.
Can you help me, please?

A: You need to pass a valid Access Token to be able to request user data.
See

*

*https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0

*https://developers.facebook.com/docs/facebook-login/access-tokens/


text: Q: How can I make this sprite cull at the nearest wall? Im working on a build-engine style unity game, and something regarding my explosion sprites has really been bugging me. My map is split into several pieces for both occlusion culling and my method for dimming certain sections. I want this explosion sprite to only render up until the nearest wall to its left and right, I thought that maybe sprite masks would work but I can't think of any way to implement this in code.


text:
Q: Error when running Access 2003 app in Access 2007 My organization is in the process of upgrading from Access 2003 to Access 2007. One of the apps I am tasked with upgrading is returning very odd errors while opening and closing forms that have nested forms. Have the events changed between Access 2003 and Access 2007 ? The events seem to be firing in a different order in 2007 then they did in 2003.

A: I haven't encountered the situation you described.  I can't find anything which mentions changes to forms event model.  Allen Browne has some information about Access 2007 compatibility with older versions:
http://allenbrowne.com/Access2007.html#Compatibility
The only problems I experienced so far with 2003 MDBs in Access 2007 were due to broken references.  If you haven't already done so, double-check yours (Tools-> References) from the VB editor.  While there, try Debug -> Compile to verify whether your code will compile without errors in Access 2007.
Tony Toews' Corrupt Microsoft Access MDBs FAQ could help fix or rule out odd behavior due to corruption:
http://www.granite.ab.ca/access/corruptmdbs.htm
If you've done those things, and still have problems with certain forms, it might be useful to create a new blank database and import those forms (and objects they depend on) into the new database.
Sorry to scatter-shot this thing.  It might help if you could provide more detail about the nature of the errors you're getting.


text:
Q: Customizing Android Progress bar I am trying to style android progress bar as shown below which have multiple sections in it.

Which properties need to be changed for that?
Here is my custom xml file.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background">
<shape>
  <corners android:radius="5dip" />
  <gradient
    android:angle="270"
    android:centerColor="@color/customeprogresscolor"
    android:centerY="0.5"
    android:endColor="@color/customeprogresscolor"
    android:startColor="@color/customeprogresscolor" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
  <shape>
    <solid android:color="@color/yellowCadmiumLight"/>
  </shape>
</clip>
</item>
</layer-list>


text:
Q: How can I communicate a service from a composed docker to another one? I have 2 different compose dockers that each one run the sames services, beeing redis, postgres and fastAPI.
Both of them works correct when trying to access each service, for example, the fastAPI from the "master container 1" can access normally it's postgres and it's redis, that are in other containers.
The same happens to the "master container 2".
But since I had to make them communicate with each other, I'm not beeing able to access one specific container of it.
I'm trying to do a request from the "master container 2"/container/fastAPI to the "master container 2"/container/fastAPI, but I get the error
{"detail":"HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /users/1 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f6a19dadf40>: Failed to establish a new connection: [Errno 111] Connection refused'))"}

I had to create a specific network for both master containers to stay in the same network, and they are because in the begging I had conflicts with postgres, but since this been solved, I can't do this specific request.
The code from the request:
 url = f'{user_api_url}/{user_id}'
        response = requests.get(url)
        user_dict = response.json()

docker-composer.yml - 1
version: '2'
services:
redis:
    image: sickp/alpine-redis:3.2.2
    restart: on-failure
    command: redis-server --port 6379 --protected-mode no
    ports:
        - "6379:6379"

postgres:
    image: postgres:14.3-alpine
    restart: on-failure
    environment:
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
        - PGPORT=5432
    ports:
        - '5432:5432'

fast_api:
    depends_on:
        - redis
        - postgres
    restart: on-failure
    build:
      context: ./
      dockerfile: Dockerfile
    volumes:
      - .:/user_api
    ports:
      - '8080:8080'
    expose:
        - "8080"
    environment:
        - POSTGRES_URL=postgresql://postgres:postgres@postgres:5432/postgres
        - REDIS_HOST=redis
        - REDIS_PORT=6379

networks:
    default:
        external:
            name: containers-shared

docker-compose.yml - 2
version: '2'
services:
redis:
    image: sickp/alpine-redis:3.2.2
    restart: on-failure
    command: redis-server --port 6389 --protected-mode no
    ports:
        - "6389:6389"

postgres:
    image: postgres:14.3-alpine
    restart: on-failure
    environment:
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
        - PGPORT=5442
    ports:
        - '5442:5442'

fast_api:
    depends_on:
        - redis
        - postgres
    restart: on-failure
    build:
        context: ./
        dockerfile: Dockerfile
    volumes:
        - .:/order_api
    ports:
        - "8090:8090"
    environment:
        - POSTGRES_URL=postgresql://postgres:postgres@postgres:5442/postgres
        - REDIS_HOST=redis
        - REDIS_PORT=6389
        - USER_API_URL=http://localhost:8080/users

networks:
    default:
        external:
            name: containers-shared

Seems to me that the problem is the "USER_API_URL", which I used localhost, but I'm not sure what IP/DNS should I put there, because the service that I want to access is in the other docker-composer.yml.
Running the project locally on the host machine, I don't get the error and everying works perfectly.


text:
Q: AS3 - Autosize button label text Is there a way in flash professional Actionscript3 to set button label with autosize?
I have many button on stage with different size and different label text on one line.
I want to auto-adapt size of entire label text inside my (all) button.
Thanks

A: Try this :
package
{
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextField;

    public class CreateButton extends MovieClip
    {
        public var btnBG: MovieClip;
        public var btn_text: TextField;

        public function CreateButton( btnName :String )
        {
            btn_text = new TextField();
            btn_text.text = ( btnName ) ? btnName : '';
            btn_text.autoSize = TextFieldAutoSize.LEFT;

            btnBG.width = btn_text.width;
        }

    }
}


text:
Q: Why does the text in console disappear on click? #include <iostream>
#include <string>
#include <windows.h>

using namespace std;
WORD setting1 = FOREGROUND_RED; // these are the user settings
WORD setting2 = FOREGROUND_RED;
WORD setting3 = FOREGROUND_RED;

WORD green = FOREGROUND_GREEN; // the 2 colors the settings can change from
WORD red = FOREGROUND_RED;

int changecolor(int key) //find out what the user pressed and then changed the color of the setting
{
    switch (key)
    {
    case VK_F1:
        if (setting1 == red)
        {
            setting1 = green;
        }
        else
            setting1 = red;
    case VK_F2:
        if (setting2 == red)
        {
            setting2 = green;
        }
    case VK_F3:
        if (setting3 = red)
        {
            setting3 = green;
        }
    }
}

WORD getconsoletextattributes(HANDLE hcon)
{
    CONSOLE_SCREEN_BUFFER_INFO bufinfo; // setting a screen buffer variable
    GetConsoleScreenBufferInfo(hcon, &bufinfo); // getting the console screen buffer and putting it into the bufinfo
    return bufinfo.wAttributes;
}

WORD setcolor(HANDLE hcon, WORD color)
{
    SetConsoleTextAttribute(hcon,color);
}

int main()
{
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    const int getcolors = getconsoletextattributes(hcon);

    while(true)
    {
        int key;
        for(key = 8; key < 190; key++)
        {
            if (GetAsyncKeyState(key))
            {
                changecolor(key);
            }
        }
        setcolor(hcon,setting1);
        cout << "Setting1 \n\n\n" << endl;
        setcolor(hcon,setting2);
        cout << "Setting2 \n\n\n" << endl;
        setcolor(hcon,setting3);
        cout << "Setting3 \n\n\n" << endl;

        Sleep(20);
        system("cls");
    }
}

I'm running Windows 10, using the codeblocks IDE with the GNU compiler.
I'm not used to the codeblocks IDE, but it's kind of small and my laptop doesn't have that much space.
So I'm trying to make a hack menu type thing, and what is supposed to happen is: it prints off some settings and when you push down F1-F3 it toggles the color from red to green (saying if the hack is on or off).
It works like its supposed to, but whenever I click on the console, my texts disappears. The only way it comes back, is if I re-build the program.
Does anyone know how to fix this problem ?


text:
Q: PHP | if stament always false I have a small problem with an if loop, I am building an appointment booking area, the directives are:

*

*Appointments can be made from Monday to Friday

*Appointment times: 11:00 - 13:00 and 15:00 - 18:00
the variables that take the value from the datepicker and timepicker are:
datepicker:
$app_to_data = $connessione->real_escape_string($_POST['data']);

timepicker:
$app_to_orario = $connessione->real_escape_string($_POST['orario']);

no problem to prevent the chosen day from being confirmed when the user chooses to book an appointment on Saturday or Sunday:
if(date('w', strtotime($app_to_data)) == 6 || date('w', strtotime($app_to_data)) == 0) {
    ?>
    <script type="text/javascript">
        var errore_appto = "<?php echo $id_pa ?>";
        window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
    </script>
<?php
exit;
}

the problem now comes when I have to initiate if cycles to check the time slot chosen for the appointment:
   /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 11:00*/
    if($app_to_orario < '11:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 13:00*/
    elseif($app_to_orario > '13:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 15:00*/
    elseif($app_to_orario < '15:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 18:00*/
    elseif($app_to_orario > '18:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

the problem I have is that if for example the user chooses to book an appointment for 16:00, the chosen time is correct, but I always get an error because for example in the second cycle 16:00 it is greater than 13:00 even if it falls correctly in the remaining 3 control cycles, so how do I perform a time check allowing the appointment in the time slots indicated in the question, without always running into a false result?

A: In your case, $app_to_orario is a string, not a DateTime. To compare with other date/time, it needs to be converted to DateTime first:
$ato = new DateTime($app_to_orario);

Or use Carbon:
$ato = new Carbon($app_to_orario);

Then compare the time(with Carbon):
if($ato->hour<11){
    ...
}

Or without Carbon:
if(intval($ato->format('H'))<11){
    ...
}

A: Please try below code:
if (str_replace(":", "", $app_to_orario) > str_replace(":", "", "11:00"))
{
}


text:
Q: Creating a new column by extracting values from dict in Pandas I have a data structure like this

name
targets
imp

Bob
{'codes':[3,4,6,199], 'region':'us', 'meta':''}
200

Diana
{'codes':[3,33,199], 'region':'us', 'meta':''}
100

I am trying to make the final results one more column of extracted codes in targets,  like this

name
targets
imp
targets.code

Bob
{'codes':[3,4,6,199], 'region':'us', 'meta':''}
200
[3,4,6,199]

Diana
{'codes':[3,33,199], 'region':'us', 'meta':''}
100
[3,33,199]

I tried doing
df['targets.code'] = df['targets'].apply(lambda x: x['codes'])

But it shows specifying on that line
[2022-01-14 19:53:33,660] {{taskinstance.py:1150}} ERROR - 'NoneType' object is not subscriptable

I really tried digging into a lot of posts but didn't find a solution. What am I doing wrong?

A: Looks like you have bad data (empty fields) in your source under "targets" column, because the following works:
df = pd.DataFrame([{'name': 'Bob', 'targets': {'codes':[3,4,6,199], 'region':'us', 'meta':''}}])
print(df)
#  name                                            targets
# 0  Bob  {'codes': [3, 4, 6, 199], 'region': 'us', 'met...

df['targets.code'] = df['targets'].apply(lambda x: x['codes'])
print(df)
#   name                                            targets    targets.code
# 0  Bob  {'codes': [3, 4, 6, 199], 'region': 'us', 'met...  [3, 4, 6, 199]

A: You can use pd.json_normalize:
df['targets.code'] = pd.json_normalize(df['targets'])['codes']
print(df)

# Output
    name                                            targets  imp    targets.code
0    Bob  {'codes': [3, 4, 6, 199], 'region': 'us', 'met...  200  [3, 4, 6, 199]
1  Diana  {'codes': [3, 33, 199], 'region': 'us', 'meta'...  100    [3, 33, 199]

You can also use a comprehension:
df['targets.code'] = [x['codes'] if x else [] for x in df['targets']]
print(df)

# Output
    name                                            targets  imp    targets.code
0    Bob  {'codes': [3, 4, 6, 199], 'region': 'us', 'met...  200  [3, 4, 6, 199]
1  Diana  {'codes': [3, 33, 199], 'region': 'us', 'meta'...  100    [3, 33, 199]
2   Test                                               None   50              []


text:
Q: In the "Fate" anime series, why is "hougu" translated as "Noble Phantasm"? In the Fate anime series, the word 宝具 "hougu", literally "precious tool", the special ability of the Servants, is translated as "Noble Phantasm". What are the reasons for translating it that way?
I don't mean to suggest that a literal translation is necessary, on the contrary, I am very much for free non-literal translations that keep as much context and associations from the source language as possible, even if you have to throw some aspects overboard for that.
But I just don't see which aspects this is supposed to translate. Any ideas?
Or is it just a case of "the translator had no idea how to translate it, so he/she just came up with something supposed to sound good"?

A: It could be argued that it's in fact not translated. Or at least, that it's not the choice of some random translator.
The term Noble Phantasm is apparently in the Japanese source material. Mind you, I don't have any of the original material and couldn't read it even if I had it. So I can't confirm any of this firsthand.
But I found a source online quoting the Fate/side material, a 100 pages side book that came out with Fate/stay night, including among other things a sort of encyclopedia.
There is an entry for "hougu" and directly underneath the following

ノウブル ファンタズム

which translates to Nouburu fantazumu -> Noble Phantasm.
So Type Moon chose this as the English reading/translation of "hougu". It seems they did this for many of the terms/names in Fate. Another example is Gilgamesh' Gate of Babylon, which in Kanji is called something like "King's riches".
In this case I would be tempted to actually go so far as to say that Type Moon did not provide a translation into English but rather "coined" the English terms they thought fitting.
It becomes obvious that the literal translation of the kanji into English makes for some lacklustre names. On the other hand some things just can't be properly translated because they don't have same meaning in a different cultural background.
So providing a translation that is not literal but focuses on the concept that you want to convey is a pretty good idea.
I don't know if Noble Phantasm is the best choice but at least the noble part always made sense to me because they are used by heroic spirits. The phantasm part might allude to them not actually being real but sort of a manifestation.
In the Fate/ series they make a point about how much of a heroic spirits power has to do with how famous and legendary they are. Same goes for their weapons. For example, I could mean that Saber isn't using Excalibur but a manifestation of Excalibur based on it's legend.
But only the author can answer what he really had in mind when he chose those translations.

A: Thanks to the effort of Sebastion_H of finding the link, looking at the description actually gives the reason for "Phantasm":

Noble Phantasm [Armament]
The armaments carried by Heroic Spirits, made from humanity's illusions.
Though they generally come in the form of things like swords, spears, or bows, there are also those Heroic Spirits whose Noble Phantasms are auxiliary armaments like shields, rings, or crowns.
  They are solidified "mysteries", and injecting them with magical energy while calling their true name will unleash their abilities.

So while 具 stands for the "armament" (one of the meanings when used a counter), the "Phantasm" stands for the aspect that it embodies the essence of the ideas and imaginations that mankind accumulated  about this particular Hero ("made from humanity's illusions", the   Japanese text is a bit more detailed).
That makes a lot of sense, but one needs to know this background to understand it.
In the same way (but that wasn't the problematic part, "Phantasm"), "Noble" of course evokes the "heroic" part of the Heroic Spirit.
So, it is a fair translation when one does know the background, and given the Japanese tendency to add English Furigana to such words, I wouldn't be surprised if this appeared as Furigana somewhere to actually add those aspects to the Japanese word. Which is then of course lost in translation (or when spoken).


text:
Q: From an R dataframe: count non-NA values by column, grouped by one of the columns I guarantee there is a simpler way to accomplish my goal.  I need to count the non-NA values of a data frame, grouped by one column in said data frame.  *This is my first question on stackoverflow, please be patient with me.
Here is my current code:
test data:
grouping <- c(1234,5678,2359)
column1 <- c('asdf',NA,NA)
column2 <- c(NA,'asdf','asdf')
column3 <- c('asdf',NA,'asdf')
litmus <- data.frame(grouping, column1, column2, column3)

get distinct list of groups:
distinct_groups <- as.data.frame(litmus %>% distinct(grouping))
length(distinct_groups$grouping)

perform loop to count non-NA values by grouping and put into a list
count_non_NA = list()
for (i in 1:length(distinct_groups$grouping)){
  count_non_NA[[i]]<-apply(litmus[grouping == as.numeric(distinct_groups$grouping[i]),], 2, function(x) length(which(!is.na(x))))}

input group names into list and convert to dataframe
names(count_non_NA) <- distinct_groups$grouping
count_non_NA <- as.data.frame(count_non_NA)
count_non_NA

A: I added a few extra observations so you can see how the grouping works as the example you provided there is only 1 observation per group.
library(dplyr)

grouping <- c(1234,5678,2359, 1234,5678,2359)
column1 <- c('asdf',NA,NA, 'asdf',NA,NA)
column2 <- c(NA,'asdf','asdf', NA,'asdf','asdf')
column3 <- c('asdf',NA,'asdf', 'asdf',NA,'asdf')
litmus <- data.frame(grouping, column1, column2, column3)

litmus %>%
  dplyr::group_by(grouping) %>%
  dplyr::summarise_at(vars(column1:column3), ~ sum(!(is.na(.))))

# # A tibble: 3 x 4
#   grouping column1 column2 column3
#   <dbl>   <int>   <int>   <int>
#   1234       2       0       2
#   2359       0       2       2
#   5678       0       2       0

A: We can use summarise_all
library(dplyr)
litmus %>%
   group_by(grouping) %>%
   summarise_all(funs(sum(!is.na(.))))

A: Can be simply
sum(!is.na(column name)) for each vector...
For a data frame using dplyr:
df%>%group_by(grouping_variable)%>%summarise("nonNAcol1"= sum(!is.na(col1name),

.....so on.for other columns)
There could more general solutions using apply functions on columns or seq_along columns for unknown number. Check SO for more and dplyr tutorials.
R4ds chapter 5.. http://r4ds.had.co.nz/transform.html
Cheers.


text:
Q: Skype doesn't find my audio input Skype doesn't find my audio input. If I click on the "Microphone" no other suggestions appears, my web camera works.
In windows everything works.

This is my audio preferences.

audio settings.

A: Under Sound Preferences, please post the "Hardware Tab" in order to check your profile, which should use at least an output + an input being in use. Otherwise, your hardware is not using the input profile which can be chosen right there.
This answer may be changed after your posting in order to give you further details. Here is a sample. Thank you.

Edit
Here is the conversation in the general chat room.

A: The only way I've found to make my internal mic work in my laptops is to use pavucontrol (install it from the homonymous package) and disabling the volume of a channel (the right or the left one), since most of microphones are mono in fact.
This is an huge workaround, by the way. I guess that this annoying bug should be fixed somewhere!

A: Make sure to use the latest Skype beta version for Linux from http://www.skype.com/intl/en/get-skype/on-your-computer/linux/. Older versions do not work properly with Pulse Audio. Also uncheck the "Allow skype to automatically adjust my mixer levels", it caused a lot of trouble for me. After that, reset all your mixer levels by opening a command-line and running alsactl init.


text:
Q: Why does a C++ mathematical operation accept a letter as an input and output a number? I'm brand new to c++, so maybe this is a stupid question, but I coded a very simple temperature conversion program. It looks like this:
#include <iostream>

int main() {

  double tempf;
  double tempc;

  // Ask the user
  std::cout << "Enter the temperature in Fahrenheit: ";
  std::cin >> tempf;

  // Conversion
  tempc = (tempf - 32) / 1.8;

  // Print Output
  std::cout << "The temp is " << tempc << " degrees Celsius.\n";

}

This compiles and runs fine when I enter an integer/float as an input. However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind. Instead, after compiling, I get this output:
$ g++ temperature.cpp -o temp
$ ./temp
Enter the temperature in Fahrenheit: abc
The temp is -17.7778 degrees Celsius.

Can someone tell me where the executable is getting the output -17.7778 from? This seems like an arbitrary number, not a mathematical output.

A: "However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind."
By default, std::cin reports errors by setting internal error bits that must be checked manually. One mechanism is to use the good() member function to check for any error bits. Another is to use the bool conversion operator which does the same thing, it will convert to true is no error bits are set, otherwise it converts to false.
Example :
if(!std::cin) {
    std::cout << "Input error!";
    return;
}

When std::cin fails, it will assign the value 0 to the variable.
From cppreference.com :

If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set.

When you provide the input "abc" the expression std::cin >> tempf; will fail to read anything, assign 0 to tempf and set a fail bit. Then, during tempc = (tempf - 32) / 1.8; the value calculated will be (0.0 - 32) / 1.8 which is approximately -17.7778 which is the result you observe.
You can change the default behavior to throw an exception on failure by using the exceptions member function. But beware that if other parts of your project use std::cin and don't expect this change it can disrupt their error handling scheme which may rely on checking error bits.
The example provided by cppreference.com for this example :
#include <iostream>
#include <fstream>

int main()
{
    int ivalue;
    try {
        std::ifstream in("in.txt");
        in.exceptions(std::ifstream::failbit); // may throw
        in >> ivalue; // may throw
    } catch (const std::ios_base::failure& fail) {
        // handle exception here
        std::cout << fail.what() << '\n';
    }
}


text:
Q: Questions about Levy measure in the canonical representation of infinitely divisible distributions Let $X$ be a random variable with infinitely divisible and symmetric distribution $F$ distributed on $\mathbb{R}$.
It is well known that the characteristic function of $X$ has  a canonical representation of the form:
\begin{align}
\phi(t)=e^{  -\frac{\sigma^2}{2}t^2-\int_{-\infty}^\infty (1-cos(tx) ) dV(x)}
\end{align}
where $V$ is a non-negative  measure  such that $V(\{0\})=0$ and $\int_{-\infty}^\infty \min(1,x^2) dV(x)<\infty$.
The measure $V$ is called Levy measure and here we are interested in its properties.
My questions are:

*

*Under what condition on $F$  is $V$ an absolutely continuous measure? For example, is absolute continuity of $F$ enough?

*Can we say anything about $V$ based on the tail behavior of $F$?

*Can we say anything about $V$ based on the tail behavior of $\phi(t)$?

*I know it is generally difficult to determine $V$ but what can generally be said about $V$ from basic properties of $F$ and $\phi(t)$?
Also, any good reference would be appreciated.

A: I would discuss your questions partially under the following condition:
$$ \int_{-\infty}^\infty x^2\,dF(x)<\infty, \tag{1}$$
or equivalently $\varphi^{\prime\prime}(0)$ exists and finite or $\int_{-\infty}^\infty y^2\,dV(y)<\infty$. Let $K(x)\triangleq\int_{-\infty}^x y^2\,dV(y)<\infty$, it is easy to obtain the following expressions:
\begin{gather}
-(\log\varphi(t))^{\prime\prime}=\sigma^2+\int_{-\infty}^{\infty}\cos(tx)dK(x),\\
-\lim_{T\to\infty}\frac1{2T}\int_{-T}^T (\log\varphi(t))^{\prime\prime} dt =\sigma^2,\\
\psi(t)\triangleq -(\log\varphi(t))^{\prime\prime}-\sigma^2=\int_{-\infty}^\infty \cos(tx)\,dK(x).\tag{2}
\end{gather}
Now from the inversion formula of characteristic functions we have following conclusion: Under (1),
\begin{gather} \int_{-\infty}^\infty|\psi(t)|\,dt<\infty \quad\Rightarrow\quad
dK(x)\ll d\lambda\quad \Rightarrow \quad dV(x)\ll d\lambda\;(\text{$V$ has density})\\
\begin{aligned}\int x^{2n}dF(x)<\infty \quad &\Rightarrow \quad \varphi^{(2n)}(0)\; \text{exists and finite}\\
&\Rightarrow \quad \psi^{(2n)}(0)\; \text{exists and finite}\\
&\Rightarrow \quad \int x^{2n}\,dV(x)<\infty, \qquad n\in\mathbb{N}
\end{aligned}
\end{gather}


text:
Q: Can the  element be used to animate individual page elements in a nuxtjs application? Can someone tell me if the transition element can be used on page elements for animations in nuxt? I have seen the doc regarding page transitions, but I want to animate a number of different page elements. What I have so far does not appear to be working.
In a simple Header component, I have this:
<template>
<transition name="menu-popover">

Payments

Subscriptions

Connect

</transition>

And in the style tag of that component:


text:
Q: Displaying selected data while Xml parsing in android public class MyXMLHandler extends DefaultHandler {

Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;

public static SitesList getSitesList() {
    return sitesList;
}

public static void setSitesList(SitesList sitesList) {
    MyXMLHandler.sitesList = sitesList;
}

/** Called when tag starts ( ex:- <name>AndroidPeople</name>
 * -- <name> )*/
@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {

    currentElement = true;

    if (localName.equals("student_response"))
    {
        /** Start */
        sitesList = new SitesList();
        //sitesList.setquizno(currentValue);
    }

}

/** Called when tag closing ( ex:- <name>AndroidPeople</name>
 * -- </name> )*/
@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {

    currentElement = false;

    /** set value */

    if(localName.equalsIgnoreCase("quiz_one"))
    {

    if (localName.equalsIgnoreCase("quiz_no"))
        sitesList.setquizno(currentValue);
    //if(Integer.parseInt(sitesList.getquizno().get(Integer.parseInt(currentValue)))==1)
    //{

    /*else if (localName.equalsIgnoreCase("subject"))
        sitesList.setsubject(currentValue);
    else if (localName.equalsIgnoreCase("grade"))
        sitesList.setgrade(currentValue);
    else*/else  if (localName.equalsIgnoreCase("question_no"))
        sitesList.setquestionno(currentValue);
     else if (localName.equalsIgnoreCase("question"))
            sitesList.setquestion(currentValue);
        else if (localName.equalsIgnoreCase("option1"))
            sitesList.setoption1(currentValue);
        else if (localName.equalsIgnoreCase("option2"))
            sitesList.setoption2(currentValue);
         else if (localName.equalsIgnoreCase("option3"))
                sitesList.setoption3(currentValue);
            else if (localName.equalsIgnoreCase("option4"))
                sitesList.setoption4(currentValue);
            /*else if (localName.equalsIgnoreCase("option5"))
                sitesList.setoption5(currentValue);*/
            else if (localName.equalsIgnoreCase("correct_answer"))
                sitesList.setcorrectans(currentValue);

            /*else if (localName.equalsIgnoreCase("explaination"))
                sitesList.setdescription(currentValue);
            else if (localName.equalsIgnoreCase("remark"))
                sitesList.setremark(currentValue);*/
    }
}

/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
 * -- to get AndroidPeople Character ) */
@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {

    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }

}

}
Using the above code i have parsed the xml file in android .
Following is my xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<student_response>

<info>

<quiz_one>
<quiz_no>1</quiz_no>
<subject>general</subject>
<grade>A</grade>

<all_question>
<question_frame>
<question_no>1</question_no>
<question>What is capital of india ?</question>
<option1>Delhi</option1>
<option2>Mumbai</option2>
<option3>Chennai</option3>
<option4>Benglore</option4>
<option5>Kolkata</option5>
<correct_answer>Delhi</correct_answer>
<explaination>Delhi is capital of india....</explaination>
<remark>capital of india </remark>
</question_frame>

<question_frame>
<question_no>2</question_no>
<question>Who is the founder of facebook ?</question>
<option1>James Goslings</option1>
<option2>Dennis Ritchie</option2>
<option3>Bjarne Stroustrup</option3>
<option4>Brian Kernighan's</option4>
<option5>Mark Zuckerberg</option5>
<correct_answer>Mark Zuckerberg</correct_answer>
<explaination>Mark Zuckerberg:facebook </explaination>
<remark>facebook</remark>
</question_frame>

<question_frame>
<question_no>3</question_no>
<question>Who is the current prime minister of india ?</question>
<option1>Pratibha patil</option1>
<option2>Dr. Manmohan singh</option2>
<option3>Rajiv Gandhi</option3>
<option4>Atal bihari vajpayee</option4>
<option5>Moraraji Desai</option5>
<correct_answer>Dr. Manmohan singh</correct_answer>
<explaination>Dr. Manmohan singh:current P.M. </explaination>
<remark>Prime Minister</remark>
</question_frame>

<question_frame>
<question_no>4</question_no>
<question>What does EPROM stand for?</question>
<option1>Electric Programmable Read Only Memory </option1>
<option2>Erasable Programmable Read Only Memory </option2>
<option3>Evaluable Philotic Random Optic Memory</option3>
<option4>Every Person Requires One Mind</option4>
<option5>Evaluable Philotic Random Optic Memory</option5>
<correct_answer>Erasable Programmable Read Only Memory </correct_answer>
<explaination>EPROM  stand for Erasable Programmable Read Only Memory </explaination>
<remark>EPROM</remark>
</question_frame>

<question_frame>
<question_no>5</question_no>
<question>Where is the headquarters of Microsoft located?</question>
<option1>Santa Clara, California </option1>
<option2>Tucson, Arizona </option2>
<option3>Richmond, Virginia </option3>
<option4>Redmond, Washington</option4>
<option5>Tucson, Arizona </option5>
<correct_answer>Santa Clara, California </correct_answer>
<explaination>headquarters of Microsoft : Santa Clara, California </explaination>
<remark>Microsoft</remark>
</question_frame>
</all_question>
</quiz_one>

<quiz_two>

<quiz_no>2 </quiz_no>
<subject>Other topic</subject>
<grade>A</grade>

<all_question>
<question_frame>
<question_no>1</question_no>
<question>Who is the current prime minister of india ?</question>
<option1>Pratibha patil</option1>
<option2>Dr. Manmohan singh</option2>
<option3>Rajiv Gandhi</option3>
<option4>Atal bihari vajpayee</option4>
<option5>Moraraji Desai</option5>
<correct_answer>Dr. Manmohan singh</correct_answer>
<explaination>Dr. Manmohan singh:current P.M. </explaination>
<remark>Prime Minister</remark>
</question_frame>

<question_frame>
<question_no>2</question_no>
<question>What does EPROM stand for?</question>
<option1>Electric Programmable Read Only Memory </option1>
<option2>Erasable Programmable Read Only Memory </option2>
<option3>Evaluable Philotic Random Optic Memory</option3>
<option4>Every Person Requires One Mind</option4>
<option5>Evaluable Philotic Random Optic Memory</option5>
<correct_answer>Erasable Programmable Read Only Memory </correct_answer>
<explaination>EPROM  stand for Erasable Programmable Read Only Memory </explaination>
<remark>EPROM</remark>
</question_frame>

<question_frame>
<question_no>3</question_no>
<question>Who is the founder of facebook ?</question>
<option1>James Goslings</option1>
<option2>Dennis Ritchie</option2>
<option3>Bjarne Stroustrup</option3>
<option4>Brian Kernighan's</option4>
<option5>Mark Zuckerberg</option5>
<correct_answer>Mark Zuckerberg</correct_answer>
<explaination>Mark Zuckerberg:facebook </explaination>
<remark>facebook</remark>
</question_frame>

<question_frame>
<question_no>4</question_no>
<question>Where is the headquarters of Microsoft located?</question>
<option1>Santa Clara, California </option1>
<option2>Tucson, Arizona </option2>
<option3>Richmond, Virginia </option3>
<option4>Redmond, Washington</option4>
<option5>Tucson, Arizona </option5>
<correct_answer>Santa Clara, California </correct_answer>
<explaination>headquarters of Microsoft : Santa Clara, California </explaination>
<remark>Microsoft</remark>
</question_frame>

<question_frame>
<question_no>5</question_no>
<question>What is capital of india ?</question>
<option1>Delhi</option1>
<option2>Mumbai</option2>
<option3>Chennai</option3>
<option4>Benglore</option4>
<option5>Kolkata</option5>
<correct_answer>Delhi</correct_answer>
<explaination>Delhi is capital of india....</explaination>
<remark>capital of india </remark>
</question_frame>
</all_question>

</quiz_two>

</info>
</student_response>

My Question is how to parse only 1 block of data from xml in android. Example from if i want to fetch only 1 quiz at time how i can do it.Please help me

A: you can add elements to the Adapter of your list and run getAdapter().notifyDatasetChanged(), this will trigger the list refresh

A: If we want to extract the data from a xml file once we have to move to SAX, which is one time top to bottom read approach and if we want ot randomly pick the data in an xml file then the tree reperesentation of DOM model is to be put into use.
You can use DOM Parser for your code. ok


text:
Q: TypeError when trying to create a Document Set with JSOM I am attempting to create a document set in sharepoint online using JSOM triggered by a button. I've found the guides referenced here on the subject, but I can't seem to find the issue in my code.
When trying to execute the query its throwing the error:
msajaxbundle.js:1 Uncaught TypeError: Cannot read property 'apply' of undefined
It seems like the Async query is failing, but im not sure why. I have also tried using list level content types and site level types with the appropriate methods for that level.
Lifeline.Functions.createCase = function(){
    context = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
    var listId = '7BC07117AE-8792-43DE-984A-D6EA2A533B6C';
    list = context.get_web().get_lists().getById(listId);
    var docSetName = "Projection Case: Please Work ";
    list = context.get_web().get_lists().getById(listId);

    context.load(list);
    console.log("list loaded");

    var parentFolder = list.get_rootFolder();
    context.load(parentFolder);
    console.log("parent folder loaded")

    var docSetContentTypeID = "0x0120D520";
    var docSetContentType =  context.get_site().get_rootWeb().get_contentTypes().getById(docSetContentTypeID);
    context.load(docSetContentType);
    console.log("doc set content type loaded");
    context.executeQueryAsync( function(){
        console.log("doc set content query executed");

        Sp.DocumentSet.DocumentSet.create(context, parentFolder, docSetName, docSetContentType.get_id());
        context.executeQueryAsync(successHandler(), function logerror(sender,args){
            console.log(args.get_message());
        });
    },
    Function.createDelegate(this, this.onQueryFailed));
};
function successHandler(){
alert("Document Set successfully Created");
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

A: So I wasn't able to fix the code to resolve the error. However I was able to get this working using an alternate method that seems much simpler. Hopefully it will help those who are also having difficulty executing this using DocumentSet.DocumentSet.create method
Lifeline.Functions.createCase = function(itemid) {
var docSetName = "my document set name";
var context = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
var list = context.get_web().get_lists().getById('LIST GUID');
var item;
context.load(list);

var itemCreateInfo = new SP.ListItemCreationInformation();
itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
itemCreateInfo.set_leafName(docSetName);

item = list.addItem(itemCreateInfo);
item.set_item("ContentTypeId", "0x0120D52000307A54BE1A445A44813BEDE85E22CADB");
item.set_item('Title', docSetName);
item.set_item('DocumentSetDescription', "This is test 3 an automatically generated description");
item.set_item('ChartIdlookup', itemid);

item.update();
context.load(item);
context.executeQueryAsync(
    function() { console.log("document-set created!");} ,
    function(sender,args) { console.log("Error: " + args.get_message()); }
);

}


text:
Q: separating data from array mainstr is my string contains:
 123;456;23;ns@234;343;3;ner@975;013;742;av@

arr is my array name.
each location of array contains some string like (should be separated by @)
arr[0]=[123;456;23;ns];

arr[1]=[234;343;3;ner];

I want to separate each element of arr[0] into separate array (they should be separated based on occurrence of ;
)..
for example
newarray[0]=[123]

newarray[1]=[23]

newarray[2]=[45]

newarray[3]=[ns]

how should I do this ?

A: You can use the firstly
NSArray *stringArray = [mainstr componentsSeparatedByString:@"@"];

then you can use
NSArray *arr0 = [[stringArray objectAtIndex:0] componentsSeparatedByString:@";"];
and so on...


text:
Q: Excel web access web part loading twice I have an excel workbook which contains Power View sheet which I want to include in my SharePoint online site. So I used excel web access web part to include the Power View chart.
But the problem is the chart loads twice. And the performance is also very bad, it takes too much time to load.

A: The Power View sheet loads only once but it does that in 2 steps. First the web part loads (you might see the blue spinner) and then the Power View sheet loads within the web part (you should see the blue spinner). The performance is a known issue. Reducing the size of the excel workbook data model will reduce the power view sheet loading time.


text:
Q: Area under UINavigationBar does not respond to taps when frame is moved offscreen I currently have a navigation controller with a UINavBar within my view controller. I hide the navbar by changing the frame x position to a negative value. This hide's the navbar but the area under the navbar no longer responds to touch input. How can I fix this?

A: You could hide the navigation controller with
[self.navigationController setNavigationBarHidden:YES animated:YES];

That way your view will resize.

A: An easier (and more intuitive) way is to simply modify the View Controller settings. You can remove the NavBar by going to the Utilities menu, selecting the Attributes Inspector, and then setting "Top Bar" to None. Be sure you have the right View Controller selected in the Storyboard.
Obviously this won't do you any good if you're not using a storyboard. In that case, use Danilo's solution.


text:
Q: Add another worksheet in an Excel worksheet Is it possible to include an additional set of worksheets (i.e. "tabs") into an already existing worksheet in Excel?

A: Yes - 2 simple ways:

*

*Right click any tab and select Insert... and then select Worksheet

*From the menu bar select Insert and then Worksheet
As per the comment made to your initial post these sorts of questions are better asked on superuser.com


text:
Q: Double Animation, .stop() Not Fixing It For some reason, I can't figure out how to stop the double animation in the following script:

When you click on .newsNav.forward too quickly, multiple .newsItems appear, instead of just one. As you can see, I'm aware that .stop(); is supposed to fix this, but I can't figure out why it's not working.
HTML if it's relevant:

    <
    >

Latest News

First News Item

Second News Item

Third News Item

Relevant CSS as well:
#contentWrapper #content #news #newsSlider p.newsItem {
        display: none;
    }

    #contentWrapper #content #news #newsSlider p.newsItem.active {
        display: block;
    }

A: You are only stopping the animation of certain classes. To achieve a "global" stop in animation, you will have to clear the animation queue for all elements that will be potentially animated in your JS function.
This will mean doing something along the line of:
$(document).ready(function() {
    var activeNews = "01";
    $(".newsNav.forward").click(function(event) {
        event.preventDefault();

        // Pre-emptively stops all animation
        $(".newsItem").stop(true, true);

        // Note the removal of the .stop() method before each animation
        if (activeNews == 01) {
            $(".newsItem.01").fadeOut(250, function() {
                $(".newsItem.02").fadeIn(250);
            });
            activeNews = 02;
        } else if (activeNews == 02) {
            $(".newsItem.02").fadeOut(250, function() {
                $(".newsItem.03").fadeIn(250);
            });
            activeNews = 03;
        } else if (activeNews == 03) {
            $(".newsItem.03").fadeOut(250, function() {
                $(".newsItem.01").fadeIn(250);
            });
            activeNews = 01;
        }
    });
});


text:
Q: As soon as I increase the limit from the psql DB, axios fails. Why? I have a function that reaches out into the DB, gets a record and verifies it. The verification process happens with an API via Axios. (See code at the end).
The limit of records requested from the DB is set to 50. When it is set to 10, the code works fine.
However, anything above 30, I get the following error:
const status = res.data.data.status; TypeError: Cannot read properties of undefined (reading 'data')
I want to stress that Axios works 100% perfectly when the limit is 10. Although, at the end of running 10, my DB says too many connections for role "DBNAME"
Am I doing something wrong?
const verify = async () => {
    console.log("Reading data from DB for verification...");
    await pool
        .query(
            `
        SELECT * FROM main_leads
        WHERE hunter_uploaded = FALSE
        AND email_sent = 'false'
        AND verification is NULL
        limit 50
  `
        )
        .then((data) => {
            const emails = data.rows.map(async (x) => {
                await axios({
                    method: "GET",
                    url: `Verify`,
                })
                    .catch((err) => {
                        console.log(err.message);
                    })
                    .then(async (res) => {
                        console.log(res.data.data);
                        const status = res.data.data.status;
                        //
                        console.log(status);
                        console.log(`${res.email}:` + " " + res.status);
                        //
                        await pool.query(
                            `UPDATE main_leads
                             SET domain_processed = TRUE, verification = $1
                             WHERE ID = $2`,
                            [status, x.id]
                        );
                    });
            });
        });
};

verify();


text:
Q: Jquery Validate minlength with depends not firing I am trying to validate the length of input based on the value of a drop down. I cannot get it to work when I add a depends to the minlength, but it does work with a fixed value. This works :
CardNumber: {
  required: {
    depends: function(element){
      return $('input[name=PaySelect]:checked').val() == "0";
    }
  },
  minlength: 14
},

But this does not :
CardNumber: {
  required: {
    depends: function(element){
      return $('input[name=PaySelect]:checked').val() == "0";
    }
  },
  minlength: {
    depends: function(element){
      var paymeth = $('select[name="PayMethod"]').val();
      if (paymeth == 'American Express') {
        return 14;
      } else {
        return 16;
      }
    }
  }
},

If I put alert(); in I can see the code firing, but on the page it never warns the user that their input is too short and it allows the page to proceed onwards. What am I doing wrong?

A: you need to remove depends from minlength property, as minlength returns minimum number of characters required, you can directly check your conditions and return appropriate number directly, like:
...
minlength: function () {
    var paymeth = $('select[name="PayMethod"]').val();
    if (paymeth == 'American Express') {
        return 14;
    } else {
        return 16;
    }
}


text:
Q: What is the need to represent the integer value in three different numbering systems? Eg:
// The number 26, in decimal
int decVal = 26;

// The number 26, in hexadecimal
int hexVal = 0x1a;

// The number 26, in binary
int binVal = 0b11010;

A: Don't get me wrong, but you could as well ask: why are we using Object Oriented programming concepts; such as classes and objects; when we could write down all programs using assembler?
The simple answer is: (as any other language, too) programming languages are means to express ideas. The designers of those languages add features that they deem to be helpful to those people that will write down source code in the end.
And as you probably know: as soon as you get closer to the "hardware side" of things; bits become important. Many algorithms work on bitwise data; or on bytewise data. Thus there is a certain need to be able to express binary, octal or hex values in simple ways.
Maybe, maybe, when your development work happens high up in the stack, then you think only in terms of EJBs, JSON data, XML, and all that "binary" stuff seems far away. But as said; that stack has a "bottom" end as well (or a networking side); and there bits and bytes are deemed so important, that Java, like many other programming languages has distinct means to express the corresponding values.


text:
Q: Need help for WordPress User Session Management? I need help regarding WordPress session management. Follow these steps::
Bug: Session management and break authentication.
Steps to reproduce:

*

*Log in to your account using browser 1.

*Now, login to the same account using browser 2.

*Change the password in browser 1.

*Refresh in the browser 2 nothing will happen account remains logged in.
If this bug is not present than account must log out automatically when the browser 2 is refreshed.
It is a medium severity bug.
What will be the solution? Thanks

A: I have gone through the above case. I have checked when you change password you will have the option of logout every where else. So you need to check it.
https://www.screencast.com/t/0tilp5u2
I will explain it the reason for the same. In this when you login into wordpress.The details are saved in the form of cookies into your browser in form of sessions. However on selecting above button you will be clearing all the session of the website.
If you do not do it there will be session on the system so you will not be logged out on another browser


text:
Q: Nginx and Apache running at same port there are projects running on apache and nginx.
as workaround, I set apache to run at port 80 while nginx at port 8000
How can I make nginx and apache to run the applications at similar port 80?
here is a simple scenario

*

*myserver.com/apache1

*myserver.com/apache2

*myserver.com:8000/nginx1

*myserver.com:8000/nginx2

is it possible to set a rule that if requests are for /nginx1 or /nginx2, apache will transfer request to nginx on port 80? or vice versa?
thanks.

A: base from reply of alvits and Kashyap, I have no other choice but to keep on setting both webserver to different ports


text:
Q: Is it possible to stop vim redrawing for every action in a key binding? This is purely a visual thing (vim is working properly), but with some key-mappings I have vim set to do multiple operations, eg.
eg, move the selected block up/down with alt j/k.
vmap <M-j> Vxp`[v`]
vmap <M-k> VxkP`[v`]

This works well but redraws for each operation which is a bit distracting.
So my question is:
Is it possible to set a key-binding to not redraw until the operation is complete?

A: I think that you are looking for
:help 'lazyredraw'


text:
Q: 'then' vs 'and-then' Z3 combinator In Z3 and-then and then and both valid combinators.  What's the difference, if any?  and-then gives the following message from (help-tactic):
- (and-then <tactic>+) executes the given tactics sequencially.

However, then doesn't seem to be defined anywhere.

A: There is no difference. If we grep for "then" or "and-then" in the Z3 source tree, then we find that these strings occur only once and they're synonyms:
grep -rE '"and-then"|"then"'
src/cmd_context/tactic_cmds.cpp:        if (cmd_name == "and-then" || cmd_name == "then")


text:
Q: Is there a plugin for VSCode to "learn" most used snippets? I'm a frequent user of VS Code, and I find a little bit annoying the fact that when I'm using code snippets VS Code suggest me things I really don't use. For example, if I input d, VS suggest whatever instead of div.
Is there a plugin for that? a plugin to let VS Code to "learn" what I use the most?

A: You can change the settings to put snippet suggestions on top. Settings --> Suggestions --> Snippet Suggestions or just add "editor.snippetSuggestions": "top" to settings.json(click the two curly braces at the top).
You can also change what is pre-selected in  "suggest selection"