text:
Q: HTML: How to change the size of a button so that it has the same size as the icon on it? I created a button using the help of https://www.css3buttongenerator.com.  I'm now trying to resize the button on my html so that the icon on the button fits on it  perfectly. I want both of them to be the same size so to say. but that webpage is not really helping me.
This is what my code looks like.
HTML:
<button class="butn"></button>

CSS:
.butn {
  color: #859f38;
    background-color:transparent;
     background-size: 30px !important;
    width: 22px !important;
    height: 22px !important;
  text-decoration: none;
    border: none;
     outline: 0 !important;
}

I've been playing with the values on the .css and changing/adding stuff, but no success so far . How can I do it?

A: use
#icon {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
  }

A: try:
<button class="butn"></button>

.butn {
   color: #859f38;
   background-color:transparent;
   text-decoration: none;
   border: none;
   outline: 0 !important;
}

or use @sao 's answer if you want to resize the icon


text:
Q: How do I close the application when I click the cross in the title bar when I have several forms? I have searched through stackoverflow and has found similar question.
As I am still a beginner in C# programming, I could not quite understand what the solutions meant.
I have a c# windows form application that has several forms.
As it only closes when I closes the main form, how do I code it such that when I close other form the application closes as well?
EDIT: most people has told me to code it in the closing event. may i know where is the event found at? thanks.

A: Not sure why you think out answers will be any easier than ones you have found already but..
A Form has an event called "Closing" (See Here). You should handle the event and then inside that function you can use the following line to close your application...
System.Windows.Forms.Application.Exit();

NOTE: This is for a WinForms application
EDIT:
You can register the closing event using VS designer mode like this...

*

*Select the form

*Go To the "Events" window

*Double click the "Closing" event option

More detailed answer here
(Google if you cannot work this out)
or you can register the event in code like this...
//In Form constructor function
this.Closing += new EventHandler(Form1_Closing);

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   //Handle event here
   System.Windows.Forms.Application.Exit();
}

A: In WPF you can call Application.Current.Shutdown to close the application.
Register in your window to the Window.Closed-Event and call Application.Current.Shutdown()
Update
For Winforms, use the FormClosedEvent or override OnFormClosed. As alreads written by others, use Application.Exit to terminate the app.
WPF stands for Windows Presentation Foundation and is a framework for building nice user interfaces

A: Its very simple. Use the following code if you want to exit from the application from any point of time.
Application.Exit();

A: Check out Application.Exit Method

Informs all message pumps that they must terminate, and then closes
  all application windows after the messages have been processed.

There is also an overload that allows forms receiving the quit event to inform it wants to cancel.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass a surface in Android to native code? I'd like to work with the Native Window, so I'm trying to call ANativeWindow_fromSurface, but it needs a jobject for the surface. I'm assuming the best way to do this would be to pass this in when onSurfaceCreated is called, i.e.:
public class RendererWrapper implements Renderer {
     @Override
     public void onSurfaceCreated(GL10 gl, EGLConfig config) {
     // (Some sort of code that would create a surface object)

     //This is a native function that will use ANativeWindow_fromSurface
     cOnSurfaceCreated(surface);
}

But I don't know what specific object I should be using nor how to access it.
Edit: I'm trying to do something like the NativeWindow API in this example: https://vec.io/posts/how-to-render-image-buffer-in-android-ndk-native-code so I can write directly to the screen from native c code,.

A: Simply put, you need to be passing it a Surface.  I would expect your onSurfaceCreated() method to be called after the Surface was created, so I'm not quite understanding the structure of the code you're showing.
If you're working with a SurfaceTexture, see the answer to this question.


text:
Q: How to calculate Mean Time Between Failure (MTBF) using SQL Given Issue Raised day and count, how can we come up with the calculation of Datediff, and the output table with MTBF for each month? Thanks a lot.
Raw data
Issue Raised | Count | Datediff
1/12/22         1      12
2/23/22         1      42
4/1/22          2      37
4/7/22          1      6

Output table
Month | MTBF
Jan     12/1=12
Feb     42/1=42
Mar
Apr     (37+6)/(2+1)=14.33

A: As mentioned you could use a group by function to aggregate by month, year and then do your calculations.  Here is something that might work for you, however I am uncertain of your DBMS.
  SELECT
 FORMAT(ISSUERAISED, 'MM-yyyy') AS Month_Year
      ,SUM("Count") AS "Count"
      ,SUM("DateDiff") AS "DATEDIFF"
      , SUM(CAST("DateDiff" AS DECIMAL(7,4))) / SUM(CAST("Count" AS DECIMAL(7,4))) AS MTBF
  FROM YOURTABLE

  GROUP BY  FORMAT(ISSUERAISED, 'MM-yyyy')


text:
Q: Netlogo - random choice I am new to programming and I would really appreciate the help.
In this model, I want to create a company that can randomly choose btw 2 choices if a certain condition is met. What would be the best way to do it?
I tried this but it is not working.
    if profit < 0 [
set color red
let choice random 2 (
  choice = 0 [ move-to min-one-of patches [costs]]
  choice = 1 [ set price (price + 1) ])
]

Thanks for the help!

A: Looks like you need an IFELSE statement. Like IF, IFELSE evaluates a test, an expression that should produce either TRUE or FALSE. IF runs the code block when the test produces TRUE. IFELSE has two code blocks. The first will run when the test is TRUE, the second will run when the test is FALSE.
You could also use two IF statements, if you wanted to.
TWO IFs (Sequential IFs)
let choice random 2
if (choice = 0) [ action-1 ]
if (choice = 1) [ action-2 ]

IFELSE
let choice random 2
ifelse (choice = 0)
[ action-1 ]
[ action-2 ]

Note that here we only need one test: (choice = 0), because there are only two options. If choice is not 0, then it must be 1.
IFELSE (more than two options)
If there were more than two options, then we can use another form of ifelse that lets us use multiple tests. This form must be entirely wrapped in ( and )
let choice random 4
( ifelse
 ( choice = 1 ) [ action-1 ]
 ( choice = 2 ) [ action-2 ]
 ( choice = 3 ) [ action-3 ]
                [ action-4 ] ;; default
)


text:
Q: Same color is displayed differently on CCLabel and CCSprite in CocosSharp (Cocos2D) I'm using CocosSharp in Xamarin to display a label (CCLabel) and a sprite with a background color (CCSprite).
Both nodes have been assigned the same color value, but the colors are displayed differently on the device and in the simulator.
Has anyone else experienced the same issue?
I have tried other blending modes for the label without any luck.
Don't see a reason why the colors are displayed differently..


text:
Q: Ruby Syntax: Bitmask I'm having a lot of difficulty putting together what the following code is supposed to do (I understand what it's supposed to do, I just can't put together the pieces):
def roles=(roles)
  self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
end

def roles
  ROLES.reject do |r|
    ((roles_mask || 0) & 2**ROLES.index(r)).zero?
  end
end

ROLES is an array specified in the link. I'm assuming roles is also an array.

*

*Why have a setter method and a regular method with the same name?

*What array serves as the object of the map method? If roles is ['author', 'editor'] and ROLES is ['author', 'editor', 'manager'], how does the & operator create an array for map?

*What is 2**ROLES? I figured out that this is really just 2 raised to the power of ROLES.index(r).

*"Bitmask attributes on a Rails application" says that (roles & ROLES) is sanitizing the parameters roles against the array ROLES, but what does sanitizing it mean?

*If r is the current value of the array (roles & ROLES), how does the index method of 2**ROLES return r? I figured out that this is returning the position of roles in the array ROLES, but I still don't know how (roles & ROLES).map interacts/works with this.

*How does the inject method work on the condition in the brackets for the map method?

I'd like to figure out how this bitmasking works, but I have no idea how what's on the right side of the equation for def roles=(roles) returns an integer.

A: Basically the index call converts the given roles to integers by determining their position in the array of ROLES. 2 is then raised to the power of this index and inject simply sums the the results.
Put simply
Step 1 is to get roles that are found in ROLES by using & to se which values in the two arrays match.
Step 2, for each matching role compute 2**index. Map returns an array of these values.
Step 3, sum the array to get the final integer.
The idea is to compute a unique integer for each combination of roles.
The getter simply unwinds the process returning the combination of roles that match.


text:
Q: Extract characters between specified characters in R I have this variable
x= "379_exp_mirror1.csv"
I need to extract the number ("379") at the beggining (which doesn't always have 3 characters), i.e. everything before the first "". And then I need to extract everything between the second "" and the ".", in this case "mirror1".
I have tried several combinations with sub and gsub with no success, can anyone give me some indications please?
Thank you

A: You can use regular expression. For your problem ^(?<Number>[0-9]*)_.* do the job
1/ Test your regular expression with this website : http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
Or you can split string with underscore and then try parse (int.TryParse). I think the second is better but if you want to be a regular expression master try the first method

A: You can use sub to extract the substrings:
x <- "379_exp_mirror1.csv"

sub("_.*", "", x)
# [1] "379"

sub("^(?:.*_){2}(.*?)\\..*", "\\1", x)
# [1] "mirror1"

Another approach with gregexpr:
regmatches(x, gregexpr("^.*?(?=_)|(?<=_)[^_]*?(?=\\.)", x, perl = TRUE))[[1]]
# [1] "379"     "mirror1"

A: May be you can try:
 library(stringr)
 x <- "379_exp_mirror1.csv"
 str_extract_all(x, perl('^[0-9]+(?=_)|[[:alnum:]]+(?=\\.)'))[[1]]
 #[1] "379"     "mirror1"

Or
   strsplit(x, "[._]")[[1]][c(T,F)]
   #[1] "379"     "mirror1"

Or
    scan(text=gsub("[.]","_", x),what="",sep="_")[c(T,F)]
   #Read 4 items
   #[1] "379"     "mirror1"


text:
Q: Java -file not being read correctly this is a post-fix expression calculator and file reader that uses file input to operate on. When F is pressed and the file name is entered the program is suppose to operate on the contents of the file and give output if valid, however it keeps jumping straight to the catch and throwing up an error. I cant see why, any suggestions?
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class assignment {

    public static void main(String[] args) {
        String option;
        char letter;
    while(true)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter K to input data or F to use file input");
        option = scanner.nextLine();
        letter = option.charAt(0);

        switch (Character.toUpperCase(letter))
        {
        case 'K':
        System.out.println("Please enter a calculation, or press enter to close");

        String line = scanner.nextLine();

            if (line.equals(""))
            {
                System.out.println("Calculator has been closed");
                System.exit(0);
            }

        String [] element = line.split(" ");

            if (element.length == 3)
            {
            System.out.println("You enter: " + element[0]+ " " + element[1]+" " + element[2]);
            try{
                double number1, number2;
                number1 = Double.parseDouble(element[0]);
                number2 = Double.parseDouble(element[1]);

                    if (element[2].equals("+"))
                    {
                        System.out.println("Total:" + (number1 + number2));
                    }
                    else if (element[2].equals("/"))
                    {
                        System.out.println("Total:" + (number1 / number2));
                    }
                    else if (element[2].equals("-"))
                    {
                        System.out.println("Total:" + (number1 - number2));
                    }
                    else if (element[2].equals("*"))
                    {
                        System.out.println("Total:" + (number1 * number2));
                    }
                    else{
                    System.out.println("That is incorect input; please try again");
                    scanner.close();
                    }
                }
            catch(NumberFormatException e)
                {
                System.out.println("Error"+e.getMessage());
                }
        }
            else{
                System.out.println("You have inserted Incorrect input");
            }

        break;
        case 'F':
            try{
            System.out.println("you have chosen to use a file input");
            Scanner file = new Scanner (System.in);
            System.out.println("input file name:");
            String input = file.nextLine ();
            Scanner s = new Scanner (new File (input));

                while ( s.hasNext() ) {

            line = s.nextLine();
            String FileInput [] =input.split(" ");

                try
                {
                    double inp1, inp2;
                    inp1 = Double.parseDouble(FileInput[0]);
                    inp2 = Double.parseDouble(FileInput[1]);

                    if (FileInput[2].equals("+"))
                    {
                        System.out.println("Total:" + (inp1 + inp2));
                    }
                    else if (FileInput[2].equals("/"))
                    {
                        System.out.println("Total:" + (inp1 / inp2));
                    }
                    else if (FileInput[2].equals("-"))
                    {
                        System.out.println("Total:" + (inp1 - inp2));
                    }
                    else if (FileInput[2].equals("*"))
                    {
                        System.out.println("Total:" + (inp1 * inp2));
                    }
                    else
                    {
                    System.out.println("That is incorect input; please try again");
                    }
                }
                catch(NumberFormatException e)
                {
                    System.out.println("invalid number" + e);
                }
            }
            System.out.println("\nEOF");
            file.close();
            s.close();
            break;
            }
             catch (FileNotFoundException e) {
                System.out.println("incorrect filename");
            }
            default:
    System.out.println("Incorrect letter entered");
    }
 }
}
}

A: you should create Scanner instance only once.
Place
Scanner scanner = new Scanner(System.in);
as a first statement in your main (before the loop), and remove other new Scanner
The reason is that each Scanner is buffered.


text:
Q: formatting of the table of contents How can I change the settings of my table of contents, so that the sections and subsections are not indented as shown in the second picture. I would also like to center the title of the Contents. I am using the article class.

A: Using the tocloft package, all you have to do is to set the indents to the same values: 0em (so entries are flushed to the left margin) and 2em (space to typeset the unit number). Using \cfttoctitlefont and \cftaftertoctitle you can center the title; I also set tocdepth to 2 since subsubsections are not to be listed according to the image:
\documentclass{article}
\usepackage{tocloft}

\cftsetindents{section}{0em}{2em}
\cftsetindents{subsection}{0em}{2em}

\renewcommand\cfttoctitlefont{\hfill\Large\bfseries}
\renewcommand\cftaftertoctitle{\hfill\mbox{}}

\setcounter{tocdepth}{2}

\begin{document}

\tableofcontents
\clearpage

\section*{Introduction}
\addcontentsline{toc}{section}{Introduction}
\section{Test section one}
\subsection{Test subsection}
\subsection{Test subsection}
\subsubsection{Test subsubsection}
\subsection{Test subsection}

\section{Test section two}
\subsection{Test subsection}
\subsection{Test subsection}
\subsubsection{Test subsubsection}
\subsection{Test subsection}

\end{document}

A: This is an approach which uses the »tocstyle« package with the tocflat option along with the standard style.
\documentclass[11pt]{article}
\usepackage[T1]{fontenc}

\usepackage[tocflat]{tocstyle}
\usetocstyle{standard}

\usepackage{blindtext}

% Redefinition of ToC command to get centered heading
\makeatletter
\renewcommand\tableofcontents{%
  \null\hfill\textbf{\Large\contentsname}\hfill\null\par
  \@mkboth{\MakeUppercase\contentsname}{\MakeUppercase\contentsname}%
  \@starttoc{toc}%
}
\makeatother

\begin{document}
  \tableofcontents

