text:
Q: Failing to cover the code and pass the test I am a beginner in unit testing. I am trying to write a test script, but I am stuck. I'd like to understand what I am doing wrong.
public ConvertExcelDocumentResponse ConvertExcelDocument(ConvertExcelDocumentRequest request)
        {
            var logger = Bootstrapper.Resolve<ILogger>();

            ConvertExcelDocumentResponse response = new ConvertExcelDocumentResponse();
            if (!string.IsNullOrEmpty(request.FileName) &&
                System.IO.Path.GetExtension(request.FileName).ToLowerInvariant() == ".xls" &&
                request.FileContent != null && request.FileContent.Length > 0)
            {
                response.FileContent = _httpClient.ConvertExcelDocument(request.FileContent, request.FileName);
                response.FileName = System.IO.Path.GetFileNameWithoutExtension(request.FileName) + ".xlsx";
                response.Success = true;
            }
            else
            {
                logger.LogError("Unable to convert Excel Document '" + request.FileName + "' only .xls files are allowed.");
                response.FileContent = new byte[] { };
                response.Success = false;
            }
            return response;
        }

Here is my test:
        /// <summary>
        /// Test to Convert XLS to XLSX
        /// </summary>
        [TestCategory("DocumentService")]
        [TestMethod]
        public void Test_ConvertExcelDocumentResponse()
        {
            byte[] filecontent = new byte[] { };
            string filename = "file";

            using (ShimsContext.Create())
            {
                ConvertExcelDocumentRequest excelDocumentRequest1 = new ConvertExcelDocumentRequest()
                {
                    FileName = "filename",
                    FileContent = new byte[] {},
                };
                ConvertExcelDocumentRequest excelDocumentRequest2 = new ConvertExcelDocumentRequest()
                {
                    FileName = "",
                    FileContent = new byte[] {},
                };

                ShimDocumentService.AllInstances.ConvertExcelDocumentConvertExcelDocumentRequest = ((@this, Success) =>
                {
                    return new ConvertExcelDocumentResponse()
                    {
                        FileContent=filecontent,
                        Success = true,
                        FileName = filename,
                    };
                });
                ShimHttpClientBase.AllInstances.ConvertWordDocumentByteArrayString = ((@this, fileContent, fileName) =>
                {
                    return fileContent;
                });

                //Act
                ILogger logger = Bootstrapper.Resolve<ILogger>();
                var docService = new DocumentService();

                //IDocumentService DocumentService = Bootstrapper.Resolve<IDocumentService>();
                var excelResponse1 = docService.ConvertExcelDocument(excelDocumentRequest1);
                var excelResponse2 = docService.ConvertExcelDocument(excelDocumentRequest2);

                //Assert
                Assert.AreEqual(excelResponse1.FileContent, filecontent );
                Assert.AreEqual(excelResponse1.FileName, filename);
                Assert.IsTrue(excelResponse1.Success, "Expects true");

                Assert.AreEqual(excelResponse2.FileContent, filecontent);
                Assert.AreEqual(excelResponse2.FileName, filename);
                Assert.IsTrue(excelResponse2.Success, "Expects true");
            }
        }

This is passing the test but code coverage is 0%. I don't know where I am going wrong. I tried covering filename = null and few other conditions. not sure why it isn't covering my code

A: It looks like you'll need to also write a test where the filename is null or empty. That way you will cover the code in the else block.
Increasing code coverage often involves making your test exercise pieces of code that are not likely to be normally hit.


text:
Q: Como usar variável de classe como valor padrão em funções de php? class Teste(){
  public variavel;
  public variavela;

  function teste($parametro=$this->variavel, $parametro2->$this->variavela){
    // code
  }
}

Me retorna o seguinte erro:

Parse error: syntax error, unexpected '$this' (T_VARIABLE)

A: Você não pode fazer isso, os valores-padrão de parâmetros precisam ser constantes. O máximo que o PHP permite é usar constantes de classe, com referência estática:
class Teste {
  const VARIAVEL = 10;
  const VARIAVELA = 20;

  function __construct($parametro=self::VARIAVEL, $parametro2=self::VARIAVELA){
    echo "$parametro - $parametro2";
  }
}

$t = new Teste();

http://ideone.com/l1NX5y
Se bem que nesse caso já vale mais a pena colocar os valores literais diretamente na assinatura da função, não é? Fica mais limpo:
class Teste {
  function __construct($parametro=10, $parametro2=20){
    echo "$parametro - $parametro2";
  }
}

$t = new Teste();

Se você precisa de uma solução com valores dinâmicos, atribua os valores dentro da própria função, como o @AndréRibeiro sugeriu na resposta dele.

A: O que você está tentando fazer não é válido no PHP.
Segundo o manual:

O valor padrão [de um parâmetro de função] precisa ser uma expressão constante, não (por exemplo)
  uma variável, um membro de classe ou uma chamada de função.

Uma alternativa com um funcionamento similar:
class Teste(){
  public $variavel;
  public $variavela;

  function teste($parametro = null, $parametro2 = null){
    $parametro = $parametro ? $parametro : $this->variavel;
    $parametro2 = $parametro2 ? $parametro2 : $this->variavela
  }
}

Nesse exemplo, caso algum dos parâmetros não seja passado na chamada da função, o valor padrão será o valor do membro da classe.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add inline model to django admin site I have these two models:
class Rule(models.Model):
    name = models.CharField(max_length=200)

class Channel(models.Model):

    id = models.CharField(max_length=9, primary_key=True)
    name = models.CharField(max_length=100)
    rule = models.ForeignKey(Rule, related_name='channels', blank=True)

And I have to be able to add channels to rule in admin site within RuleAdmin interface. So I created these two admin models:
class ChannelAdmin(admin.TabularInline):
    model = Channel

class RuleAdmin(admin.ModelAdmin):
    model = Rule
    inlines = [ChannelAdmin]

But when I start my server I got this errors:
ERRORS:
<class 'main.admin.ChannelAdmin'>: (admin.E202) 'main.Channel' has no ForeignKey to 'main.Channel'.

Still in django shell I can make queries like
rule = Rule.objects.get(pk=1)
rule.channels.all()

There is got to be something obvious but I just can't figure it out.

A: do something like this:
class ChannelAdmin(admin.TabularInline):
    model = Channel

class RuleAdmin(admin.ModelAdmin):
   inlines = [ChannelAdmin,]

admin.site.register(Rule,RuleAdmin)

A: ADD in admin.py
from .models import Post, Comment

class CommentInline(admin.StackedInline):
    model = Comment
    extra = 0

class PostAdmin(admin.ModelAdmin):
    inlines = [
        CommentInline,
    ]

admin.site.register(Post, PostAdmin)

Click on this:
result

A: class OrderItemInline(admin.TabularInline):
    model = OrderItem
    fields = ['image']

class OrderAdmin(admin.ModelAdmin):
    list_display = ['id']
    list_filter = ['status']
    inlines = [OrderItemInline]

A: Mar, 2022 Update:
This will work:
from django.contrib import admin
from .models import Channel, Rule

class ChannelInline(admin.TabularInline):
    model = Channel

@admin.register(Rule)
class RuleAdmin(admin.ModelAdmin):
    inlines = [ChannelInline]


text:
Q: Prohibited package name: java I tried to get the data from my database name as jaane with user name Hello and Password hello.
Error:
java.lang.SecurityException: Prohibited package name: java
        at java.lang.ClassLoader.preDefineClass(ClassLoader.java:480)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: java.Main.  Program will exit.
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

my code is
package java;

import java.awt.Container;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author ritesh
 */
public class Main extends JFrame{

    public Main() throws SQLException
    {super("Database of Students");
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

        }
     Connection connection = DriverManager.getConnection( "jdbc:derby:/localhost:1527","hello","Hello" );
     Statement statement = connection.createStatement();

 // query database
       ResultSet resultSet =
 statement.executeQuery( "SELECT * FROM COLLEAGUES" );
       StringBuffer results = new StringBuffer();
 ResultSetMetaData metaData = resultSet.getMetaData();
 int numberOfColumns = metaData.getColumnCount();

 for ( int i = 1; i <= numberOfColumns; i++ ) {
 results.append( metaData.getColumnName( i ) + "\t" );
 }

 results.append( "\n" );

 while ( resultSet.next() ) {

 for ( int i = 1; i <= numberOfColumns; i++ ) {
 results.append( resultSet.getObject( i ) + "\t" );
 }

 }

 // close statement and connection
 statement.close();
 connection.close();

// set up GUI and display window
JTextArea textArea = new JTextArea( "Hello");
 Container container = getContentPane();

 container.add( new JScrollPane( textArea ) );

 setSize( 300, 100 ); // set window size
 setVisible( true ); // display window
}

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            Main window = new Main();
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // TODO code application logic here
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

A: Change your package name. java as a package name is prohibited.
Edit: Move your Main.java file in a (source) directory that doesn't start with java or javax and use the directory structure names to change your package name in the code.

A: Never Keep your class in a root package as "java" or never create a package starting as java. ... you can use any other identifier as your package name.

A: java.lang.SecurityException: Prohibited package name: java

You cannot use java as the name of your package. Replace it to something else.

A: You need to specify the Database Name, and there are two slashes before localhost. I assume hello is your username and Hello the password...
Connection connection = DriverManager.getConnection( "jdbc:derby://localhost:1527/DatabaseName","hello","Hello" );

...that is after you change your package name to something other than java!

A: Look at why `java.lang.SecurityException: Prohibited package name: java` is required?