  \blinddocument
\end{document}

You can compare with the tocfullflat option for equidistant spaces between numbers and heading entries. More details can be found in the package manual.
N.B.: You will get a warning about the alpha status of the package. So far is has not caused any major problems for me.

A: Here's a solution using titletoc package; it defines the dottedcontents command which has syntax:
% \dottedcontents{<section>}[<left>]{<above-code>}
% {<label width>}{<leader width>}

I have also used the command
\renewcommand{\contentsname}{\centering Contents}

to center the table of contents title.

Here's the code:
% arara: pdflatex
% arara: pdflatex
\documentclass{article}
\usepackage{titletoc}

% \dottedcontents{<section>}[<left>]{<above-code>}
% {<label width>}{<leader width>}
\dottedcontents{section}[0em]{\bfseries}{2.9em}{1pc}
\dottedcontents{subsection}[0em]{}{3.3em}{1pc}

% center the toc heading
\renewcommand{\contentsname}{\centering Contents}

\begin{document}

\tableofcontents

\section*{Introduction}
\addcontentsline{toc}{section}{Introduction}
\section{Test section one}
\subsection{Test subsection}
\subsection{Test subsection}
\subsection{Test subsection}

\section{Test section two}
\subsection{Test subsection}
\subsection{Test subsection}
\subsection{Test subsection}

\end{document}

For further reading, see How to modify the space between the numbers and text of sectioning titles in the table of contents?.


text:
Q: How to upgrade databse with deleting old database in flutter? I have some database in flutter, when I am trying to change version of database, I can't remove old. I know why this happening, I just have to write code of deleting database in onCreateFunc. What's the problem? I dunno how to do it. How can reach my goal?

This my code:

class DBHelper {
  static Database db_instance;

  final String TABLE_NAME = "DatabaseModel";

  Future<Database> get db async {
    if (db_instance == null) db_instance = await initDB();
    return db_instance;
  }

  initDB() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "maps_database.db");
    var db = await openDatabase(path, version: 3, onCreate: onCreateFunc);
    return db;
  }

  void onCreateFunc(Database db, int version) async {
    await db.execute('CREATE TABLE $TABLE_NAME'
        '(id INTEGER PRIMARY KEY,'
        'realTime TEXT, '
        'moduleDate TEXT, '
        'moduleTime TEXT, '
        'moduleDay TEXT, '
        'gpsCoordinates TEXT, '
        'gpsSatellites TEXT, '
        'gpsTime TEXT, '
        'gpsDate TEXT, '
        'temperature TEXT, '
        'pressure TEXT, '
        'humidity TEXT, '
        'dust TEXT, '
        'zivert TEXT )');

  }
}

A: Your code does not delete the existing table and create a new table because it already exists with the same name. Try the following piece of code inside the function.
await db.execute('CREATE OR REPLACE TABLE $TABLE_NAME'
        '(id INTEGER PRIMARY KEY,'
        'realTime TEXT, '
        'moduleDate TEXT, '
        'moduleTime TEXT, '
        'moduleDay TEXT, '
        'gpsCoordinates TEXT, '
        'gpsSatellites TEXT, '
        'gpsTime TEXT, '
        'gpsDate TEXT, '
        'temperature TEXT, '
        'pressure TEXT, '
        'humidity TEXT, '
        'dust TEXT, '
        'zivert TEXT )');

  }


text:
Q: Qooxdoo default tab index not working properly According to the Qooxdoo Beginner's Guide
here the default tab index for the widgets is set in the order in which the widgets are added to a container. But in this code in the playground this for some reason is not happening. Is this a qooxdoo bug or is something else ?

A: This book is somewhat outdated. I'm not sure if it worked like stated in the book at some time or if it hasn't worked like that all along. Anyway, the manual (which is the preferred and most up-to-date source of information) states:

The tab handling in qooxdoo is based on coordinates of each widget on
  the screen. It follows the visible structure and not the internal
  application (or even markup) structure.

So it's not a bug - you have to set the tab index manually if you want more control over this behavior.


text:
Q: Laravel insert record in 2 tables from single model I am using Lumen(Laravel), structure of 2 tables is given below
Language:
id,
lanugae_name,

Language_country
id,
language_id,
country_id,

I have created a model for lanugage table. But i want when i am inserting record in Language table on same time how i can insert its relationship with country in language_country ?

A: Assuming you have defined the relationship between Language and Country on the language model, you can use the attach() method to do this.
$language->countries()->attach($country->id);

Information about defining the relationship and more on the attach() method is at: https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships

A: You can use the attach() method
In your case:
$language->countries()->attach($countryId);


text:
Q: Does electrically neutral mean the potential is zero? I don't know if this is a silly question, but I have a homework problem that tells me a line charge is electrically neutral at time $t=0$.  I was calculating the potential from the definition
$$ V(\boldsymbol{r})=\frac{1}{4\pi \varepsilon_0}\int\frac{1}{\mathcal{r}}\rho(\boldsymbol{r}')d\tau', $$
and then I began to worry that I am supposed to assume the potential is zero since the object is electrically neutral.

A: Electrically neutral means the net charge is zero. There might be no charge present at that location, or there might be an equal density of positive and negative charge.
The potential at that point might be 0 or it might be non-zero due to the effect of charge at other locations.
For example if you have a point charge in space, the potential at a point A few cm away from that charge is not zero even though there is no charge at point A.


text:
Q: локальные уведомления когда приложение свернуто Интересует, как реализовать локальные уведомления когда приложение в бэкграунде, то есть у каждого уведомления есть такой метод (сначала идет подключение к API, которое меняется раз в минуту а потом наполнение) :
    let content = UNMutableNotificationContent()
    content.title = name
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats:true)
                        UIApplication.shared.applicationIconBadgeNumber = 0
    let reguest = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
                        UNUserNotificationCenter.current().add(reguest) { (error) in}

, который работет раз в минуту когда приложение на экране, но как только сворачивается - то всё. Как создать метод в бэкграунде с периодичностью, допустим, раз в минуту?

A: Приведенный вами код способен работать в бэкграунде. Скорее проблема в том, что ваше приложение в целом не работает в этом режиме. Как добиться чтобы работало? – читайте документацию.
В iOS в бэке можно делать ограниченное количество задач:

*

*Кратковременно выполнять код после закрытия апа (вроде до 3 минут)

*Скачивать/закачивать файл.

*Проигрывать/записывать аудио.

*Отслеживать геопозицию.

*VoIP.

*Регулярная скачка контента, типа новостных апов. (iOS сама решает, когда вы можете качать).

*Блютуз и прочие внешние девайсы.

Причем каждый пункт имеет строгие ограничения. У вас не получится под видом проигрывания музыки скачивать данные о погоде (а раньше можно было).

A: Читал несколько раз вопрос, так и не понял, какую задачу вы пытаетесь, хотите решить, плюс посмотрел ваши вопросы.
Возможно вашей задачи подойдут Background Update Notification, в этой документации описание
Единственное, что их не следует слишком часто посылать
Либо почитайте про работу в бэкграунде ios


text:
Q: Hotlinking - htacces redirige a una página si cumple una condición llevo mucho buscando la solución a este problema. Les explico.
Tengo una páginas con descarga de archivos zip, rar, pdf, doc, docx, xls, xlsx.
Las páginas y los archivos tienen esta estructura:
www.dominio.com/fotos/11/05/17/un-ave-de-color-negro-x4S12qlJ.html (página)
www.dominio.com/fotos/11/05/17/x4S12qlJ.zip (archivo .zip)
www.dominio.com/fotos/11/05/17/mamifero-de-clima-frio-uWe36Sqt.html (página)
www.dominio.com/fotos/11/05/17/uWe36Sqt.zip (archivo .zip) ... etc
No tengo problema que se lleven el ancho de banda con las fotos, el problema son con los archivos .zip, rar, etc.. que son enlazados. Lo que quiero es si desde otros dominios enlazan a www.dominio.com/fotos/11/05/17/uWe36Sqt.zip sea redireccionado a www.dominio.com/fotos/11/05/17/mamifero-de-clima-frio-uWe36Sqt.html
Tengo que precisar que la página es con php y mysql
¿Es posible hacer esto?
Gracias


text:
Q: Do browsers render all SVGs twice? This is a pretty standard way of inlining SVGs to be used later. It was made popular by Chris Coyier of CSS-tricks in Icon System with SVG Sprites and presumably thousands of developers have ditched icon fonts in favor of SVGs.

.icon {
    outline: 1px dotted blue;
    width: 500px;
    height: auto;
}
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;" hidden>
  <defs>
    <g id="circle">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="50" />
      </svg>
    </g>
  </defs>
</svg>

<svg class="icon">
  <use xlink:href="#circle" />
</svg>

The <svg> with the <defs> is made hidden (twice just to be sure!), even though if <defs> has any semantics, browsers should not render anything inside svg/defs.
But are those SVGs really hidden? Let's add a rule for the <g> element in the <defs>, which is inside a hidden <svg> with display: none. Double hide.

.icon {
    outline: 1px dotted blue;
    width: 500px;
    height: auto;
}

defs g {
   outline: 30px dashed green;
}
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;" hidden>
  <defs>
    <g id="circle">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="50" />
      </svg>
    </g>
  </defs>
</svg>

<svg class="icon">
  <use xlink:href="#circle" />
</svg>

Say what? What's the deal with those four green fellas? Why is that g rendered? Firefox and IE don't show any green outline.
Does this show that wherever you <use> SVGs, Chrome renders them twice?
Oh, but it's not just Chrome. If you add a fill to that g, IE11 will render it too:


text: Q: Is it possible to temporarily hide a chrome window when using selenium chromedriver? Is it possible to use selenium with chromedriver in a way that allows headless-like interaction with the browser, so that the actions in the browser are not visible until a later point in time? I'd like to automate a sign-in process for a particular streaming service, and only display the browser once i've navigated to, and started playing, an episode of a show, so that at no point in the process, a button could accidentally be pressed and break the flow


text:
Q: java programming exercise debug program I want to say thank you for reviewing my post and any contributions to my problem i am having. I am fairly new to java so i was wondering if you guys could please help me debug this program.
import java.util.Scanner;

public class DebugExercise {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String area, inStr;
        int pages;

        System.out.println("Please enter your city");
        area = input.nextLine();

        System.out.println("Please enter page number " + area + "'s phone book");
        pages = input.nextInt();

        PhoneBook phoneBook = new PhoneBook(area, pages);
        phoneBook.display();
    }
}

class PhoneBook extends Book {

    private String area;
    private String size;

    PhoneBook(int pages, String city) {
        super();
        area = city;
        if (pages > 300) {
            size = "big";
        } else {
            size = "small";
        }
    }

    public display() {
        System.out.println( area + pages + size);
    }
}

class Book {

    protected int pages;

    public Book(int pages) {
        pages = pages;
    }

    public int getPages() {
        return pages;
    }
}

A: Swap the arguments to the phonebook constructor
public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            String area, inStr;  //there is no need of inStr as you are not using it so remove it if not used
            int pages;

            System.out.println("Please enter your city");
            area = input.nextLine();

            System.out.println("Please enter page number " + area + "'s phone book");
            pages = input.nextInt();

            PhoneBook phoneBook = new PhoneBook(pages,area); //swapp the argurments
              phoneBook.display(pages, area); //add arguments to this otherwise it will just show 0
        }

And in your phonebook class add argument to super
    PhoneBook(int pages, String city) {
        super(pages);  // u can even remove this its not needed
        area = city;
        if (pages > 300) {
            size = "big";
        } else {
            size = "small";
        }

public void display(int pages,String area) {
    System.out.println( area + pages + size);
}
}

Now it will work

A: First of all, you have a few elementary problems:

*

*in your Phonebook class's constructor PhoneBook(int pages, String city), you call super(), but there is no empty constructor for class Book, so you must call super(pages).

*In the constructor of the Book class, you are assigning the pages variable it's own value. what you probably meant to do is this.pages = pages;. By using this.pages you tell java that you are referring to the field pages of the object that you are creating, and not to the parameter that is passed to the constructor. you can read more about the this keyword in Oracle's documentation here


text:
Q: How to set/reset property to react element at runtime Ok. Let's the make the question pretty simple.
I've a component named ColorText.
class ColorText extends React.Component{
  render(){
    return (<Text style={{color:this.props.color}}>{this.props.text}</Text>);
  }
}

and when I call
<ColorText color="red" text="I am red text"/>

It works.

Now, I've a function which returns the ColorText like this
 getGreenText = () => {
    return (<ColorText text="Default text" color="green"/>);
 }

and I want to reset the text property at runtime like this
const GreenText = this.getGreenText();
GreenText.props.text = "I am green text";

It doesn't work. and prints the Default Text
So, here is my question. Is it possible to set/reset property of a react component at runtime ? What is the correct way?
NOTE: I've googled a lot, couldn't find anything positive. If you have any doubt the question, ask me in the comments. Full source code can be available from here
Edit:
I know it's could be accomplished by simply passing the variable to the method like this
getGreenText = (text) => {
    return (<ColorText text={text || "Default text"} color="green"/>);
}

but that's not how i want to get it accomplished. I want to set it via the object returned from the method. Is it possible ?

A: You can't. It's by design. If you try to do
GreenText.props.text = "I am green text";

It will throw an error because props are immutable.
Can you give a use case where you need to do something like that ? It should never be needed.

Possible solution
You could simply pass the text as an argument as follows:
getGreenText = (text) => {
    return (<ColorText text={text || "Default text"} color="green"/>);
}

render() {
    const GreenText = this.getGreenText("I am green text");
    return (
        <View style={styles.container}>
            <ColorText color="red" text="I am red text"/>
            {GreenText}
        </View>
    );
}