User code is never allowed to put classes into one of the standard Java packages. That way, user code cannot access any package-private classes/methods/fields in the Java implementation. Some of those package-private objects allow access to JVM internals. (I'm thinking of SharedSecrets in particular.)

A: I just had the same error. Previously, the package name is as below:
package java.com.transaction.statistics.controllers;

This is created due to a mistake.
I corrected and the package looks as below:
package com.transaction.statistics.controllers;

This is fine now and doesn't show any error.

A: If your project is inited by Gradle, I recommend you to change the project by specifying the package name, then we can avoid the problem.
gradle init --type java-application --test-framework junit --package packname


text:
Q: How to write an .exe file using C# code with StreamWriter? Actually I am copying an exe file over sockets. I am able to copy a text using StreamWriter Class but i used the same code for copying a exe file , it created a exe file with the desired name but I cannot run it.
"This app cannot run on your PC". I have Windows 8 x64, that is irrelevant.
static void Main(string[] args)
{
    TcpClient tcpclient = new TcpClient();
    tcpclient.Connect("localhost", 20209);
    NetworkStream stm = tcpclient.GetStream();

    byte[] buffer = new byte[1024];
    var fs = File.Open("F:/aki/RMI/akshay.exe", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    var streamWriter = new StreamWriter(fs);
    int x;
    while ((x=stm.Read(buffer, 0, 1024))>0)
    {
        **A**    streamWriter.Write(buffer);
        **B**  //streamWriter.Write(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
    }
    streamWriter.Close();
    fs.Close();

    Thread.Sleep(2000);
    Console.WriteLine("Waiting");
    //Console.ReadLine();
    tcpclient.Close();
}

I tried both A and B methods, B works for text file but not for an exe file. Any solutions?
Or I have to use any other Writer Class for exe files ?

A: You would need a Write(byte[], index, count) method in the StreamWriter class to do that, but that doesn't exist. Calling streamWriter(buffer) is the same as streamWriter(buffer.ToString()), so that won't write the contents of the buffer, and using Encoding.ASCII to convert the binary content in the buffer to text will change it.
Don't use a StreamWriter at all. Write to the FileStream instead:
while ((x = stm.Read(buffer, 0, 1024)) > 0) {
  fs.Write(buffer, 0, x);
}

You should use the variable x as the length to write rather than buffer.Length, as the buffer might not always be completely filled. At least the last block will almost never be a full buffer.

A: A StreamWriter is a TextWriter. Can't you just do:
fs.Write(buffer, 0, buffer.Length);


text:
Q: Simple matrix question $x$ is an $(n*1)$ vector
$A$ is an $(n*n)$ matrix
$B$ is an $(n*k)$ matrix
$u$ is an $(k*1)$ vector
$P$ is a positive semi-definite symmetric matrix
$E$ means mathematical expectation
$E(x'A'PBu+u'B'PAx)=2x'A'PBu$
How does this equation hold?

A: The second term in the sum is the transpose of the first term.
The first term is a scalar. So the second term is the same scalar.


text:
Q: The type java.lang.Charsequence cannot be resolved. It is indirectly referenced from required .class file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
 prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
 prefix="html"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
 prefix="logic"%>
<%@ page import="de.fhg.fokus.hss.db.model.*, java.util.* " %>

<jsp:useBean id="resultList" type="java.util.List" scope="request"></jsp:useBean>
<jsp:useBean id="maxPages" type="java.lang.String" scope="request"></jsp:useBean>
<jsp:useBean id="currentPage" type="java.lang.String" scope="request"></jsp:useBean>
<jsp:useBean id="rowPerPage" type="java.lang.String" scope="request"></jsp:useBean>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<link rel="stylesheet" type="text/css" href="/hss.web.console/style/fokus_ngni.css">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><bean:message key="result.title" /></title>

 IMS Subscription - Search Results

     ID
     Name
     S-CSCF Name
     Diameter Name

   <%
    if (resultList != null && resultList.size() > 0){
     IMSU imsu;
     int idx = 0;
     Iterator it = resultList.iterator();

     while (it.hasNext()){
      imsu = (IMSU) it.next();
   %>

      <tr class="<%= idx % 2 == 0 ? "even" : "odd" %>">

        <%= imsu.getId() %>

        <a href="/hss.web.console/IMSU_Load.do?id=<%= imsu.getId() %>">
         <%= imsu.getName() %>

        <%= imsu.getScscf_name() %>

        <%= imsu.getDiameter_name() %>

    <%
      idx++;
     } //while
    } // if
    else{
    %>

       <bean:message key="result.emptyResultSet" />

    <%
    }
    %>

     <%
      int length = Integer.parseInt(maxPages) + 1;
      int cPage = Integer.parseInt(currentPage) + 1;
      for (int iy = 1; iy < length; iy++) {
       if (cPage != iy) {
     %>
        <a href="javascript:submitForm(<%=String.valueOf(iy)%>);"><%=iy%>
     <%
       } else {
     %>

          <%=String.valueOf(iy)%>

     <%   }
      }
     %>

     <bean:message key="result.rowsPerPage" />

      <option value="20"
       <%= rowPerPage.equals("20") ? "selected" : "" %> >20 </option>
      <option value="30"
       <%= rowPerPage.equals("30") ? "selected" : "" %> >30 </option>
      <option value="50"
       <%= rowPerPage.equals("50") ? "selected" : "" %> >50</option>
      <option value="100"
       <%= rowPerPage.equals("100") ? "selected" : "" %> >100</option>

I am trying to run a appliaction, I am accessing the application through a web interface but at some part I am getting the following error:
HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 116 in the jsp file: /pages/user/imsu_search_result.jsp
Generated servlet error:
The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files

    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:397)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1063)
    org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:263)
    org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:386)
    org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:318)
    org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:229)
    org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194)
    org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.

Please find the attached jsp file
Please provide your suggestion to resolve the issue.
Thanks

A: 1) Check your compiler and JVM versions as I believe they mismatch OR
2) Compile your all classes with newer version of 1.8 or
3) downgrade to Java 1.7


text:
Q: counting unexpected Chars when trying to find occurrence of the words in phpmyadmin I have a table that contains different length of sentences from one word to 40 words, and I want to count each word separately  and how many times it occurred in that table,
but whenever the sentence is containing just one word it prints unexpected Char. for some reasons any ideas why ?
this is a demo of my DB
DB demo
and this is the code
create table messages(sent varchar(200), verif int);
insert into messages values

             ('HI' , null),

             ('HI alex how are you' , null),

             ('bye' , null);

select * from messages;

UPDATE messages set sent = TRIM(sent);
UPDATE messages set sent = REGEXP_REPLACE(sent,' +',' ')

with recursive cte as (
    select
        substring(concat(sent, ' '), 1, locate(' ', sent)) word,
        substring(concat(sent, ' '), locate(' ', sent) + 1) sent
    from messages
    union all
    select
        substring(sent, 1, locate(' ', sent)) word,
        substring(sent, locate(' ', sent) + 1) sent
    from cte
    where locate(' ', sent) > 0
)
select row_number() over(order by count(*) desc, word) wid, word, count(*) freq
from cte
group by word
order by wid

out put of the code

wid word    freq
1       2
2   HI  2
3   alex    1
4   are     1
5   bye     1
6   how     1
7   you     1

expected output
wid word    freq
1   HI  2
2   alex    1
3   are     1
4   bye     1
5   how     1
6   you     1

A: Your problem is in these lines:
substring(concat(sent, ' '), 1, locate(' ', sent)) word,
substring(concat(sent, ' '), locate(' ', sent) + 1) sent

When sent doesn't contain a space, locate(' ', sent) returns 0 and substring returns an empty string, which is what you are seeing counted in your output. To fix that, use concat(sent, ' ') in place of sent:
substring(concat(sent, ' '), 1, locate(' ', concat(sent, ' '))) word,
substring(concat(sent, ' '), locate(' ', concat(sent, ' ')) + 1) sent

For your sample data this gives:
wid     word    freq
1       HI      2
2       alex    1
3       are     1
4       bye     1
5       how     1
6       you     1

Demo on dbfiddle


text:
Q: Can an invisible neutron star exist? Basically a neutron/quark star that approaches it's Schwarzschild radius but doesn't surpass it. Its gravitational force is great enough to not let light escape from it, but not great enough to become a black hole.

A: If it is not a black hole, then light can escape from it. Why? Because a black hole is defined as something light cannot escape from.

A: The answer is "no" because only for a black hole can light never escape.
However, this question deserves a fuller answer because of a thing called the "photon sphere".
At the Schwartzchild radius of a compact body - whose mass is all inside the radius - light can no longer escape.  However, at a distance which is 1.5 times the Schwartzchild radius there is a thing called the photon sphere.  Any light incident on a massive body that comes from the outside of the photon sphere and enters it will invariably be "sucked into" the body.  Light that originates within the photon sphere, but outside the Schwartzchild radius, and is directed outwards, may still escape however.  This opens up the possibility that there exist objects so massive that their mass is within a photon sphere but not within the Schwartzchild radius.  Such objects would likely be neutron stars.
Now the fun part - what do we mean by "invisible"?  If by "invisible" we mean "I shine light on it and zero of it is ever reflected" then the answer to your question is "yes"!