If you need to defer the update of the text you can simply use the state.
Otherwise you could achieve something as you want with ref (see: https://reactjs.org/docs/refs-and-the-dom.html).

A: I've found that the React.cloneElement can clone the object and insert new props with it.
let GreenText = React.cloneElement(this.getGreenText(),{
    text : 'I am green text'
});

Full working source code can be found here : Gist


text:
Q: Trying to split a complex shapefile by Australian states I'm trying to work with a 1:1 million scale shapefile of the geology of Australia.
When the whole lot is loaded in to QGIS (over 200,000 polygons) it will freeze and go to slow to work with.
Ideally I would split the data by each state and just turn on which state I need at a time and that will hopefully run full speed.
However I can't figure out how to split the shapefile properly (700mb file),  I've tried a vector layer split and clip in the geoprocessing tools but I can't get them to work properly. The clip tool just generates a blank shapefile (I tried drawing a polygon shape as a vector file as the output layer so maybe that part was wrong).


text:
Q: Compilation fails using Gradle and Kotlin I am going through the examples in Kotlin in Action book. The gradle buid script is as follows:
group 'kotlin-in-action'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.2-2'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin'

repositories {
    mavenCentral()
}
apply plugin: 'java'

dependencies {
    testCompile 'junit:junit:4.12'
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "junit:junit:4.12"
    compile 'junit:junit:4.12'
    compile 'junit:junit:4.12'
}

sourceSets {
    main.kotlin.srcDirs += 'src'
}

All the scripts compile except for two classes that uses junit.
package ch06.ex1_8_1_LateinitializedProperties

import org.junit.Before
import org.junit.Test
import org.junit.Assert

class MyService {
    fun performAction(): String = "foo"
}

class MyTest {
    private var myService: MyService? = null

    @Before fun setUp() {
        myService = MyService()
    }

    @Test fun testAction() {
        Assert.assertEquals("foo",
            myService!!.performAction())
    }
}

The compiler says it can't find junit. I have tried adding the jar files in IntelliJ, but this has not resolved the problem. The jar files I have added are junit and hamscrest-core. This is all version 4.12.

A: I have resolved this. I had to add the Junit and hamcrest-core jar files from the mavan depository.


text:
Q: Deserializing Object of Unknown Types I have a bunch of objects that were serialized to XML.  Now I want to deserialize them, but since I don't know what the type is for a given XML string, I can't figure out how to do it.  Here is the code I am using when I know what type (Task in this case) the objects are:
public static Task DeserializeFromXML(string value)
{
  Task task = new Task();
  StringReader reader = new StringReader(value);
  XmlSerializer serializer = new XmlSerializer(task.GetType());
  XmlReader xmlReader = new XmlTextReader(reader);
  task = (Task)serializer.Deserialize(xmlReader);
  return task;
}

I'm confused since XmlSerializer needs a type passed to the constructor and the Deserialize method eventually needs to be cast from Object to whatever I just deserialized, but I don't know what that type is at this point.

A: The XML serializer does not include information about the kind of objects that are serialized out.  With straight XML, you don't have a way around this.  The object type is not included in the serialization.
Some other serializers in .NET (notably the NetDataContractSerializer) do include enough information to reconstruct specific object types without knowing them ahead of time.


text:
Q: Wondering about where I can find some literature about what my professor called "Generalized geometric series" So geometric series are nice and easy all around. But in my last text my analysis teacher brought some problems up, such as the following:

*

*$\sum_{n=1}^{\infty}\frac{1}{2^{ln(n)}}$

*$\sum_{n=1}^{\infty}\frac{1}{3^{ln(n)}}$
After the test we talked about the convergence of the general case when you have a series of the form $\sum_{n=1}^{\infty}r^{f(n)}$. where $r$ is a real number and $f(n)$ is a function such that is increasing on the positives. Is this an actual topic? Is there a general way to find the values of $r$ such that it converges? Thanks in advance for any help that you might provide.


text:
Q: Tic Tac Toe and Minimax - Creating an imperfect AI on a microcontroller I have created a Tic-Tac-Toe game on a microcontroller, including a perfect AI (perfect meaning that it doesn't lose). I did not use a minimax algorithm for that, just a little state machine with all possible and optimal moves.
My problem now is that I wanted to implement different difficulties (Easy, Medium and Hard). The AI so far would be the hard one.
So I've thought about how to do this the best way and ended up wanting to use the minimax algorithm but in a way that it calculates all the scores for all game positions so that I can also sometimes pick the second best score instead of the best. Since I can't always do all of these calculations on the microcontroller itself, I wanted to create a little program that I can run on my computer which gives me arrays of all possible board states (with respect to symmetry, ect to minimize the storage used) and their according scores.
For this I firstly tried to implement the minimax algorithm itself, regarding the depth in order to properly calculate the scores of each state. It was then supposed to give me back all of the optimal moves (for now) in an array. However, it does not seem to work that well. I have tried to debug it with some printf lines. Here is the code so far of both the minimax function as well as my main function:
    static int minimax(int *board, int depth)
{
    int score;
    int move = -1;
    int scores[9];
    int nextDepth;

    printf("\n----- Called Minimax, Depth: %i -----\n\n", depth);

    if(depth%2 ==1){
        player = -1;
    } else {
        player = 1;
    }

    printf("Player: %i\n---\n", player);

    if(isWin(board) != 0){
        score = (10-depth)*winningPlayer;

        printf("Player %i won on depth %i\n", winningPlayer, depth);
        printf("Resulting score: (10-%i)*%i = %i\nScore returned to depth %i\n---\n", depth, winningPlayer, score, depth-1);

        return score;
    }

    score = -20;
    nextDepth = depth+1;

    printf("Next depth is %i\n---\n", nextDepth);

    int i;
    for(i=0; i<9; i++){
        if(board[i] == 0) {

            if(nextDepth%2 ==0) {
                player = -1;
            } else {
                player = 1;
            }

            printf("Found vacant space at position %i\n", i);
            printf("Set value of position %i to %i\n---\n", i, player);

            board[i] = player;
            int thisScore = minimax(board, nextDepth);

            printf("Value of the move at position %i on next depth %i is %i\n---\n", i, nextDepth, thisScore);

            scores[i] = thisScore;
            if(thisScore > score){

                printf("New score value is greater than the old one: %i < %i\n---\n", thisScore, score);

                score = thisScore;
                move = i;
                g_moves[nextDepth-1] = move;

                printf("Score was set to %i\n", thisScore);
                printf("Remembered move %i\n---\n", move);

            }
            board[i] = 0;

            printf("Value of position %i was reset to 0 on next depth %i\n---\n", i, nextDepth);

        }
    }

    if(move == -1) {

        printf("Game ended in a draw.\n Returned score: 0\n---\n");

        return 0;
    }

    printf("Move at position %i was selected on next depth %i\n", move, nextDepth);
    printf("Returning score of %i to depth %i\n---\n", score, depth);

    return score;
}

The main is:
int main(int argc, char **argv)
{
    memcpy(board, initBoard, sizeof(board));
    int score = 0;
    int depth = getDepth(board);
    score = minimax(board, depth);
    printf("\n--- finished ---\n\n");

    printf("Moves with the highest score: ");
    int i;
    for(i=0; i<9; i++){
        printf("%i | ", g_moves[i]);
    }
    printf("\n");

    printf("The score is %i\n", score);

    printf("The best next board is: \n|----|----|----|\n");

    for(i=0; i<3; i++){
        printf("| %-2i ", board[i]);
    }
    printf("|\n|----|----|----|\n");
    for(i=3; i<6; i++){
        printf("| %-2i ", board[i]);
    }
    printf("|\n|----|----|----|\n");
    for(i=6; i<9; i++){
        printf("| %-2i ", board[i]);
    }
    printf("|\n|----|----|----|\n");

    return 0;
}

Furthermore, i have some variables:
//1  = Beginning Player
//-1 = second Player
static int player;
static int winningPlayer = 0;
static int g_moves[9];

/* 0 1 2
 * 3 4 5
 * 6 7 8
 */
int initBoard[9] = {
    0, 0, 0,
    0, 0, 0,
    0, 0, 0,
};

int board[9];

As well as my winning function:
int isWin(int *board)
{
    unsigned winningBoards[8][3] = {
        {board[0], board[1], board[2],},
        {board[3], board[4], board[5],},
        {board[6], board[7], board[8],},
        {board[0], board[3], board[6],},
        {board[1], board[4], board[7],},
        {board[2], board[5], board[8],},
        {board[0], board[4], board[8],},
        {board[2], board[4], board[6],},
    };

    int i;
    for(i=0; i<8; i++){
        if( (winningBoards[i][0] != 0) &&
            (winningBoards[i][0] == winningBoards[i][1]) &&
            (winningBoards[i][0] == winningBoards[i][2])){
                winningPlayer = winningBoards[i][0];
                return winningPlayer;
            }
    }
    return 0;
}

For some reason, the last time the minimax returns from depth 7 step-by-step to depth 1, it overwrites my array g_moves with all 0s thus resulting in the following lines in my printed output (only the last 70 lines):
...
----- Called Minimax, Depth: 7 -----

Player: -1
---
Player 1 won on depth 7
Resulting score: (10-7)*1 = 3
Score returned to depth 6
---
Value of the move at position 2 on next depth 7 is 3
---
Value of position 2 was reset to 0 on next depth 7
---
Move at position 0 was selected on next depth 7
Returning score of 3 to depth 6
---
Value of the move at position 3 on next depth 6 is 3
---
Value of position 3 was reset to 0 on next depth 6
---
Move at position 0 was selected on next depth 6
Returning score of 3 to depth 5
---
Value of the move at position 4 on next depth 5 is 3
---
Value of position 4 was reset to 0 on next depth 5
---
Move at position 0 was selected on next depth 5
Returning score of 3 to depth 4
---
Value of the move at position 5 on next depth 4 is 3
---
Value of position 5 was reset to 0 on next depth 4
---
Move at position 0 was selected on next depth 4
Returning score of 3 to depth 3
---
Value of the move at position 6 on next depth 3 is 3
---
Value of position 6 was reset to 0 on next depth 3
---
Move at position 0 was selected on next depth 3
Returning score of 5 to depth 2
---
Value of the move at position 7 on next depth 2 is 5
---
Value of position 7 was reset to 0 on next depth 2
---
Move at position 0 was selected on next depth 2
Returning score of 5 to depth 1
---
Value of the move at position 8 on next depth 1 is 5
---
Value of position 8 was reset to 0 on next depth 1
---
Move at position 0 was selected on next depth 1
Returning score of 5 to depth 0
---

--- finished ---

Moves with the highest score: 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
The score is 5
The best next board is:
|----|----|----|
| 0  | 0  | 0  |
|----|----|----|
| 0  | 0  | 0  |
|----|----|----|
| 0  | 0  | 0  |
|----|----|----|

If you need any other information in order to help me, I'll be glad to give them to you if I have them myself.
Thanks in advance.
EDIT:
So I rewrote my minimax function so it now prints all the possible board states on a .txt file using the console (cmd: ./NAME_OF_FILE > DEST_NAME.txt in the according folder). The code is the following:
int minimax(int *board, int depth)
{
    g_node++;
    int player;
    int move = -1;
    int score = -20;
    int thisScore = -20;
    int i;

    if(isWin(board) != 0){
        printf("\nNode: %i\n", g_node);
        printf("Board state:");
        for(i=0;i<9;i++) {
            if((i%3) == 0)
                printf("\n");
            printf("%2i ", board[i]);
        }
        printf("\n");
        printf("has a score of %i\n", (10-depth)*winningPlayer);
        return (10-depth)*winningPlayer;
    }

    if(depth%2 ==1){
            player = -1;
        } else {
            player = 1;
        }
    for(i=0; i<9; i++){
        if(board[i] == 0){
            board[i] = player;
            thisScore = minimax(board, depth+1);
            if(thisScore > score){
                score = thisScore;
                move = i;
            }
            board[i] = 0;
        }
    }

    printf("\nNode: %i\n", g_node);
    printf("Board state:");
    for(i=0;i<9;i++) {
        if((i%3) == 0)
            printf("\n");
        printf("%2i ", board[i]);
    }
    printf("\n");

    if(move == -1){
        printf("has a score of 0\n");
        return 0;

    }
    printf("has a score of %i\n", score);
    return score;
}

My next step is to print out the board with the max score of each move at the according position.
Example:
10  8 10
 8  7  8
10  8 10
for the empty board at the beginning.

EDIT 2:
I now added another function called printScoredBoards which basically is supposed to do what I discribed above in my last edit, however there is a problem to it.
Since it is always possible to win after the 5th move if your opponent plays dumb enough and since the minimax tries out all possibilities, including those, with the following code I get a scored board of all 15s for the empty board.
void printScoredBoards(int *board, int depth)
{
    int player;
    int scoredBoard[9] = {0,0,0,0,0,0,0,0,0,};
    int i;
    if(isWin(board) == 0){
        if(depth%2 ==1){
            player = -1;
        } else {
            player = 1;
        }

        for(i=0; i<9; i++){
            if(board[i] == 0){
                board[i] = player;
                scoredBoard[i] = minimax(board, depth+1)+10;
                printScoredBoards(board, depth+1);
                board[i] = 0;
            }
        }
        printf("Scored board:");
        dumpTable(scoredBoard);
        printf("\n");
    }
}

This is although the corners should be worth more and the center is the least valuable. Does anyone happen to know a work-around for this?

EDIT: I've set up a new minimax algorithm and posted it in another post. You can find the post in the "Linked" section on the right or here.
Now all I'm doing is implementing it in the microcontroller code and creating a function which can pick the best/second best move out of all scored moves as well as randomize it if there are multiple moves with the same score.
This post can thereby be closed.

A: I think trying to get the second best move with a full depth analysis is overdoing it. Don't explore the whole tree by limiting the depth of your minmax (2 move ahead permits to win but the AI is still strong), or just a use a random move for a really imperfect AI.


text:
Q: Trying to deploy build to Sitecore 9.3 instance using ".\build.ps1 -target quick-deploy" getting error - executing task: "Publish-Foundation-Projects"
I am using Sitecore 9.3
in powershell when running command:
".\build.ps1 -target quick-deploy", it is giving error :
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Microsoft\VisualStudio\v16.0\Web\Microsoft.Web.Publishing.targets(3000,5): error : Copying file App_Config\Include
MHealthFairview\Foundation\MHealthFairview.Foundation.Indexing.Providers.CloudSpatialSearch.Master.Index.config to obj\Debug\Package\PackageTmp\App_Config\Include\MHealthFairview\Foundatio
n\MHealthFairview.Foundation.Indexing.Providers.CloudSpatialSearch.Master.Index.config failed. Could not find a part of the path 'obj\Debug\Package\PackageTmp\App_Config\Include\MHealthFai
rview\Foundation\MHealthFairview.Foundation.Indexing.Providers.CloudSpatialSearch.Master.Index.config'. [C:\Projects\Fairview\Repos\mhf-web-sitecore.pharmacy\src\server.sitecore\src\Founda
tion\Indexing\code\MHealthFairview.Foundation.Indexing.csproj]
An error occurred when executing task 'Publish-Foundation-Projects'.
Error: One or more errors occurred.
MSBuild: Process returned an error (exit code 1).


text:
Q: How to replace 3 words coming from mysql to links I have a table which contains one row with a string (for example: 'me', 'you', 'him') and now when I fetch them with PHP I want to replace them with links,
I tried with explode to seperate them and then add links but its not going really well, I started to make a function but it didn't go really well. Can you guys help me to make a function to fetch a string, and then seperate those 3 words and add a certain link for each one of them. the links already exist I just want to replace those words with them.
WARNING: not every row has those 3 words, some have ony the first word some have all of the 3 words.. etc.!

A: Try strtr() with array argument.
http://php.net/manual/en/function.strtr.php

A: I'm not sure exactly what you're asking but I think something along these lines might help:
function replace_you_me_him($string) {
    $new_string = str_replace(
        array(
            'me',
            'you',
            'him',

            'Me',
            'You',
            'Him'
        ),
        array(
            'me',
            'you',
            'him',

            'Me',
            'You',
            'Him'
        ),
        $string
    );
    return $new_string;
}

$s = "You, me and him went for a walk.
";
echo replace_you_me_and_him($s);
//You, me and him went for a walk.


text:
Q: Vue2 when refreshing any page it redirects to the main page I was trying to work on vue2. and I am facing a strange problem.
I have 4 routes.

*

*/login when user is not logged in they will see this page so they can log in.

*/uploads when user login they are redirected to this page.

*/train this page for some other work

*/documents/collaboration when they use this router it should render train component only but url will be BASE_URL/documents/collaborate

My problem is when I refresh /train page or paste the collaborate url it redirects me to /uploads.
I am not able to know what is wrong with this and why this is happening.
Below is the code for my router.js
import Vue from 'vue'
import Router from 'vue-router'
import LoginPage from './views/Login.vue'
import Uploads from './views/Uploads.vue'
import Train from "./views/Train";

Vue.use(Router)

export const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginPage,
      meta: {bodyClass: 'auth-wrapper'}
    },
    {
      path: '/', redirect: '/uploads'
    },
    {
      path: "/uploads",
      name: 'Uploads',
      component: Uploads,
      meta: {bodyClass: 'full-screen', verboseName: 'Data Classifier', icon: '@/assets/img/company5.png'}
    },
    {
      path: "/train",
      name: 'Train',
      component: Train,
      meta: {bodyClass: 'full-screen', verboseName: 'Data Trainer', icon: '@/assets/img/company5.png'}
    },
    {
      path: "/documents/collaborate/:id",
      name: "Collaborate",
      component: Train,
      meta: {bodyClass: 'full-screen', verboseName: 'Data Trainer', icon: '@/assets/img/company5.png'}
    }
  ]
})