text:
Q: The image background can not fit the height of body content container in email template? I have problem with the image background for email template. As you see the screenshots, I want the email in Outlook for Window 7/10 will display the same as Outlook for MacOS. But unfortunately, it doesn't work. I try many times but cannot figure out the reason why the body container always has the space between it and footer container. Please help me to solve this problem! My code is below
:(enter image description here

Tak for din bestilling!

{{Name}}

{{Address}}

Tlf. {{Phone}}

Reg.nr.: {{CarReg}}

                                                                                Du har bestilt følgende:

                                                                                {{OrderLines}}

                                                                                {{Services}}

Din bookede tid:

                                                                                {{BookingTime}}
                                                                                hos
                                                                                {{Department}}

Kontakt
                                                                                din afdeling, hvis du vil ændre eller aflyse
                                                                                din booking.

Vi glæder os til
 at servicere din bil

                                                                                Hvis du har spørgsmål - eller hvis der
                                                                                er noget, der ikke stemmer, så
                                                                                ring til os på tlf. 7615 3000


text:
Q: Turn ON radio using wlan api I have requirement to turn off wireless radio using wlanapi in C#.
Iam able to turn off the radio but not able to turn on.
Here is my code:
WLAN_PHY_RADIO_STATE wlan_intf_opcode_radio_state = new WLAN_PHY_RADIO_STATE();
wlan_intf_opcode_radio_state.dwPhyIndex = 0; // TODO : can change ???
wlan_intf_opcode_radio_state.dot11HardwareRadioState = DOT11_RADIO_STATE.dot11_radio_state_on;// ignored in fact, according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms706791(v=vs.85).aspx
wlan_intf_opcode_radio_state.dot11SoftwareRadioState = DOT11_RADIO_STATE.dot11_radio_state_on;

radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(wlan_intf_opcode_radio_state));
Marshal.StructureToPtr(wlan_intf_opcode_radio_state, radioStatePtr, false);

if (WlanEnumInterfaces(handle, IntPtr.Zero,
              out ppInterfaceList) == ERROR_SUCCESS)
{

    interfaceList = new WLAN_INTERFACE_INFO_LIST(ppInterfaceList);

    for (int i = 0; i < interfaceList.dwNumberofItems; i++)
    {
        Guid pInterfaceGuid = ((WLAN_INTERFACE_INFO)interfaceList.InterfaceInfo[0]).InterfaceGuid;

        if (WlanSetInterface(handle, ref pInterfaceGuid, WLAN_INTF_OPCODE.wlan_intf_opcode_radio_state, dataSize, ref ptr, IntPtr.Zero) == ERROR_SUCCESS)
            MessageBox.Show("yes");
        else MessageBox.Show("Some Issue");

    }
}

Definition :
[DllImport("wlanapi.dll", SetLastError = true)]
public static extern uint WlanSetInterface(IntPtr hClientHandle, ref Guid      pInterfaceGuid, WLAN_INTF_OPCODE OpCode, uint dwDataSize, ref  IntPtr pData, IntPtr pReserved);

Everything going smooth I mean wlansetinterface function returning ERROR_SUCCESS but radio is not swithching on in my PC.please help where i missed ?
I fallowed How can I turn ON radio of a Wifi adapter that is actually OFF?


text:
Q: Android help with ImageView How can I draw an ImageView from the OnDraw() method? canvas.() does not have to call a resource?
I am trying to do this
        @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        imageBack = BitmapFactory.decodeResource(getResources(), R.drawable.background);
        canvas.drawBitmap(imageBack, (x /2)-15 ,y /2, null);
        //touchEvents();
        ImageView image1 = (ImageView)findViewById(R.id.ImageView01);

    }

A: Hi have improved you onDraw method plz check
 @Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    imageBack = BitmapFactory.decodeResource(getResources(), R.drawable.background);
    imageBack.setBounds(0,0,getWidth(),getHeight());
    imageBack.draw(canvas);

}

you are not very much clear. so if you find any diffuculty you can add comment to my post


text:
Q: data-popup: lightbox cant popup with error (Not allowed to navigate top frame to data URL: data:image/jpeg;base64) my table with the picture
.. I have a problem, my image won't appear in the popup, i use data-popup:lightbox.
My code:

i got an error:

Not allowed to navigate top frame to data URL: data:image/jpeg;base64,


text:
Q: iPhone: Increment badge counter automatically
Possible Duplicate:
Push-Notification Badge auto increment.

I have implemented Push Notification for my iPhone application. Whenever I get the message, I want to increment badge value by one so I need not to pass it in Push Notification payload. Is it possible?
From here I learnt that I have to manage that from server side, so that's the only way? I had to store the previous value in Database and get the last value whenever I send next message? Isn't Apple support this automatically like incrementing application.applicationIconBadgeNumber whenever Push Notification received.
The problem with managing Badge number from server side is if user has already seen the previous Push Notification message, you would send wrong badge number!

A: It's not really a problem. The client just needs to let the server know what messages it has seen. Everyone else is doing it, so just learn how to do it and do it.
EDIT: You can set the badge counter using:
[UIApplication sharedApplication].applicationIconBadgeNumber = badgeCount;

Every time you do, you should send badgeCount to the server, so that the server knows the current count.


text:
Q: Is it a good practice to do something based on other components name in Vue.js? Is it considered a good practice to set a condition and run some code based on other component's name?
For example I have a reusable child component, and want one of it's methods to stop and not run when it is rendered as a child of a specific component, so I would have something like this inside that method:
   methodName() {
     if(this.$parent.$options.name == 'someSpecificName')
     {
        // prevent rest of the function if child of specific component
        return;
     }
     else {
        // continue the function when rendered inside other components
     }
   }

EDIT:
So to further clarify my question, I have a method inside the child component than runs normally when the particular event is fired, but what I want to do is prevent that method when it is being rendered inside of a specific parent component.

A: I would instead set a Boolean prop in the child component and make the method fire, if that prop is set to true.
Example:
// Child component
props: {
  runSomeMethod: {
     type: Boolean,
     default: false
  }
},
mounted() {
   if (this.runSomeMethod) {
     this.functionToRun();
   }
}
methods: {
   functionToRun() {
      // some code
   }
}

// Parent
<template>
  <child-component
    :run-some-method="true">
  </child-component>
</template>


text:
Q: Что означает данный селектор $("#"+ajax_form)? Есть форма.
<form id="ajax_form"></form>

И Ajax запрос.
$.ajax({
    data: $("#"+ajax_form).serialize()
});

Тоже самое что и $("#ajax_form") ???

A: Смысл записи
$("#"+ajax_form)

в том что в функцию $ будет передан селектор с именем состоящим из # и значения переменной ajax_form.
Например, если где-то есть
var ajax_form = "mySuperSelector";`

то вы получите
$('#mySuperSelector')

И будет искаться элемент с id="mySuperSelector".
Почему и кто написал такое - мы здесь разбираться не будем. Вероятно, это просто опечатка и код должен быть просто:
$("#ajax_form")


text:
Q: How can I sort a text file from number of occupied lines? How could I sort a text files from number of ocupied lines?
From:
`He spoke to her, saying, "Dear child, can my servant and I find shelter for the night in this little house?"
"Oh, yes," said the girl in a sad voice, "You certainly can, but I do not advise you to do so. Do not go inside."
"Why not?" asked the prince.
The girl sighed and said, "My stepmother practices evil arts, and she does not like strangers."
Then he realized that he had come to a witch's house, but because it was dark, and he could go no further, he entered. In any event, he was not afraid.
The old woman was sitting in an armchair by the fire. She looked at the stranger with her red eyes. "Good evening," she croaked,
pretending to be quite friendly. "Sit down and rest."
She blew into the coals on which she was cooking something in a small pot. The daughter warned the two to be cautious, to eat nothing, and to drink nothing, for the old woman brewed evil drinks. They slept soundly until early morning.
After traveling about for a long time they came to a town where there was a beautiful but proud princess. She had made it known that she would marry any man who could ask her a riddle that she could not solve. However, if she solved it his head would be cut off. She had three days to think about it, but was so clever that she always solved the riddle that she had been given before the deadline. When the prince arrived nine men had already died in this manner. However, he was blinded by her great beauty and was willing to risk his life for it.´
To:
´After traveling about for a long time they came to a town where there was a beautiful but proud princess. She had made it known that she would marry any man who could ask her a riddle that she could not solve. However, if she solved it his head would be cut off. She had three days to think about it, but was so clever that she always solved the riddle that she had been given before the deadline. When the prince arrived nine men had already died in this manner. However, he was blinded by her great beauty and was willing to risk his life for it.
pretending to be quite friendly. "Sit down and rest."
She blew into the coals on which she was cooking something in a small pot. The daughter warned the two to be cautious, to eat nothing, and to drink nothing, for the old woman brewed evil drinks. They slept soundly until early morning.
Then he realized that he had come to a witch's house, but because it was dark, and he could go no further, he entered. In any event, he was not afraid.
The old woman was sitting in an armchair by the fire. She looked at the stranger with her red eyes. "Good evening," she croaked,
"Oh, yes," said the girl in a sad voice, "You certainly can, but I do not advise you to do so. Do not go inside."
"Why not?" asked the prince.
He spoke to her, saying, "Dear child, can my servant and I find shelter for the night in this little house?"
The girl sighed and said, "My stepmother practices evil arts, and she does not like strangers."´

A: With GNU Awk version 4.0+
gawk '
  BEGIN {RS=""; ORS="\n\n"}
  {a[$0] = length($0)}
  END {
    PROCINFO["sorted_in"] = "@val_num_desc"
    for (i in a) print i
  }
' file.txt

Note that this sorts on number of characters, including punctuation and whitespace.

A: Used this not so optimized command line:
cat -n notes.txt | sort -rn | head -6 >> result.txt && \
cat -n notes.txt | sort -rn | tail -5 | sort -n | head -3 | sort -rn >> result.txt && \
cat -n notes.txt | sort -rn | tail -5 | sort -n | tail -2 >> result.txt && \
sed -i 's/^\s*[[:digit:]]*\s*//g' result.txt