router.beforeEach((to, from, next) => {
  // redirect to login page if not logged in and trying to access a restricted page
  const publicPages = ['/login'];
  const authRequired = !publicPages.includes(to.path);
  const loggedIn = localStorage.getItem('user-token');

   if (authRequired && loggedIn === null) {
     return next('/login');
   }
   if (loggedIn !== null && !authRequired) {
     return next('/uploads');
   }
  next()

})

export default router;

A: Redirecting to /uploads since the if (loggedIn !== null && !authRequired) {...} condition is true inside route.beforeEach(). Change:

router.beforeEach((to, from, next) => {
   ...
   if (authRequired && loggedIn === null) {
     return next('/login');
   }

   // navigate to to.path() page
   next();
})


text:
Q: alternative to pthread_timedjoin_np I am trying to figure out how to get rid of a reliance on the pthread_timedjoin_np because I am trying to build some code on OSX.
Right now I have a Queue of threads that I am popping from, doing that pthread_timedjoin_np and if they dont return, they get pushed back on the queue.
The end of the thread_function that is called for each thread does a pthread_exit(0); so that the recieving thread can check for a return value of zero.
I thought i might try to use pthread_cond_timedwait() to achieve a similar effect, however I think i am missing a step.
I thought I would be able to make worker Thread A signal a condition AND pthread_exit() within a mutex, , and worker Thread B could wake up on the signal, and then pthread_join(). The problem is, Thread B doesn't know which thread threw the conditional signal. Do I need to explicitly pass that as part of the conditonal signal or what?
Thanks
Derek

A: Here is a portable implementation of pthread_timedjoin_np. It's a bit costly, but it's a full drop-in replacement:
struct args {
    int joined;
    pthread_t td;
    pthread_mutex_t mtx;
    pthread_cond_t cond;
    void **res;
};

static void *waiter(void *ap)
{
    struct args *args = ap;
    pthread_join(args->td, args->res);
    pthread_mutex_lock(&args->mtx);
    args->joined = 1;
    pthread_mutex_unlock(&args->mtx);
    pthread_cond_signal(&args->cond);
    return 0;
}

int pthread_timedjoin_np(pthread_t td, void **res, struct timespec *ts)
{
    pthread_t tmp;
    int ret;
    struct args args = { .td = td, .res = res };

    pthread_mutex_init(&args.mtx, 0);
    pthread_cond_init(&args.cond, 0);
    pthread_mutex_lock(&args.mtx);

    ret = pthread_create(&tmp, 0, waiter, &args);
    if (!ret)
            do ret = pthread_cond_timedwait(&args.cond, &args.mtx, ts);
        while (!args.joined && ret != ETIMEDOUT);

    pthread_mutex_unlock(&args.mtx);

    pthread_cancel(tmp);
    pthread_join(tmp, 0);

    pthread_cond_destroy(&args.cond);
    pthread_mutex_destroy(&args.mtx);

    return args.joined ? 0 : ret;
}

There may be small errors since I wrote this on the spot and did not test it, but the concept is sound.

A: Producer-consumer queue.  Have the threads queue *themselves, and so their results,(if any), to the queue before they exit. Wait on the queue.
No polling, no latency.
With your current design, you would have to join() the returned threads get the valueptr and to ensure that they are destroyed.
Maybe you could sometime move to a real threadpool, where task items are queued to threads that never terminate, (so eliminating thread create/terminate/destroy overhead)?

A: solution with alarm.
pthread should enable cancel, so it can stop by external.(even with pthread_timedjoin_np).
pthread_timedjoin_np return with ETIMEOUT after waited time.

*

*set alarm, use alarm also can give "TIMEOUT" signal.

*In handler, just pthread_cancel it. (only timeout run this).

*pthread_join it in main thread.

*reset alarm
I write test code in here:github


text:
Q: framework for plugin/theme options panel? I found that the longest part of a plugin or theme development is creating the options panel, at least in my case.
So i like to know what's your take on that.
Do you use a ready made framework or class? And if so witch one?
Or do you write it up from scratch?  Use the settings API or plain options?
Thanks.

A: *

*scbFramework has related classes, I used it for one plugin and it saved me plenty of time;

*WPAlchemy MetaBox I see a lot of mentions for this around, hadn't used it myself yet;

*Hybrid Core has set of functions for pages/metaboxes/settings, but it probably won't make sense to use it just for that.

A: The UpThemes team has just released their options framework as an opensource for everyone. It worth to take a look.

A: I had been using this , I liked how it outputs a iframe preview, but I started to just write my own since I'm figuring this stuff out.
http://clark-technet.com/2010/01/wordpress-theme-options-framework-ver-2

A: OK so found some more:

*

*JeffreyWay /
WordPress-Theme-Options-Page  -
open source class the project is hosted on github aimed at theme developers,
looks nice, haven't used it. (link dead)
.

*devinsays / Options-Framework -
open source Framework the project is
hosted on github aimed at theme
developers , i later learned that is
has evolved in to
Thematic-options very large
scaled project that has lots of
features. (link dead)

*helgatheviking /
thematic-options-KIA -    open
source Framework the project is
hosted on github aimed at help
developers build options into their
thematic child themes , witch was
forked for Thematic-options very much
up to date.(link dead)

*Wordpress AdminPage Class - a
commercial solution, packed it
features and very easy to use.

*OptionTree plugin - and IDE for
creating option panels , lots of
feature and constantly updated,
downside is: it's not easily
integrated in plugins or themes and
default options are not an option (up
to version 1.1.1).
that's it for now but still looking to here about your experience.
Update
After a long time of trying I've managed to integrate Options tree with my plugin and after that part was done , I have to say that its never been easier to add options to my plugin, EVER! all done with no code, but using the slick UI that comes with it.
So as of now its my favorite with a small exception of being a plugin by it self and not a framework witch makes the integration part a lot harder.
Update2
If you read the first update then this will be 180 degree turn, i have stopped using Option-Tree witch was hard to integrate in the first place but mainly for the reason that it create an option row in the options database table for each option you add to it so my plugin has created 287 rows in the database and thats bad for many reasons but the main ones are its hard to remove all of them at plugin deactivation and you have to create a get-option call for each one of them so that's a lot of database calls.
Since that little set back,I found that most of the frameworks listed up here work in the same manner of each option gets its own row.
So i modified AdminPage Class to save all options per admin page in an array of options and and now my plugin only generates 7 Rows in the database and at most i only need to call the get_option function 7 times so that saves lots of database calls, I'll contact the creator of AdminPage Class and ask him to consider this modification but other then that it very easy to use and even easier to manage.
Last Update
if anyone is still keeping score here, then i ended up coding my own
option panel class

which  it's main features are:

*

*Open source, GPL licensed.

*Works with plugins as well as themes

*OOP Code all the way (which means easy to extend and modify).

*Import Export Options.

*All Options saved as a single row in a database.

*Available fields are:

*

*Input

*Textarea

*Radio button

*Checkbox

*Select Dropdown

*File Upload

*Image Upload

*WYSIWYG editor

*Date Picker

*Time Picker

*Color Picker

*Taxonomy List Dropdwon or checkboxes

*Post list Dropdown or checkboxes

*WordPress User Roles Dropdown or checkboxes

*Syntax Highlighted Code Editor (PHP, CSS, HTML, JAVASCRIPT)

*Typography Field (set of size, color, face, family fields)

*Sortable Drag & Drop

*Repeater Field

*Plupload field

*hooks and filters all over the place so you can customize just the way you'd like

A: The devinsays Options-Framework has now evolved more, into the Options Framework Plugin/Options Framework Theme.
This is beautiful and user-friendly, and there is documentation about including it right in your theme code. However, if you wanted to incorporate it into a plugin, that would take some work.

A: I think we can add Infinity Theme Anti-Framework to this list. http://infinity.presscrew.com/


text:
Q: What is this German (?) virus and how can I get rid of it? UPDATE
I've posted my solution below.

This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one.
This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared.
I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it.
What is this virus and how can I get rid of it?

A: As it's been said over and over again, the only sure-fire way to ensure that a virus is gone is to format your computer, and re-install things one by one.
That said, this isn't technically a virus, but a new kind of malware that makes you pay to remove it, which you should not do under any circumstances, because you're contributing to organised crime.

A: How much time have you spent already trying to fix the PC?
You may just find that booting with something like an Ubuntu live CD to copy all data to a removable USB hard drive, then formatting the disk and re-installing is actually the fastest way to solve this problem.
I've seen it happen time and time again where so many more hours are spent trying to remove viruses or malware than what it takes to simply backup, format and re-install.
I know you don't want to do this, you would rather use a tool to fix the problem, but I think you'll save time by doing a clean install and you'll also know that the malware is really gone.
You computer will probably run faster as well as this is usually the case on a fresh install.

A: It seems to be the BKA Trojan (the first couple of results are links to the scareware's site, so don't use those). It seems that the consensus is to either reinstall, or use more anti-malware software.
Re-installing should be a last resort; trying to remove it is better. The worst that can happen is that you end up re-installing anyway and "waste" some time learning some stuff.
It may seem silly/obvious, but have you tried pressing Alt+F4 on the window?

I can suggest trying a few more softwares to try (run them in safe-mode to for better results):

*

*SUPERAntiSpyware (use the portable version)

*Autoruns (to weed out where it is running from)

*HijackThis (to analyze the system fairly throughly)

*WinSpy++ (to remove the topmost attribute from the window, though it may reset it every couple of seconds)

*ComboFix (scorched-Earth last resort)

Another thing to try is to quickly look in the Task Manager's Processes tab to try to figure out which process(es) the trojan is running from, and try to kill it (you don't need to see it the Task Manager to kill it, you can type out the first several letters of the EXE name, and press Del, then Space), though make sure that the Task Manager's Always-On-Top option is selected; just in case.

(Side note: I find it amusing that the trojan is using the Windows 7 logo even though the Alex has indicated that it is an XP system. sigh)

A: So, after spending several days fighting this thing, I finally got rid of it. I'm pretty sure I got the right one, but along the way I found some suspicious items that could have contributed. Here's the steps it took to clean it up.
First thing I did was to check all of the autostart locations on windows. I followed this article here. Most of the locations where clean except for:

*

*HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit

*

*This key had a second path on it pointing to C:\Documents and Settings\NetworkService\Application Data\09A52917-B4FC-4f02-AE3B-BF55D9351F4A\msvcs.exe

*HKLM\Software\Microsoft\Windows\CurrentVersion\Run

*

*This node had a REG_SZ key named 2C508BD5-F9C6-4955-B93A-09B835EC3C64 which was pointing to the msvcs.exe file in the Userinit key.

*HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify

*

*This node had two other nodes that looked suspicious to me. They were named \toldvw32 and torlfsvses. Both nodes had keys that pointed to a toldvw32.dll file and were set with a WlStartupEvent event. Looking these up on Google didn't produce any meaningful results at the time, so I went ahead an removed them. There doesn't seem to be problems with having done that yet.

The real issue is that msvcs.exe file. If one manages to survive it will replicate it self across all user profiles on the machine. Since it was hooked up into the NetworkService profile it would always make sure it existed in the other profiles.
There's three locations where msvcs.exe exists. They are:

*

*{PROFILE}/Application Data/09A52917-B4FC-4f02-AE3B-BF55D9351F4A

*{PROFILE}/Start Menu/Programs/Startup

*WINDOWS\Prefetch

*

*Not 100% sure on this one, but I did find two suspicious files: MSVCS.EXE-0CA809BA.pf and MSVCS.EXE-301B4EC0.pf. I went ahead and removed them without issues (so far at-least).

I hope this helps someone in the future. It worked for me. If you have a computer that had/has this and it's hooked up to a domain make sure to check the user's profile folder on the server as well, there's a copy there too. Needless to say, don't login into that profile directly on the server because you're just going to have a very fun time after that...
Also, you can't clean it through Safe Mode if the profile you're logging into has been infected. I used UBCD4Win to clean up what I saw, then I did the rest through Safe Mode.
Now, I know the general consensus is to nuke the computer and start from scratch, but that is not always possible in a business environment. After I had it cleaned up and confirmed clean by several antivirus tools I ran chkdsk /f /r on the drive, defragmented it with MyDefrag (4.3.1) and the computer works perfectly as if it never happened. So, nuking the computer is not always the best course of action as @Synetech pointed out him/her self.
Lastly, Kaspersky was installed on the computer, but somehow was turned off and that's how the virus (malware?) got through and did what it did. I'm not a fan of antivirus software at all, in fact I don't have any on my 6 or so machines that I have, but in an environment where you have technically challenged personel, it is a good idea to have it and its also a very good idea to make sure it's actually turned on and updated.
That is all fellow awesome people. I hope someone else can benefit from this answer in the future.

A: This seems to be a brand new scareware. As far as I see, it has not been described by the antivirus specialists yet. It threatens to delete the contents of the disk and sue you for using an illegal copy of Windows.
I propose you turn off the infected computer, remove the disk and copy the contents of the disk to some safe spot. Then you can also retry a virusscan while attached to a different computer (not booting this infected disk).
Personally, I would backup the data and go for a fresh install. Once a malware was on a windows, there is no way to make sure all traces have been removed, because once they have a hold of your computer they will continue to try and use it / your data / your bank account. In cases like this, it seems to be usual to load more malware onto the computer.
Users of this computer should change their passwords, if banking has been done, check their bank accounts and set a new PIN.
Oh, and dont pay. If you do, it might ask for admin permissions to "fix" your windows, and then rootkit you for good.

A: Most, but not all, malware can be manually removed with autoruns.
Try the following procedure:

*

*download autoruns from the above link and run it straight from the zip archive

*let it scan (if it can)

*look for two types of entries - ones with no signature and more importantly entries which say 'file not found'. The second kind is typical for viruses that insert themselves into various parts of the system that get executed during start time (but upon startup they temporarily remove the infected file and make it accessible only on the next restart). By unticking the problematic/suspicious entries you can cripple the malware to the point that it will not be active in the system anymore (and if you untick something that is needed you can always tick it back on).

Now, if you can not run autoruns that would be due to the virus already blocking it - however viruses will rarely do that.
This procedure is surprisingly efficient, but of course this is only due to viruses not targeting it. You can always try it.
After going through it you can use

*

*process explorer to check if there are strange processes running on you system

*tcpview to audit and monitor your network activity

Using these tools is not trivial (does require knowledge of the normal system behavior), but in case that

*

*the regular anti-virus software does not recognize the threat yet neither will booting to linux and trying to clean with clamav

*you really want to try to clean it and try to avoid re-format

you can try to follow the procedure I gave.