Information: It splits the whole texts into parts and then puts sort and puts them together and removes the line numbers used to sort them.
Results:
After traveling about for a long time they came to a town where there was a beautiful but proud princess. She had made it known that she would marry any man who could ask her a riddle that she could not solve. However, if she solved it his head would be cut off. She had three days to think about it, but was so clever that she always solved the riddle that she had been given before the deadline. When the prince arrived nine men had already died in this manner. However, he was blinded by her great beauty and was willing to risk his life for it.
pretending to be quite friendly. "Sit down and rest." She blew into the coals on which she was cooking something in a small pot. The daughter warned the two to be cautious, to eat nothing, and to drink nothing, for the old woman brewed evil drinks. They slept soundly until early morning.
Then he realized that he had come to a witch's house, but because it was dark, and he could go no further, he entered. In any event, he was not afraid. The old woman was sitting in an armchair by the fire. She looked at the stranger with her red eyes. "Good evening," she croaked,
"Oh, yes," said the girl in a sad voice, "You certainly can, but I do not advise you to do so. Do not go inside." "Why not?" asked the prince.
He spoke to her, saying, "Dear child, can my servant and I find shelter for the night in this little house?"
The girl sighed and said, "My stepmother practices evil arts, and she does not like strangers."


text:
Q: Transforming Roman numbers to correct Arabic numerals by transforming an XML file via XSLT I have the following xml input:
<root>
    <calc>
        <roman>XLIV</roman>
    </calc>
    <calc>
        <roman>DCXI</roman>
    </calc>
</root>

I want to output the following:
<root>
    <calc>
        <roman>XLIV</roman>
        <arab>44</arab>
    </calc>
    <calc>
        <roman>DCXI</roman>
        <arab>611</arab>
    </calc>
</root>

By writing a XSLT. So far I wrote this XSLT but what else needs to be done to output the right result?

<xsl:transform
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:num="http://whatever"
  version="2.0">

  <xsl:output method="xml" version="1.0"
    encoding="UTF-8" indent="yes"/>

  <!-- identity transform -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:function name="num:roman" as="xs:string">
    <xsl:param name="value" as="xs:integer"/>
    <xsl:number value="$value" format="i"/>
  </xsl:function>

</xsl:transform>

Extra rules for validating Roman numbers:
Several rules apply for subtracting amounts from Roman numerals:

*

*Only subtract powers of ten (I, X, or C, but not V or L)

Ex: For 95, do NOT write VC (100 – 5). DO write XCV (XC + V or 90 + 5)

*

*Only subtract one number from another

Ex: For 13, do NOT write IIXV (15 – 1 - 1).
DO write XIII (X + I + I + I or 10 + 3)

*

*Do not subtract a number from one that is more than 10 times greater (that is, you can subtract 1 from 10 [IX] but not 1 from 20—there is no such number as IXX.)

Ex: For 99, do NOT write IC (C – I or 100 - 1).
DO write XCIX (XC + IX or 90 + 9)

A: You have to more clear in function as see in XSLT 2.0
<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:num="http://whatever"
    version="2.0" exclude-result-prefixes="xs num">

    <xsl:output method="xml" version="1.0"
        encoding="UTF-8" indent="yes"/>

    <!-- identity transform -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="roman">
        <xsl:copy-of select="."/>
        <arab><xsl:choose>
            <xsl:when test="matches(., '[^IVXLCDM]|II[^I]|IIII+|XXXX+|CCCC+|V[^I]|[^I]?I[VIX][IVXLCDM]|[^I]?I[^VIX]')">
                <xsl:comment>Your Message about Not Roman Data</xsl:comment>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="num:roman(., 0)"></xsl:value-of>
            </xsl:otherwise>
        </xsl:choose>
        </arab>
    </xsl:template>

    <xsl:function name="num:roman" as="xs:integer">
        <xsl:param name="r" as="xs:string"/>
        <xsl:param name="s"/>
        <xsl:choose>
            <xsl:when test="ends-with($r,'CM')">
                <xsl:sequence select="900 + num:roman(substring($r,1,string-length($r)-2), 900)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'M')">
                <xsl:sequence select="1000+ num:roman(substring($r,1,string-length($r)-1), 1000)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'CD')">
                <xsl:sequence select="400+ num:roman(substring($r,1,string-length($r)-2), 400)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'D')">
                <xsl:sequence select="500+ num:roman(substring($r,1,string-length($r)-1), 500)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'XC')">
                <xsl:sequence select="90+ num:roman(substring($r,1,string-length($r)-2), 90)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'C')">
                <xsl:sequence select="(if(100 ge number($s)) then 100 else -100)+ num:roman(substring($r,1,string-length($r)-1), 100)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'XL')">
                <xsl:sequence select="40+ num:roman(substring($r,1,string-length($r)-2), 40)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'L')">
                <xsl:sequence select="50+ num:roman(substring($r,1,string-length($r)-1), 50)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'IX')">
                <xsl:sequence select="9+ num:roman(substring($r,1,string-length($r)-2), 9)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'X')">
                <xsl:sequence select="(if(10 ge number($s)) then 10 else -10) + num:roman(substring($r,1,string-length($r)-1), 10)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'IV')">
                <xsl:sequence select="4+ num:roman(substring($r,1,string-length($r)-2), 4)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'V')">
                <xsl:sequence select="5+ num:roman(substring($r,1,string-length($r)-1), 5)"/>
            </xsl:when>
            <xsl:when test="ends-with($r,'I')">
                <xsl:sequence select="(if(1 ge number($s)) then 1 else -1)+ num:roman(substring($r,1,string-length($r)-1), 1)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:sequence select="0"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:function>

</xsl:transform>


text:
Q: Python DBM Module for Windows? I would like to use the dbm module on my Windows machine, but it is currently only supported on Unix. http://docs.python.org/library/dbm.html
Does anyone know of a similar module with similar syntax or a workaround to get dmb functional on windows? Being able to access a database written to the hard drive much like how I code to access a dictionary would be great. Thank you for your help!

A: Actually, after more googling around, I found this:
http://docs.python.org/library/anydbm.html#module-anydbm
I've tried this on windows and it seems to be working fine =)

A: Based on the following test on a Windows 7 system using Python 2.7.2 it appears that dbhash is supported on Windows instalations.
import os

import anydbm

import whichdb

file = os.curdir + '/testdbm'   # define a test file name in the current directory

d = anydbm.open(file, 'c')      # create a new database using the test file name

db_type = whichdb.whichdb(file) # get the dbm database type

print(db_type)                  # display the result

'dbhash'

A: If Python 3 is of relevance, I'd go for an external k-v solution, as dumbdbm is no joy.
Some pure Python options:

*

*semidbm - A faster alternative to dumbdbm, Python standard library only, pip and go. The one I'd go for if I want to ensure portability and availability to users.

*PickleDB - Uses json to serialize data. Standrad library only, I haven't benchmarked but I suspect it's slower than semidbm because of the serialization overhead.

*Petite DB - My own simple workaround using Python's zipfile module. Basic testing in the books but it's not production ready.
There are also Python wrappers to LMDB, UnQLite and SQLite4 LSM, all of which support Windows, though the SQLite4 bindings weren't tested.
The latter two are by Charles Leifer, who is both savvy with k-v stores and an avid Python developer (see Peewee).
As far as LMDB, I've tried it for a while. No complaints, but it uses a transactional model, where you can't use it dictionary-style like with other dbm's, unless you subclass/compose/submit a pull request etc.
Also, it explicitly doesn't utilize compression (see also) which was something I was interested in.
So LMDB just didn't quite fit my specific needs. It does seem to be highly capable, the bindings worked fine, and installing them was untroublesome (pip worked for me, had no need to install LMDB seperately or any nuisance to that effect).

A: I think anydbm on Windows will only load dumbdbm, since all the other modules appear to be Unix only. According to the Python documentation...

"The dumbdbm module is intended as a last resort fallback for the
  anydbm module when no more robust module is available. The dumbdbm
  module is not written for speed and is not nearly as heavily used as
  the other database modules."


text:
Q: What does this mean in vectors in c++? vector<int> v[1000];

Is this for reserving space for the vector? But isn't the command for reserving space ()? What does this do?

A: That is an array, with each element being a vector, so there are 1000 default-constructed (empty) vectors.
However, if you wanted to make a single vector of 1000 int, you would say
vector<int> v(1000);


text:
Q: Rename multiple columns based on pattern search I am importing an excel file with a lot of indentation in the row values. These indentations are used to specify categories and subcategories. When I port the file to pandas, there are lot of unnamed columns created like:

['Levels in Millions ', 'Unnamed: 1', 'Unnamed: 2', 'Unnamed: 3',
  ' ',
         'Total National Health Expenditures', 'Hospital Care',
         'Physician and Clinical Services', 'Other Professional Services',
         'Dental Services', 'Unnamed: 10',
         'Other Health, Residential, and Personal Care', 'Home Health Care',
         'Nursing Care Facilities and Continuing Care Retirement Communities',
         'Unnamed: 14', 'Prescription Drugs', 'Durable Medical Equipment',
         'Other Non-durable Medical Products', 'Unnamed: 18', 'Unnamed: 19',
         'State', 'Federal', 'Net Cost of Health Insurance',
         ' Government Public Health Activities', 'Unnamed: 24', 'Research',
         'Structures', 'Equipment']

I have tried a couple of things:
    type_of_prog_1.columns= type_of_prog_1.columns.str.replace('Unnamed: *',
    '')
    type_of_prog_1= type_of_prog_1.rename(columns=lambda x:
    x.replace('Unnamed: *', 'Level: *'))

The output is that the columns gets numbers as 1, 2, 3, etc. The numbered columns makes it difficult for slicing, later.
Ideally, I want the columns to be named as "Level 1" or Level 2" based on the numbers after "Unnamed". Because there are 24 Unnamed columns, I don't want to do this- {"Unnamed 1": "Level 1",...}

A: Based on your description of the problem, you could call Index.str.replace:
df.columns = df.columns.str.replace('Unnamed:', 'Level')


text:
Q: Unpack large zips in parts with PHP into a folder I am trying to unzip a zip file containing maybe over 1500 pdf files. The compressed file should be unpacked in parts into a folder to not overflow the server memory with a 20mb file at once.
I already found an example on how to unzip in parts. However, this method does not create a directory or something in which the unpacked files can be viewed. It only creates one file, which is not a directory, which seems like to be a new zip again.
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w+");

while ($string = gzread($sfp, 4096)) {
    fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);

This function creates some file that seems like yet an other zip file, as explained above. If I create the folder I want to unzip it to first and use that as $dstName, it gives a warning that it can not find the file. Also when I let it create a "file" with a "/" at the end of the destination link it gives that warning.
Using opendir instead of fopen does not give a warning, but nothing seems to be extracted then, guess the handler is of some wrong type.
How can I unzip this large compressed file in parts into a folder?

A: (PK)Zip and GZip are two completely different formats; gzopen cannot open zip archives.
To unpack PKZip archives, take a look at the PHP Zip extension.

A: <?php

function unzip($file) {
    $zip = zip_open($file);
    if (is_resource($zip)) {
        $tree = "";
        while (($zip_entry = zip_read($zip)) !== false) {
            echo "Unpacking " . zip_entry_name($zip_entry) . "\n";
            if (strpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR) !== false) {
                $last = strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR);
                $dir = substr(zip_entry_name($zip_entry), 0, $last);
                $file = substr(zip_entry_name($zip_entry), strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR) + 1);
                if (!is_dir($dir)) {
                    @mkdir($dir, 0755, true) or die("Unable to create $dir\n");
                }
                if (strlen(trim($file)) > 0) {
                    //Downloading in parts
                    $fileSize = zip_entry_filesize($zip_entry);
                    while ($fileSize > 0) {
                        $readSize = min($fileSize, 4096);
                        $fileSize -= $readSize;
                        $content = zip_entry_read($zip_entry, $readSize);
                        if ($content !== false) {
                            $return = @file_put_contents($dir . "/" . $file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                            if ($return === false) {
                                die("Unable to write file $dir/$file\n");
                            }
                        }
                    }
                }
                fclose($outFile);
            } else {
                file_put_contents($file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
            }
        }
    } else {
        echo "Unable to open zip file\n";
    }
}

unzip($_SERVER['DOCUMENT_ROOT'] . '/test/testing.zip');
?>


text:
Q: Tensorflow Object Detection API quantization with output tensor as TFLite_Detection_PostProcess I am in the process of performing a full 8-bit quantization of ssd_mobilenet_v2_320x320_coco17 using Object detection API. For this I run the following notebook.
In my case my final hardware requires that the output tensors are TFLite_Detection_PostProcess (they actually can be float32). However, when performing post-training quantization, with the Object detection API, the final tflite output tensors are StatefulPartitonedCall, which are not accepted by the application running on the mcu. So somehow I need to convert to TFLite_Detection_PostProcess.
Some searching reveales that some are using converter = tf.lite.TFLiteConverter.from_frozen_graph(... output_array=output_array...) for convertion where they use
output_arrays = ['TFLite_Detection_PostProcess',
           'TFLite_Detection_PostProcess:1',
           'TFLite_Detection_PostProcess:2',
           'TFLite_Detection_PostProcess:3']

In my case the notebook is using converter = tf.lite.TFLiteConverter.from_saved_model(...) which does not accept an parameter such as output_array.
So, can I quantize using tf.lite.TFLiteConverter.from_saved_model and define my output tensors to TFLite_Detection_PostProcess?
See also TF Object detection API issue tracker TF2 Detection API Models on mobile TFLite_Detection_PostProcess #10130


text:
Q: How to implement the MapReduce example in Erlang efficiently? I am trying to compare the performance of concurrent programming languages, such as Haskell, Go and Erlang. The following Go code calculates the sum of squares, ( repeat calculate the sum of squares for R times):

1^2+2^2+3^2....1024^2

package main

import "fmt"

func mapper(in chan int, out chan int) {
    for v := range in {out <- v*v}
}

func reducer(in1, in2 chan int, out chan int) {
    for i1 := range in1 {i2 := <- in2; out <- i1 + i2}
}

func main() {
    const N = 1024  // calculate sum of squares up to N; N must be power of 2
    const R = 10  // number of repetitions to fill the "pipe"

    var r [N*2]chan int
    for i := range r {r[i] = make(chan int)}
    var m [N]chan int
    for i := range m {m[i] = make(chan int)}

    for i := 0; i < N; i++ {go mapper(m[i], r[i + N])}
    for i := 1; i < N; i++ {go reducer(r[i * 2], r[i *2 + 1], r[i])}

    go func () {
        for j := 0; j < R; j++ {
            for i := 0; i < N; i++ {m[i] <- i + 1}
        }
    } ()

    for j := 0; j < R; j++ {
        <- r[1]
    }
}

The following code is the MapReduce solution in Erlang. I am a newbie to Erlang.  I would like to compare performance among Go, Haskell and Erlang. My question is how to optimize this Erlang code. I compile this code by using erlc -W mr.erl and run the code by using erl -noshell -s mr start -s init stop -extra 1024 1024. Are there any special compile and execution options available for optimizations? I really appreciate any help you can provide.
-module(mr).
-export([start/0, create/2, doreduce/2, domap/1, repeat/3]).

start()->
    [Num_arg|Repeat] = init:get_plain_arguments(),
    N = list_to_integer(Num_arg),
    [R_arg|_] = Repeat,
    R = list_to_integer(R_arg),
    create(R, N).

create(R, Num) when is_integer(Num), Num > 0 ->
    Reducers = [spawn(?MODULE, doreduce, [Index, self()]) || Index <- lists:seq(1, 2*Num - 1)],
    Mappers = [spawn(?MODULE, domap, [In]) || In <- lists:seq(1, Num)],
    reducer_connect(Num-1, Reducers, self()),
    mapper_connect(Num, Num, Reducers, Mappers),
    repeat(R, Num, Mappers).

repeat(0, Num, Mappers)->
    send_message(Num, Mappers),
    receive
        {result, V}->
            %io:format("Repeat: ~p ~p ~n", [0, V])
            true
    end;
repeat(R, Num, Mappers)->
    send_message(Num, Mappers),
    receive
        {result, V}->
            %io:format("Got: ~p ~p ~n", [R, V])
            true
    end,
    repeat(R-1, Num, Mappers).
send_message(1, Mappers)->
    D = lists:nth (1, Mappers),
    D ! {mapper, 1};
send_message(Num, Mappers)->
    D = lists:nth (Num, Mappers),
    D ! {mapper, Num},
    send_message(Num-1, Mappers).

reducer_connect(1, RList, Root)->
    Parent = lists:nth(1, RList),
    Child1 = lists:nth(2, RList),
    Child2 = lists:nth(3, RList),
    Child1 ! {connect, Parent},
    Child2 ! {connect, Parent},
    Parent !{connect, Root};
reducer_connect(Index, RList, Root)->
    Parent = lists:nth(Index, RList),
    Child1 = lists:nth(Index*2, RList),
    Child2 = lists:nth(Index*2+1, RList),
    Child1 ! {connect, Parent},
    Child2 ! {connect, Parent},
    reducer_connect(Index-1, RList, Root).

mapper_connect(1, Num, RList, MList)->
    R = lists:nth(Num, RList),
    M = lists:nth(1, MList),
    M ! {connect, R};
mapper_connect(Index, Num, RList, MList) when is_integer(Index), Index > 0 ->
    R = lists:nth(Num + (Index-1), RList),
    M = lists:nth(Index, MList),
    M ! {connect, R},
    mapper_connect(Index-1, Num, RList, MList).

doreduce(Index, CurId)->
    receive
        {connect, Parent}->
            doreduce(Index, Parent, 0, 0, CurId)
    end.
doreduce(Index, To, Val1, Val2, Root)->
    receive
        {map, Val} ->
            if Index rem 2 == 0 ->
                To ! {reduce1, Val},
                doreduce(Index, To, 0, 0, Root);
            true->
                To ! {reduce2, Val},
                doreduce(Index, To, 0, 0, Root)
            end;
        {reduce1, V1} when Val2 > 0, Val1 == 0 ->
            if Index == 1 ->% root node
                Root !{result, Val2 + V1},
                doreduce(Index, To, 0, 0, Root);
            Index rem 2 == 0 ->
                To ! {reduce1, V1+Val2},
                doreduce(Index, To, 0, 0, Root);
            true->
                To ! {reduce2, V1+Val2},
                doreduce(Index, To, 0, 0, Root)
            end;
        {reduce2, V2} when Val1 > 0, Val2 == 0 ->
            if Index == 1 ->% root node
                Root !{result, Val1 + V2},
                doreduce(Index, To, 0, 0, Root);
            Index rem 2 == 0 ->
                To ! {reduce1, V2+Val1},
                doreduce(Index, To, 0, 0, Root);
            true->
                To ! {reduce2, V2+Val1},
                doreduce(Index, To, 0, 0, Root)
            end;
        {reduce1, V1} when Val1 == 0, Val2 == 0 ->
            doreduce(Index, To, V1, 0, Root);
        {reduce2, V2} when Val1 == 0, Val2 == 0 ->
            doreduce(Index, To, 0, V2, Root);
        true->
            true
    end.

domap(Index)->
    receive
       {connect, ReduceId}->
            domap(Index, ReduceId)
    end.