text:
Q: Replace document.all with document.getElementById with If Else Statement I am trying to rewrite this function to remove the document.all and replace with document.getElementById, but so far I am not having much luck.
This is the original function:
if (document.all.DeptFundingYN.value == "TRUE") {

This is what I have:
function VoidRtn(fRecNum,fReferenceNum) {
  var DeptFundingYNField = document.getElementById("VoidID");

  if(DeptFundingYNField.value == "TRUE") {
    var href = "PaymentsEntry.asp?speedpay=false&CLAIM=YES&LevelCode=Void&Mode=Update&Reference_Num=" + document.PayClaimGridForm.ReferenceNum.value;
    href += "&RecNum=" + fRecNum;
    document.location.href = href;
  } else {
    alert("No Department Funding");
  }
}

This button:
<button title=""Void This Payment"" id=""VoidID"" class=""whitefontbutton"" onclick=""VoidRtn(" & fRecNum & "," & fReferenceNum & ");"" style=""width: 15px; height: 15px;BACKGROUND: #6a7dae; FONT-SIZE: 7 PT"" onmouseover=""this.style.background='#000066'"" onmouseout=""this.style.background='#6a7dae'"">V</button></font>

A: I don't understand why the double-quotes appear twice in your <button>, for example:
<button title=""Void This Payment"" ...

It should be:
<button title="Void This Payment" ...

And there is no "TRUE" value anywhere in your markup.
The only way your condition can work is if you add a value="TRUE" attribute to the button, for example:
<button title="Void This Payment" value="TRUE" ...

With these changes, it should work.


text:
Q: I forgot how I cropped a video two years ago Two years ago, I cropped a video on Windows 7 using Windows Live Movie Maker.  I cannot remember how I did it, but I know I did because I have the video from two years ago in three different sizes. One is the original that looks small and far away. Then I have  a second copy that looks bigger and closer and a third copy that is the biggest and closest.  I need to do this with another video and cannot figure out how I did it. It's driving me nuts! Can someone please tell me how to do it again?  Thanks.

A:
When you finish editing your video, and want to save it, you will have options, to choose which quality and size you want, or when you want to publish it to youtube you will have other options like custom quality and size


text:
Q: Increase minimum user password length? For security reason i would like to enforce users to set 10 character password length .
How can i modify this policy ?

A: Open Terminal :
sudo vi /etc/pam.d/common-password

Add :
password [success=2 default=ignore] pam_unix.so obscure sha512 **min=10**

As you can see min=xx will specify the x number of character should the password include .


text:
Q: PHP JSON array if equals value then echo I'm trying to get a specific link for each of my videos from the Vimeo API. I can loop through the results and echo them in a foreach but when I try to access a specific value it still out puts all the results:
    // Make Request
    $response = $lib->request('/videos/'.$vurl.'?fields=files', [ ], 'GET');

    // Get Response
    $links = $response['body']['files'];

    foreach ($links as $key => $value) {

        if ($value['width'] = '1920') {

            echo $value['link_secure'];

        } else {

            echo 'no match';

        }
    }

How do I access just the result where the $value equals '1920'?

A: use == instead of = here.
 if ($value['width'] == 1920) {

        echo $value['link_secure'];

    } else {

        echo 'no match';

    }


text:
Q: Stack Exchange should submit a copy of your message when you send a support request I noticed that when I get an automated email about a support ticket after writing to Stack Exchange, I don't see a copy of the message I wrote.
I do tend to work with more media-specialized organizations when I send emails so it might just be what I am used to, but I haven't seen a group or business that doesn't include a copy of the original message in a real long time so I wouldn't think to copy and paste the original message.
Having it just makes the conversation more continuous and I honestly don't see what the harm would be in including it for the ticket. Is there a specific reason Stack Exchange doesn't do this?

A: The support system is already prone to abuse, and sending a copy of the message would only make that worse.
For a long time we didn't send any kind of auto-response at all, because the contact form is not validated and anyone can type any email address into that box and bother whoever owns that email with an auto-response. Sending what they typed into the box along with it only exacerbates that problem. Now some random user is receiving a potentially spam or abusive message from our email address in the form of a confirmation of receiving some ticket they didn't submit.
Unfortunately the way we do support does not make these options viable. We've already been experiencing issues with confused users receiving confirmations for stuff they didn't submit in the couple weeks we've had the option turned on. We will likely be turning the auto-responders back off sometime in the near future for community support requests.


text:
Q: Any python libs for parsing apache config files? Any python libs for parsing apache config files or if not python anyone aware of such thing in other languages (perl, php, java, c#)?
As i'll be able to rewrite them in python.

A: Red Hat's Emerging Technologies group has Augeas (written in C, but with Python bindings available), a generic system configuration tool with "lenses" for reading and writing several different configuration file formats. I would consider investigating the availability of a lens for Apache.

A: There is a new library as of 2016 written using pyparsing:
https://pypi.python.org/pypi/parse_apache_configs/
Has a few rough edges, but allowed me to add in directives and save to a new file.
Source at https://github.com/alextricity25/parse_apache_configs

A: No Python libraries exist that I know of, but here's a perl one:
http://packages.debian.org/sid/libapache-configfile-perl
Package: libapache-configfile-perl
Priority: optional
Section: interpreters
Installed-Size: 124
Maintainer: Michael Alan Dorman
Version: 1.18-1
Depends: perl (>= 5.6.0-16)
Description: Parse an Apache style httpd.conf configuration file

This module parses the Apache httpd.conf, or any
compatible config file, and provides methods for
you to access the values from the config file.

If you do rewrite it in Python, please update your post to mention the name of your package on PyPI! :)

A: There is also one new parser released.

*

*http://pypi.python.org/pypi/apache_conf_parser/
It still lacks documentation, however is quite straightforward for understanding.

Example
import apache_conf_parser
import pprint

DEFAULT_VHOST = '/etc/apache2/sites-available/000-default.conf'

vhost_default = apache_conf_parser.ApacheConfParser(DEFAULT_VHOST)

print vhost_default.nodes
print vhost_default.nodes[0].body.nodes

pprint.pprint(
    {
        i.name: [i.arguments for i in vhost_default.nodes[0].body.nodes]
    }
)

A: ZConfig, I think, used to ship with a schema for parsing Apache configuration files; it doesn't seem to anymore, but it's oriented around parsing those types of files and turning the config into a Python object. A quick glance at the documentation suggests it wouldn't be too hard to set up a ZConfig schema corresponding to whatever Apache options you'd like to parse and validate.
http://pypi.python.org/pypi/ZConfig/2.6.0


text:
Q: using specialized templates to overload function based on return type I am trying to return a reference to a value in an array based on the return type. I read somewhere that c++ did not support overloading using return types but that specialized templates could be used.
I tried and failed.. could you help me figure out what i am doing wrong?
This is what i thought I should to:
uint16_t var_uint16[10];
float var_float[10];

template<class T>
T& Memory(int index) {  }

template<>
uint16_t& Memory<uint16_t>(int index) { return var_uint16[index]; }

template<>
float& Memory<float>(int index) { return var_float[index]; }

And call it like this:
float a = 10.0;
Memory(1) = a;     // Should set var_float[1] to 10.0

The code above produces the following error:
no matching function for call to 'Memory(int)'
candidate is:
template<class T> T& Memory(int)
template argument deduction/substitution failed:
couldn't deduce template parameter 'T'

A: You can only overload cast operator based on return type. You can overload =operator to support your exact semantics
struct Element {
    operator uint16_t&()
    {
        return var_uint16[i];
    }

    operator float&()
    {
        return var_float[i];
    }

    template <typename T>
    void operator=(T t)
    {
        T& val = *this;
        val = t;
    }
    int i;
};
inline Element Memory(int i) { return Element{i}; }

float a = 10.0;
Memory(1) = a;

float& x = Memory(1);
x = 10.0


text:
Q: How do I get an event message from UITextField in a custom table cell to the table cell? I'm sure this is a very noddy question, but I just can't get anything useful from the manuals.
I've a UITextField embedded in a custom UITableViewCell. If I use a delegate for the UITextView - it just gives me the UITextView.
If I link the event to the ParerentViewController, it just gives me the ID of the UITextView.
What I want to do is handle the event at the UITableViewCell level. Can I get the events from this text control to feed to the parent, and handle them at the parent level.
I don't seem to even be able to find the parent cell from the UITextField that the handler gives me. How do I find out which cell within the table the UITextField is in when I'm trying to process the events.
I have to be missing something obvious, as I've done this in earlier (pre storyboard) versions, and I'm sure it wasn't this difficult.

A: Answered a similar question the other day. See the accepted answer.
How can I get index path of cell on switch change event in section based table view
This will let you handle the text changes in the cell and pass them on to the table view. In your case its a UITextView and not a UISwitch.
Add properties to the cell for anything you will need inside the block code when it is called.

A: Create a subclass of UITableViewCell and implement the textField delegates inside the subclass. The code is lengthy but if you want I can post it when I get time.


text:
Q: Expected number of draws of m objects at a time out of n objects with replacement The question is as follows: Consider an urn of n distinct objects. At each time, m (m < n) objects are drawn randomly at once. The objects obtained are noted and then placed back in the urn. What is the expected number of draws I have to make until all of the objects have drawn at least once?

A: Let's take a look at a random draw log. In each line, we have all $n$ objects, where $1$ means it has been drawn and $0$ means it hasn't been. Here, $n=5$ and $m=3$:
1 1 1 0 0
0 1 1 0 1
1 0 1 0 1
0 1 1 1 0

Now we will try to find the probability, that all objects have been drawn after $k$ draws. This is achieved when each object has been drawn at least once. We can denote this as $1-\text{[probability that it has never been drawn]}$. In each draw, there is probability $\frac{n-m}{n}$ that the object isn't drawn, so after $k$ draws, there is probability $\left(\frac{n-m}{n}\right)^k$ that the object hasn't been drawn.
Okay, so we know that each object is after $k$ draws drawn at least once with probability $1-\left(\frac{n-m}{n}\right)^k$. If we have $n$ objects, then probability, that all of them have been drawn at least once after $k$ draws is obviously $\left(1-\left(\frac{n-m}{n}\right)^k\right)^n$.
If we want to know, what is the probability, that we got the state "each object has been drawn at least once" exactly after $k$ draws, we need to subtract probability, that it was achieved after $k-1$ draws or sooner:
$$P_{\text{exactly after $k$}}=\left(1-\left(\frac{n-m}{n}\right)^k\right)^n-\left(1-\left(\frac{n-m}{n}\right)^{k-1}\right)^n$$
Now if you lok at definition of expected value, our expected number of draws is sum of expressions $k\times\text{[probability of ending exactly after $k$]}$. Namely,
$$\sum_{k=0}^\infty k\cdot\left(\left(1-\left(\frac{n-m}{n}\right)^k\right)^n-\left(1-\left(\frac{n-m}{n}\right)^{k-1}\right)^n\right)$$
And this can be simplified to:
$$\sum_{k=0}^\infty 1-\left(1-\left(\frac{n-m}{n}\right)^k\right)^n$$
I'm convinced it can't be simplified any more (and WolframAlpha agrees). If you're interested in any specific step of this solution, just write in comments.
Edit: My answer is not totally correct, see comments.

A: This answer is a work in progress.
Case 1: $m=n-1$
In this case, all but one are drawn on the first draw, and we're just looking for the expected number of attempts to get the last one. Since the probability of getting it on any particular draw is $\frac{n-1}{n}$, the expected number of draws after the first to get it is $\frac{n}{n-1}=1+\frac{1}{m}$. Adding to this the original draw, we have $E=2+\frac{1}{m}$.

Case 2: $m=1$
The probability that the number of draws required is $k$ is given by $n\times\frac1n\times K$, where $K$ is the probability that the other $n-1$ objects were all drawn in the first $k-1$ draws. (The first $n$ picks the final object drawn, and the $\frac1n$ gives us that it shows up in draw number $k$.) We can write a formula for $K$ using inclusion-exclusion:
$$K=\frac{(n-1)^{k-1} - \binom{n-1}{n-2}(n-2)^{k-1}+\binom{n-1}{n-3}(n-3)^{k-1}+\cdots + (-1)^n\binom{n-1}{1}(1)^{k-1}}{n^{k-1}}$$
Letting $E_n$ denote the resulting expected value for $n$ objects drawn $m=1$ at a time, we have:
$$E_2=3, E_3=\frac{11}{2}, E_4=\frac{25}{3}, E_5=\frac{137}{12}, E_6=\frac{147}{10}$$
I don't yet have a general formula for $E_n$ in the $m=1$ case, but it seems possibly tractable.
Edit: The case $m=1$ is the Coupon collector's problem, which is a wheel I'm going to now stop re-inventing. We have $E_n=n(1+\frac12+\cdots+\frac1n)$, which confirms the answers I'd found so far.

Another approach: The number of objects not yet chosen after $k$ steps is approximately $U_k=n\cdot\left(\frac{n-m}{n}\right)^k$. (That value is actually precise for $k=0$ and $k=1$, and approximate after that.) We might expect all objects to have been chosen at some point where $U_k<1$. How far below $1$ is not entirely clear, but maybe we can get an idea by looking at cases where we know the answer. Thus, for $m=n-1$, we have $U_{E_n}=n\cdot\left(\frac1{n}\right)^{2+\frac1{n-1}}$. This quantity is $\frac14$ for $n=2$, and goes to $0$ as $n\to\infty$. On the other hand, for $m=1$, the quantity $U_{E_n}$ goes up from $\frac14$ and approaches $\frac12$ as $n\to\infty$.


text:
Q: Ponteiros por parâmetro em C++ Estou tendo um problema com o ponteiro em customers. Chamo a função newCustomer(), que insere nós na lista pendurada em customers. O problema é que toda vez que o programa sai da função newCustomer(), customers volta a valer nullptr.
Segue abaixo a chamada de função, na main():
case 1:
  newCustomer(customers);
break;

A função newCustomer() é esta:
void newCustomer(Cliente *customers){
 int num;
 string nome;
 Cliente *qwe, *next;
 cout << "Numero de clientes: ";
 cin >> num;
 qwe = customers;
 if(customers == nullptr){
   cout << "oi" << endl;
   customers = new Cliente();
   cout << "Nome do cliente: ";
   setbuf(stdin, 0);
   getline(cin, nome);
   customers->setName(nome);
   customers->setid(num);
   qwe = customers;
   num--;
 }
 while(qwe->getProx() != nullptr){
 qwe = qwe->getProx();

 }
 while( num != 0){
   next = new Cliente();
   qwe->setProx(next);
   qwe = qwe->getProx();
   cout << "Nome do cliente: ";
   setbuf(stdin, 0);
   getline(cin, nome);
   qwe->setName(nome);
   qwe->setid(num);
   num--;
 }
}

Gostaria também de pedir algumas dicas de como posso melhorar meu código. Estou começando em C++ agora, aceito todas as críticas :)