domap(Index, To)->
    receive
        {mapper, V}->
            To !{map, V*V},
            domap(Index, To);
        true->
            true
    end.

A: Despite it is not a good task for Erlang at all, there is a quite simple solution:
-module(mr).

-export([start/1, start/2]).

start([R, N]) ->
    Result = start(list_to_integer(R), list_to_integer(N)),
    io:format("~B x ~B~n", [length(Result), hd(Result)]).

start(R, N) ->
    Self = self(),
    Reducer = start(Self, R, 1, N),
    [ receive {Reducer, Result} -> Result end || _ <- lists:seq(1, R) ].

start(Parent, R, N, N) ->
    spawn_link(fun() -> mapper(Parent, R, N) end);
start(Parent, R, From, To) ->
    spawn_link(fun() -> reducer(Parent, R, From, To) end).

mapper(Parent, R, N) ->
    [ Parent ! {self(), N*N}  || _ <- lists:seq(1, R) ].

reducer(Parent, R, From, To) ->
    Self = self(),
    Middle = ( From + To ) div 2,
    A = start(Self, R, From, Middle),
    B = start(Self, R, Middle + 1, To),
    [ Parent ! {Self, receive {A, X} -> receive {B, Y} -> X+Y end end}
      || _ <- lists:seq(1, R) ].

You can run it using
$ erlc -W mr.erl
$ time erl -noshell -run mr start 1024 1024 -s init stop
1024 x 358438400

real    0m2.162s
user    0m4.177s
sys     0m0.151s

But most of the time is VM start and gracefull stop overhead
$ time erl -noshell -run mr start 1024 1024 -s erlang halt
1024 x 358438400

real    0m1.172s
user    0m4.110s
sys     0m0.150s

$ erl
1> timer:tc(fun() -> mr:start(1024,1024) end).
{978453,
 [358438400,358438400,358438400,358438400,358438400,
  358438400,358438400,358438400,358438400,358438400,358438400,
  358438400,358438400,358438400,358438400,358438400,358438400,
  358438400,358438400,358438400,358438400,358438400,358438400,
  358438400,358438400,358438400,358438400|...]}

Keep in mind it is more like an elegant solution than an efficient one. An efficient solution should balance reduction tree branching with communication overhead.


text:
Q: cufft 1D complex to complex transform I'm trying to write a simple code for fft 1d transform using cufft library.
I use as example the code on cufft library tutorial (link)but data before transformation and after the inverse transform arent't same. Why ?
this is output :
[1DCUFFT] starting...

[1DCUFFT] is starting...
Transforming signal cufftExecC2C
Transforming signal back cufftExecC2C
first : 0.840188 0.000000  after 2.020520 -2.465333
first : 0.394383 0.000000  after 2.690347 -2.105700
first : 0.783099 0.000000  after 3.155561 -1.491952
first : 0.798440 0.000000  after 3.309971 -0.761629
first : 0.911647 0.000000  after 3.139909 -0.092953
first : 0.197551 0.000000  after 2.734147 0.355526
first : 0.335223 0.000000  after 2.256154 0.501509
first : 0.768230 0.000000  after 1.887422 0.369626
first : 0.277775 0.000000  after 1.762471 0.083391
first : 0.553970 0.000000  after 1.920150 -0.179526
first : 0.477397 0.000000  after 2.289955 -0.252255
first : 0.628871 0.000000  after 2.718623 -0.039409
first : 0.364784 0.000000  after 3.026649 0.449287
first : 0.513401 0.000000  after 3.072947 1.104457
first : 0.952230 0.000000  after 2.803322 1.758350
first : 0.916195 0.000000  after 2.265463 2.245056

this is my source code, tutorial example suggest to divide output for dataset size to have same values.
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

// includes, project
#include <cufft.h>
#include <cutil_inline.h>
#include <shrQATest.h>
void runTest(int argc, char** argv);

// The filter size is assumed to be a number smaller than the signal size
#define SIGNAL_SIZE        16

////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
    runTest(argc, argv);
}

////////////////////////////////////////////////////////////////////////////////
//! Run a simple test for CUDA
////////////////////////////////////////////////////////////////////////////////
void runTest(int argc, char** argv)
{

    printf("[1DCUFFT] is starting...\n");

    if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") )
        cutilDeviceInit(argc, argv);
    else
        cudaSetDevice( cutGetMaxGflopsDeviceId() );
    cufftComplex* h_signal=(cufftComplex*)malloc(sizeof(cufftComplex) * SIGNAL_SIZE);
    // Allocate host memory for the signal
    //Complex* h_signal = (Complex*)malloc(sizeof(Complex) * SIGNAL_SIZE);
    // Initalize the memory for the signal
    for (unsigned int i = 0; i < SIGNAL_SIZE; ++i) {
        h_signal[i].x = rand() / (float)RAND_MAX;
        h_signal[i].y = 0;
    }

    int mem_size = sizeof(cufftComplex) * SIGNAL_SIZE;

    // Allocate device memory for signal
    cufftComplex* d_signal;
    cutilSafeCall(cudaMalloc((void**)&d_signal, mem_size));

    // Copy host memory to device
    cutilSafeCall(cudaMemcpy(d_signal, h_signal, mem_size,
                              cudaMemcpyHostToDevice));

    // CUFFT plan
    cufftHandle plan;
    cufftSafeCall(cufftPlan1d(&plan, mem_size, CUFFT_C2C, 1));

    // Transform signal
    printf("Transforming signal cufftExecC2C\n");
    cufftSafeCall(cufftExecC2C(plan, (cufftComplex *)d_signal, (cufftComplex *)d_signal, CUFFT_FORWARD));

    // Transform signal back
    printf("Transforming signal back cufftExecC2C\n");
    cufftSafeCall(cufftExecC2C(plan, (cufftComplex *)d_signal, (cufftComplex *)d_signal, CUFFT_INVERSE));

    // Copy device memory to host
    cufftComplex* h_inverse_signal = (cufftComplex*)malloc(sizeof(cufftComplex) * SIGNAL_SIZE);;
    cutilSafeCall(cudaMemcpy(h_inverse_signal, d_signal, mem_size,
                              cudaMemcpyDeviceToHost));

    for(int i=0;i< SIGNAL_SIZE;i++){
        h_inverse_signal[i].x= h_inverse_signal[i].x/(float)SIGNAL_SIZE;
        h_inverse_signal[i].y= h_inverse_signal[i].y/(float)SIGNAL_SIZE;

        printf("first : %f %f  after %f %f \n",h_signal[i].x,h_signal[i].y,h_inverse_signal[i].x,h_inverse_signal[i].y);
    }

    //Destroy CUFFT context
    cufftSafeCall(cufftDestroy(plan));

    // cleanup memory
    free(h_signal);

    free(h_inverse_signal);
    cutilSafeCall(cudaFree(d_signal));
    cutilDeviceReset();
}

A: You need to change:
cufftSafeCall(cufftPlan1d(&plan, mem_size, CUFFT_C2C, 1));

to:
cufftSafeCall(cufftPlan1d(&plan, SIGNAL_SIZE, CUFFT_C2C, 1));

(cufftPlan1d needs the number of data points, not the memory size in bytes!)


text:
Q: How to format number with minus at right side? How to format number with minus at right side?
I have xml:

<Invoice>
<TotalAmount>890.09-</TotalAmount>
</Invoice>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">
  <xsl:decimal-format decimal-separator="," grouping-separator="."/>

  <xsl:template match="/Invoice">
   <xsl:value-of select="format-number(TotalAmount, '#.###,00')"/>
  </xsl:template>

</xsl:stylesheet>

I think is ok but I have specific requirement, for negativs minus sign is at right side of number instead left side. How to display number in format: '#.###,00' with minus at right side. Should I read value without minus and after that append minus?
Is it better solution?

A: I think removing the minus prior to the format number, and then re-appending it, might be the only way to go
Here is one way you could do that, in a single expression
<xsl:value-of select="concat(format-number(translate(TotalAmount, '-', ''), '#.###,00'), translate(TotalAmount, '01234567890.,', ''))"/>


text:
Q: dbms_output.put is not printing data I have a simple program in plsql. Basically the program has no errors but is not printing output when I use dbms_output.put.
declare
v_name varchar(30);
v_len number;
v_number number;
  begin
    v_name := '&name';
    v_number := length(v_name);
    while v_number > 0
    loop
      dbms_output.put(v_number||'::'||substr(v_name,v_number,1));
      v_number := v_number - 1;
    end loop;
  end;

The above program produces output when I use dbms_output.put_line but the output has new line after ever character and I would like to have the output in a single horizontal line. On using dbms_output.put it doesn't throw any error but it just gives me the message:
"anonymous block completed"
Please let me know if am doing anything wrong.
Thanks,
Dex.

A: Try this: Just add dbms_output.put_line('') or dbms_output.new_line at the end of the loop.
declare
v_name varchar(30);
v_len number;
v_number number;
  BEGIN

    v_name := :name;
    v_number := length(v_name);
    while v_number > 0
    loop
      dbms_output.put(v_number||'::'||substr(v_name,v_number,1)|| ' ' );
      v_number := v_number - 1;
    END loop;

    dbms_output.new_line;
  end;

P.S. Please refrain from using '&' for substitution variable (&name) in pl/sql since its a feature supported by SQL*Plus. Instead, use bind variable like this :name

A: DBMS_OUTPUT does not appear to flush the buffer until a new line is sent; you can either use DBMS_OUTPUT.PUT_LINE( NULL ) or DBMS_OUTPUT.NEW_LINE like this:
SET SERVEROUTPUT ON;
declare
v_name varchar(30);
v_len number;
v_number number;
begin
  v_name := '&name';
  v_number := length(v_name);
  while v_number > 0
  loop
    dbms_output.put(v_number||'::'||substr(v_name,v_number,1));
    v_number := v_number - 1;
  end loop;
  DBMS_OUTPUT.NEW_LINE;
end;
/


text:
Q: How to create an event when the animation ends? 1 - How to create an event when the animation ends?
Animation written in css3
2 - How to Play the animation only when all data loaded in the browser ?
You can see
Many Thx.
Demo jsFiddle

A: 1 -You need to add an animationEnd event listener
document.getElementById('animation-03').addEventListener('animationend', function () {
    alert('end')
}, false);

Make sure you add it for all browser vendors.
Here is a forked version: http://jsfiddle.net/Fj2vF/2/
2 - Do not worry about this. As the W3C specks say your animation will start only when everything is loaded.

A: Initiating and then handling css3 animations with Javascript/jQuery is quite easy.
Check example here
You can use js library  Move.js for it.


text:
Q: How to make a c++ project from command prompt? Note that this is referred to make a project from command prompt, not build or run it, by "make", i mean, creating a .vcxproj file like Visual Studio does.
I am unable to use Visual Studio for now, this is why i'm asking to make a project through cmd, i tried gcc, but it doesn't generate these project stuff.

A: The vcxproj format provides information the MSBuild tool to control the build process. It's an XML file that is automatically created by Visual Studio, but its possible to make it manually by writing the XML yourself, and then specifying the file when invoking MSBuild from the cmd prompt.
See this walkthrough in the MS docs, and this reference to the vcxproj format if you want it to work when you regain access to VS.
Alternatively, if you're not absolutely required to use Visual Studio and the Visual C++ ecosystem, then it might be worth exploring other build systems as suggested in other answers/comments.

A: GCC is just a compiler, rather than a full IDE like Visual Studio. It takes source code (and some binary libraries), and then outputs compiled executables or object files.
You can use a build system like CMake or Meson, which can make the building process easier for you and those who clone your code, and can even be integrated into Visual Studio. You can actually use CMake to convert projects into Visual Studio format.


text:
Q: One selection only in listview I'm having problem to find solution to make a single selection row in the listview in my WPF application.
How should I do it?

A: ListView in WPF has SelectionMode="Single" .

A: SelectionMode="Single"?

A: The answer above is for ListBox, not ListView .
For a ListView you set the MultiSelect property to False (can be done via the Designer).


text:
Q: array of images in Jupyter Markdown How can I show two pictures side by side in Jupyter Markdown?
from IPython.core.display import Image, display, HTML
Image('C:/Temp/Sketch1.jpg')
Image('C:/Temp/Sketch2.jpg')

A: My solution implements HTML code in a markdown cell:

The cell is run to render the result.
Sample output:

A: You will need to use PIL and numpy for this:
import numpy as np
from IPython.core.display import display
from PIL import Image

img1 = Image.open('C:/Temp/Sketch1.jpg')
img2 = Image.open('C:/Temp/Sketch2.jpg')
display(Image.fromarray(np.concatenate((img1, img2), axis=1)))

You could define a function that takes multiple file names and displays all the images side by side:
def sidebyside(*args):
    imgs = np.concatenate([np.asarray(Image.open(x)) for x in args], axis=1)
    display(Image.fromarray(imgs))

sidebyside('C:/Temp/Sketch1.jpg', 'C:/Temp/Sketch2.jpg')

I hope this helps.


text:
Q: BackboneJS return PHP array to [object object] I'm new to BackboneJS and Jquery so I have a problem when trying to return JSON data from php array.
this is my code:
Model:
var NoteModel = Backbone.Model.extend({
    initialize:function(){
    console.log('Model initialize');
        },
    url : '../www/api/controller.php'
});

View:
var NoteView = Backbone.View.extend({
    el : '#result',
    // /var note = new NoteModel();
    //template : _.template($("#result-view-template").html()),
    initialize:function(){
        console.log('View initialize');
    },
    render :function(){
         //var note = new NoteModel();
         var note = new NoteModel();
         var template = _.template($("#result-view-template").html(),{result : note});
         this.$el.html(template);
         return this;
    }
});

Route:
Backbone.emulateHTTP = true;
Backbone.emulateJSON = true;

var NoteRouter = Backbone.Router.extend({
    routes : {
        "result" : "displayMessage"

    },
    displayMessage : function(){
        var notemodel = new NoteModel();
        var noteview  = new NoteView();
        notemodel.fetch({
            success: function(){
                  noteview.render();
                }
            })
        }
    });

var router = new NoteRouter();

Backbone.history.start();

PHP Api:
<?php

$datas = array(
    'result '=> 'PHP array data'
    );

$data = json_encode($datas);

echo $data;

?>

Html view :

it should return the php array data on the #result div but it's not, instead of returned [object Object] on the #result  div.

A: You try parse the Model itself into the template, but you actually want to parse the result of the fetch method of the Model.
Either you fetch the model object (returned from the server) from within the render function of the note_View object, or you instantiate the model in the router and pass it as 'options' parameter to the initializer function of the note_View.
You can do something like:
Router:
    var notemodel = new NoteModel();
    notemodel.fetch({
        success: function(returned_model){
            var noteview  = new NoteView({model : returned_model});
            }
        })
    }

View:
var NoteView = Backbone.View.extend({
    el : '#result',
    initialize:function(options){
        this.model = options.model;
        this.render();
    },
    render :function(){
         var template = _.template($("#result-view-template").html(),{result : this.model});
         this.$el.html(template);
         return this;
    }
});

A: You are passing whole object into the template. Don't put any object like this. If you want to access attributes, specify it like model.attribute.


text:
Q: Android Studio Drawing Application: Unfortunately App, has stopped My app continues to stop and I don't know why. It is a drawing app in a fragment which allows the user to draw.  I am a beginner programmer so any assistance would be great thank you!
Field Fragment:
package com.example.marlon.fieldapp;

import android.app.DialogFragment;
import android.content.Context;
import android.graphics.Color;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import java.util.UUID;
import android.provider.MediaStore;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Field_fragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Field_fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Field_fragment extends Fragment implements OnClickListener
{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private DrawingView drawView;
    private ImageButton currPaint, drawBtn;
    private float smallBrush, mediumBrush, largeBrush;

    private OnFragmentInteractionListener mListener;

    public Field_fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Field_fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Field_fragment newInstance(String param1, String param2)
    {
        Field_fragment fragment = new Field_fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        smallBrush = getResources().getInteger(R.integer.small_size);
        mediumBrush = getResources().getInteger(R.integer.medium_size);
        largeBrush = getResources().getInteger(R.integer.large_size);

        drawBtn = (ImageButton)getView().findViewById(R.id.draw_btn);
        drawBtn.setOnClickListener(this);

        drawView.setBrushSize(mediumBrush);

        super.onCreate(savedInstanceState);
        if (getArguments() != null)
        {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        drawView = (DrawingView) drawView.findViewById(R.id.drawing);
        LinearLayout paintLayout = (LinearLayout) getView().findViewById(R.id.paint_colours);
        currPaint = (ImageButton)paintLayout.getChildAt(0);
        currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));

        return getView();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */

    public void paintClicked(View view)
    {
        if(view!=currPaint)
        {
            ImageButton imgView = (ImageButton)view;
            String color = view.getTag().toString();
            drawView.setColor(color);
        }
    }

    @Override
    public void onClick(View view)
    { //Respond to clicks
        if(view.getId()==R.id.draw_btn)
        {
            final Dialog brushDialog;
            brushDialog = new Dialog(getActivity());
            brushDialog.setTitle("Brush size:");

            brushDialog.setContentView(R.layout.brush_chooser);

            ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
            smallBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    drawView.setBrushSize(smallBrush);
                    drawView.setLastBrushSize(smallBrush);
                    brushDialog.dismiss();
                }
            });

            ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
            mediumBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    drawView.setBrushSize(mediumBrush);
                    drawView.setLastBrushSize(mediumBrush);
                    brushDialog.dismiss();
                }
            });

            ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
            largeBtn.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {
                    drawView.setBrushSize(largeBrush);
                    drawView.setLastBrushSize(largeBrush);
                    brushDialog.dismiss();
                }
            });
            brushDialog.show();
        }
    }

    public interface OnFragmentInteractionListener
    {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

Here's the error that I'm getting:
02-06 11:39:00.681 28557-28557/com.example.marlon.fieldapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.marlon.fieldapp, PID: 28557
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.marlon.fieldapp/com.example.marlon.fieldapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:155)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
                                                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                at com.example.marlon.fieldapp.Field_fragment.onCreate(Field_fragment.java:80)
                                                                                at android.app.Fragment.performCreate(Fragment.java:2031)
                                                                                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:863)
                                                                                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                at android.app.BackStackRecord.run(BackStackRecord.java:834)
                                                                                at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1454)
                                                                                at android.app.Activity.performStart(Activity.java:6025)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:155)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

A: In onCreateView you should return an inflated view.
View Fragment.getView:

Get the root view for the fragment's layout (the one returned by
onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.

At your comment
// Inflate the layout for this fragment

Use the provided inflater to inflate your layout resource.
Something like
View fragmentView =  inflater.inflate(R.layout.frag_view, container, false);

return fragmentView.
You should probably also move
        drawBtn = (ImageButton)getView().findViewById(R.id.draw_btn);

to onCreateView, after inflation. Again, use the inflated view, not getView().