A: Na linha
customers = new Cliente();

Coloquei no GitHub para referência futura.
você está mudando o conteúdo de uma variável local, quando termina execução da função esta variável deixa de existir e seu valor desaparece. Por alguma razão você parece achar que esse valor sobrevive mesmo depois do fim da função, mas isto não acontece.
Seria possível usar Cliente **customers como parâmetro aí você altera o objeto da variável e não a variável em si, ou seja, você usa uma indireção para resolver o problema. Aí todo acesso ao objeto final será dado por um objeto intermediário que é um ponteiro para o objeto final. Esse ponteiro por ser um objeto passado pode ser alterado e será refletido lá fora. Claro, tem que passar o argumento de forma apropriada e o acesso ao objeto final tem que ser sempre través desse ponteiro, aí dá certo. Ou então pode retornar o objeto criado ali em vez de retornar void, oque pode ser mais simples.
Já que pediu dicas aí vão elas:
Na verdade isso tudo é programar em C usando o C++, em C++ real nada disso é considerado certo, ele tem mecanismos bem melhores que inclusive gerencia a memória automaticamente (este caso tem cara que vai vazar memória, pelo menos incentiva).
Uma função que cuida da inserção e a interface com o usuário não é adequado. As funções deveriam ter uma uma responsabilidade, aí tem duas. Isso pode criar problemas de manutenção. Em exercício não causa, mas se quer aprender cero é melhor se acostumar com isso.
O código parece fazer algumas coisas desnecessárias.
Poderia caprichar na formatação do código, pode parecer bobagem mais ajuda bem e costuma usar em minha palestra:

Nem falei que me dá medo criar um único cliente em uma variável com nome no plural. Nomes adequados ajudam muito dar entendimento no código.

A: Isso é porque você está iniciando customers dentro da função.
Pense dessa forma: o customers que você tem fora da função é um ponteiro que aponta para o endereço 10000. O customers que você tem dentro da função é uma cópia do outro ponteiro, ele está alocado em uma posição diferente, mas também aponta para o endereço 10000, ou seja tem o mesmo valor.
Se em algum ponto da função você alterar o valor que existe na posição 10000, ambos os customers estarão apontando para esse endereço, e portanto o valor desse endereço irá refletir em ambos os ponteiros.
No entanto você não está alterando o valor no endereço 10000, você está alterando o endereço para qual o ponteiro customers dentro da função está apontando. Agora o customers fora da função continua apontando para 10000, mas o customers dentro da função aponta para 20000, e portanto os valores não se refletem mais.
Se você quiser que o valor do customers dentro da função sempre reflita no customers fora da função, você precisa passar um ponteiro de um ponteiro, Cliente **customers. Ou ao menos é o que você precisaria fazer em C. Em C++ existe uma forma mais prática, você pode passar a referência de uma variável, dessa forma a variável dentro da função é tratada como sendo exatamente a mesma que a fora da função. Tudo que você precisa fazer é adicionar um & no argumento.
void newCustomer(Cliente *&customers) {
  //...
}


text:
Q: Program recursion in javascript I am a beginner at javascript. I want to use javascript to browse all the elements in the dom and print its name, I wrote the following:
function getNumber(parent){
                var entiredoc = parent;
                var docnodes = entiredoc.childNodes;
                return docnodes.length;
            }
function browAllDom(parent){
      if(parent!=null){
            for(i = 0; i < getNumber(parent); i++){
                    alert(parent.nodeName);
                    return browAllDom(parent.childNodes[i]);
            }
      }
}

when I debug, it browses the leaf in the tree dom and exits. I think it has to browse all in the for loop.
Where's the problem? And how can I you fix it?

A: The following code will run only a single time:
for(i = 0; i < getNumber(parent); i++){
    (parent.nodeName);
    return browAllDom(parent.childNodes[i]);
}

This code will run only once since you are returning from the for loop.
Instead you should write the return outside of the for loop.
Have a look at this answer. You will have a better understanding.


text:
Q: "Apple event timed out" using xlwings to open large spreadsheet I am using the following xlwings code on MacOS to read a large Excel spreadsheet containing many formulae to be executed:
import xlwings as xl
app = xl.App(visible=False)
book = app.books.open("large.xlsx")
book.save()
app.kill()

Attempting to execute this code leads to a CommandError: "Apple event timed out", full stack trace:
File "./open_excel_file.py", line 32, in open_excel_file
    book = app.books.open("large.xlsx")
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xlwings/main.py", line 2889, in open
    impl = self.impl.open(fullname, update_links, read_only, format, password, write_res_password,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/xlwings/_xlmac.py", line 209, in open
    self.app.xl.open_workbook(workbook_file_name=fullname, update_links=update_links, read_only=read_only,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aeosa/appscript/reference.py", line 518, in __call__
    raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
appscript.reference.CommandError: Command failed:
        OSERROR: -1712
        MESSAGE: Apple event timed out.
        COMMAND: app('/Applications/Microsoft Excel.app', newinstance=(0, 34521322)).open_workbook(workbook_file_name='large.xlsx', update_links=k.do_not_update_links, read_only=None, format=None, password=None, write_reserved_password=None, ignore_read_only_recommended=None, origin=None, delimiter=None, editable=None, notify=None, converter=None, add_to_mru=None)

Is there a way to use xlwings to open this file, execute all of the formulae and then save it again, without encountering this timeout?

A: xlwings currently goes with the default timeout from the underlying appscript. If this happens during the save event, you should be able to do this as a workaround until this is fixed: workbook.api.save(timeout=3000), see: https://github.com/xlwings/xlwings/issues/618
Edit:
To open a workbook works like this:
import xlwings as xw
app = xw.App(visible=False)
book = app.api.open_workbook(workbook_file_name='/full/path/to/large.xlsx', timeout=3000)

I'll try to add native support with the next release.


text:
Q: Implementing link in PHP foreach loop Trying to implement links in my foreach loop. However, can't get the $category link working. Any pointers? Managed to get the link to work for the sub-category, as shown below:
<?
$output = mysqli_query("SELECT * FROM bikes, bikeTypes WHERE bikes.model_id = bikeTypes.model_id");
$result = array();
while($row = mysqli_fetch_array($output))
{
   $result[$row['model']][] = $row;
}

foreach ($result as $category => $values) {
  echo "
".$category.'
';
    foreach ($values as $value) {
      echo "
" . $value['bikeName'] . "
";
    }
echo '
';
echo '
';
}
?>

Thanks for the help in advance guys! :)

A: The HTML Tags are not in the correct order first commes the li-tag and then the a-tag
  foreach ($values as $value) {
      echo "
" . $value['bikeName'] . "
";
    }

A: Your a and li tags are intertwined:

...

this should be:

...


text:
Q: Why does a test scope dependency add compile scope dependencies? Why does adding the following result in compile scope dependencies?
<dependency>
  <groupId>myproject.core</groupId>
  <artifactId>api</artifactId>
  <classifier>tests</classifier>
  <scope>test</scope>
</dependency>

[INFO] +- myproject.core:api:jar:tests:5.0.5-SNAPSHOT:test
[INFO] |  +- org.apache.curator:curator-framework:jar:2.7.1:compile
[INFO] |  |  \- org.apache.curator:curator-client:jar:2.7.1:compile
[INFO] |  +- org.apache.curator:curator-x-discovery:jar:2.7.1:compile
[INFO] |  |  +- org.apache.curator:curator-recipes:jar:2.7.1:compile

I'd expect copy-dependencies with an exclusion on test scope to not only skip the top level but remove it and its transitives from the tree.

A: There is a difference between test dependencies and test-jar dependencies.
For test dependencies, the scope of transitive dependencies are correctly set to test (see this table in the Maven reference).
For test-jar dependencies (what you have here), the behaviour is different. I couldn't find anything in the Maven docs explaining why it is different (maybe someone else with better insight can explain why). However, I found a bug report (MNG-1378) about this, which remains unresolved after more than 10 years, so I would not get your hopes up.


text:
Q: Vpython accessing object loaded from pdb protein file using this .cif file:
https://files.rcsb.org/download/1MSC.cif and parsing in with https://pypi.org/project/pdbx-mmcif/
with this code (main.py) that uses Vpython 7.6.1 in python3:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov  11 17:40:03 2020

@author: Pietro

"""
import sys
from pdbx.reader.PdbxReader import PdbxReader

import time

from vpython import *

scene = canvas(title='Examples of Tetrahedrons',
     width=800, height=800,
     center=vector(0,0,0), background=color.black)

openz = open('./1msc.cif')

pRd = PdbxReader(openz)

data = []

pRd.read(data)

block = data[0]

atomsite = block.getObj("atom_site")

i=0
while True:
        atom =  atomsite.getValue("group_PDB",i)
        atomid = atomsite.getValue('label_atom_id',i)
        if atom =='ATOM':
            if atomid == 'CA':
                    aa = sphere(pos=vector(float(atomsite.getValue('Cartn_x',i)),float(atomsite.getValue('Cartn_y',i)),
                                           float(atomsite.getValue('Cartn_z',i))),radius=0.5)

            i +=1

        else:

            break

print('fine')

I can show CA atoms in space as spheres. What I am missing is how to access the singles spheres ( objects as I understood) created by vpython, to be able to apply something like
sphere-object-number-1.color = color.red

sphere-object-number-1.color = color.blue

obviusly not in the same loop I created to display all the spheres ?
Please be kind I am not a Python expert.

A: A standard method is to make a list atoms = [] and when you create a sphere add it to the list, as atoms.append(sphere(.....)). Then you access the nth sphere with atoms[n], where n runs from 0 to atoms.length-1.