A: In the fragment you should not access ui element ion oncreate method. You have  to do this in the oncreateView method try this code.
package com.example.marlon.fieldapp;

        import android.app.DialogFragment;
        import android.content.Context;
        import android.graphics.Color;
        import android.media.Image;
        import android.net.Uri;
        import android.os.Bundle;
        import android.app.Fragment;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageButton;
        import android.widget.LinearLayout;
        import java.util.UUID;
        import android.provider.MediaStore;
        import android.app.AlertDialog;
        import android.app.Dialog;
        import android.content.DialogInterface;
        import android.view.View.OnClickListener;
        import android.widget.Toast;

        /**
         * A simple {@link Fragment} subclass.
         * Activities that contain this fragment must implement the
         * {@link Field_fragment.OnFragmentInteractionListener} interface
         * to handle interaction events.
         * Use the {@link Field_fragment#newInstance} factory method to
         * create an instance of this fragment.
         */
        public class Field_fragment extends Fragment implements OnClickListener
        {
            // TODO: Rename parameter arguments, choose names that match
            // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
            private static final String ARG_PARAM1 = "param1";
            private static final String ARG_PARAM2 = "param2";

            // TODO: Rename and change types of parameters
            private String mParam1;
            private String mParam2;

            private DrawingView drawView;
            private ImageButton currPaint, drawBtn;
            private float smallBrush, mediumBrush, largeBrush;

            private OnFragmentInteractionListener mListener;

            public Field_fragment() {
                // Required empty public constructor
            }

            /**
             * Use this factory method to create a new instance of
             * this fragment using the provided parameters.
             *
             * @param param1 Parameter 1.
             * @param param2 Parameter 2.
             * @return A new instance of fragment Field_fragment.
             */
            // TODO: Rename and change types and number of parameters
            public static Field_fragment newInstance(String param1, String param2)
            {
                Field_fragment fragment = new Field_fragment();
                Bundle args = new Bundle();
                args.putString(ARG_PARAM1, param1);
                args.putString(ARG_PARAM2, param2);
                fragment.setArguments(args);
                return fragment;
            }

            @Override
            public void onCreate(Bundle savedInstanceState)
            {

                super.onCreate(savedInstanceState);
                if (getArguments() != null)
                {
                    mParam1 = getArguments().getString(ARG_PARAM1);
                    mParam2 = getArguments().getString(ARG_PARAM2);
                }

            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState)
            {
                // Inflate the layout for this fragment
                drawView = (DrawingView) drawView.findViewById(R.id.drawing);
                LinearLayout paintLayout = (LinearLayout) getView().findViewById(R.id.paint_colours);
                currPaint = (ImageButton)paintLayout.getChildAt(0);
                currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));

                smallBrush = getResources().getInteger(R.integer.small_size);
                mediumBrush = getResources().getInteger(R.integer.medium_size);
                largeBrush = getResources().getInteger(R.integer.large_size);

                drawBtn = (ImageButton)getView().findViewById(R.id.draw_btn);
                drawBtn.setOnClickListener(this);

                drawView.setBrushSize(mediumBrush);

                return getView();
            }

            // TODO: Rename method, update argument and hook method into UI event
            public void onButtonPressed(Uri uri) {
                if (mListener != null) {
                    mListener.onFragmentInteraction(uri);
                }
            }

            @Override
            public void onAttach(Context context) {
                super.onAttach(context);
                if (context instanceof OnFragmentInteractionListener) {
                    mListener = (OnFragmentInteractionListener) context;
                } else {
                    throw new RuntimeException(context.toString()
                            + " must implement OnFragmentInteractionListener");
                }
            }

            @Override
            public void onDetach() {
                super.onDetach();
                mListener = null;
            }

            /**
             * This interface must be implemented by activities that contain this
             * fragment to allow an interaction in this fragment to be communicated
             * to the activity and potentially other fragments contained in that
             * activity.
             *

             * See the Android Training lesson Communicating with Other Fragments for more information.
             */

            public void paintClicked(View view)
            {
                if(view!=currPaint)
                {
                    ImageButton imgView = (ImageButton)view;
                    String color = view.getTag().toString();
                    drawView.setColor(color);
                }
            }

            @Override
            public void onClick(View view)
            { //Respond to clicks
                if(view.getId()==R.id.draw_btn)
                {
                    final Dialog brushDialog;
                    brushDialog = new Dialog(getActivity());
                    brushDialog.setTitle("Brush size:");

                    brushDialog.setContentView(R.layout.brush_chooser);

                    ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
                    smallBtn.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            drawView.setBrushSize(smallBrush);
                            drawView.setLastBrushSize(smallBrush);
                            brushDialog.dismiss();
                        }
                    });

                    ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
                    mediumBtn.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            drawView.setBrushSize(mediumBrush);
                            drawView.setLastBrushSize(mediumBrush);
                            brushDialog.dismiss();
                        }
                    });

                    ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
                    largeBtn.setOnClickListener(new OnClickListener(){
                        @Override
                        public void onClick(View v) {
                            drawView.setBrushSize(largeBrush);
                            drawView.setLastBrushSize(largeBrush);
                            brushDialog.dismiss();
                        }
                    });
                    brushDialog.show();
                }
            }

            public interface OnFragmentInteractionListener
            {
                // TODO: Update argument type and name
                void onFragmentInteraction(Uri uri);
            }
        }

The onCreate method run before onCreateView method so you should not access
drawView.setBrushSize(mediumBrush);

before you initialize it in the oncreateview
drawView = (DrawingView) drawView.findViewById(R.id.drawing);


text:
Q: Why Won't VBScript Paste? Word 2013 I am trying to create a VBScript that inserts some text from the clipboard into an existing (and loaded) Word document.  I have tried numerous approaches without success (including Selection.Paste) but Word (2013) will just not paste. Whilst trying to diagnose the problem, I have got down to this minimal script.
Set objWord = GetObject(, "Word.Application")
objWord.Application.Activate
Dim objShell
Set objShell = CreateObject("WScript.Shell")
objShell.SendKeys "Arggh 1"
objShell.SendKeys "^V"
objShell.SendKeys "Arggh 2"

If I place some text on clipboard (I have got down to basic unformatted text, I originally started with MathML but that is another story), the above script generates
Arggh 1Arggh 2

with the text left on the clipboard. If I then press Ctrl+V, the clipboard text gets pasted as expected.
I feel like I am missing something obvious.  Any help most welcome.

A: I had similar issues before (I need Ctrl-C), but this should work for you:
objShell.SendKeys "^{V}"

A: Avoid unsafe keystroke simulation when you have other programmatic facilities:
Set objWord = GetObject(, "Word.Application")
objWord.Selection.TypeText "Arggh 1"
objWord.Selection.Paste
objWord.Selection.TypeText "Arggh 2"

Also note objWord.Application is same as just objWord.

A: Ok.  This is partially solved.

*

*The initial problem - objWord.Selection.Paste not working - ended up being a strange timing interaction between the clipboard and the software creating the VBS script.  Basically, the script is trying to do the pasting before the clipboard knows about the data.  Once I took away the timing issue, objWord.Selection.Paste is working as expected.  We have not solved this problem yet but at least we now know what is going on and can work on it.  From a purely pragmatic point of view, the issue raised above is no longer important.

*SendKeys pasting is still not working and I don't know why.  I won't be spending any more time on it as the problem I have has now morphed.
This is one of those rare times that trying to make things simpler for diagnostic purposes has actually made things more difficult.


text:
Q: Creating response to answering quiz questions in a table I am creating an app for medical students, and one view is a quiz mode that randomly generates quiz questions with a table view of the answer options. In the current stage, the user selects an answer from the table view, and a text field below the table view tells them whether they are right or not.
What I would like to do is, when the user clicks an answer, if the answer is correct, the selected answer in the table is highlighted green. If the answer is wrong, the selected answer would turn red, and the correct answer in the table would turn red. Anyone know if it's possible to have different selection background colors in the same table (and also whether the logic described is possible)?

A: This should do the trick, beware it is not tested:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row != self.correctAnswerRow)
    {
        UITableViewCell *wrongCell = [tableView cellForRowAtIndexPath:indexPath];
        [wrongCell setBackgroundColor:[UIColor redColor]];
    }

    UITableViewCell *correctCell = [tableView cellForRowAtIndexPath:
[NSIndexPath indexPathForRow:self.correctAnswerRow inSection:indexPath.section]];
    [correctCell setBackgroundColor:[UIColor greenColor]];
}


text:
Q: Is it possible for Rollup to preserve file and folder structure? I'm using ES6 imports and transpiling them with Rollup.
The output is a single bundle file.
Can Rollup be configured to generate a file-for-file transpile result?
Here is the current configuration I'm using which obviously spits out one file.
 gulp.task('rollup', function() {
    const rollup = require('rollup');
    const nodeResolve = require('rollup-plugin-node-resolve');

    const JS_INDEX_FILE = 'src/index.js';

    return rollup.rollup({
        input: JS_INDEX_FILE,
        plugins: [
            nodeResolve({
                browser: true
            })
        ]
    }).then(bundle => {
            bundle.write({
                sourcemap: true,
                format: 'cjs',
                strict: true,
                file: 'bundle.js'
            });
        });
});

Basically, I'd like individual files with require() instead of import.

A: If you want to use rollup to convert ES6 to CommonJS and preserve the file and directory structure, your rollup config might look something like this:
import { nodeResolve } from "@rollup/plugin-node-resolve";

export default [
  {
    input: ["src/index.js"],
    plugins: [nodeResolve()],
    output: [
      {
        dir: "dist",
        format: "cjs",
        exports: "named",
        preserveModules: true, // Keep directory structure and files
      }
    ]
  }
]

See Integrating Rollup with Other Tools to determine if you need the @rollup/plugin-node-resolve plugin and exactly what gets "preserved" from the external packages.

A: Rollup is a module bundler. What you want is a compiler, such as Babel.