text:
Q: Error with phv font family I was just testing the template that the faculty has left me to do the work when I come across a compilation error. Debugging the code, I have come to isolate the problem, which is given by something related to the phv source but I can't identify why. According to miktex, all the necessary dependencies are installed and up-to-date so I find it quite strange to know what is wrong. I leave you the part that I have isolated and its corresponding log
\documentclass[spanish,12pt,a4paper]{book}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[spanish,activeacute]{babel}

\begin{document}

\fontfamily{phv}\selectfont{\large \textbf{Nombre}}

\end{document}

Log
LaTeX Font Info:    Trying to load font information for T1+phv on input line 9.
 ("/Users/jose/Library/Application Support/MiKTeX/texmfs/install/tex/latex/psnfss/t1phv.fd"
File: t1phv.fd 2020/03/25 scalable font definitions for T1/phv.
) [1{/Users/jose/Library/Application Support/MiKTeX/texmfs/data/pdftex/config/pdftex.map}

Thank you very much!!


text:
Q: Triangles points' distance becomes larger, but all points have the same speed I am trying to show a bunch of triangles with random colors on the center of the screen. Those triangles, with various continuous and steady velocities should go out of sight (beyond the screen limits) depending on their speed.
I can't work out what doesn't work right, actually.
Triangle initialization:
In every triangle I set the 1st point to be somewhere in [-0.1, 0.1]. So I get a (firstX, firstY) for the first point. The next two points are (firstX-0.02f, firstY-0.02f) and ((firstX+0.02f, firstY+0.02f)) correspondingly. So, all the triangles should be equilateral, right?
Next, for each triangle, I set a speed for X and a speed for Y axis, both being in [-1/2000, 1/2000]. This speed is steady and will never change for each triangle.
Triangle updating:
The triangles update each frame, because they are moving with some speed, as stated. I know that I will have to multiply it by deltaTime, but this is not important for now.
So, in the update function, I basically find each point in every triangle and I update their X and Y based on the speed of that triangle.
Every of the 3 points in every triangle, have the same speed (speed varies from triangle to triangle, though).
I cannot understand why doesn't every triangle simply move to some edge of the screen and then disappear.
What I see is triangles, starting from close to the center of the screen (as expected, as firstX and firstY are values close to 0) and becoming bigger and bigger, while it seems that their speed decreases.
The code:
import java.util.Random;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;

public class MainMenu implements Screen {

    private MyGame game;
    private Mesh trianglesMesh;

    private int screenWidth, screenHeight;

    public static final int MAX_TRIANGLES_NUM = 2000;
    //2 for position, 4 for color
    public static final int COMPONENTS_NUM_PER_TRIANGLE = 6;

    //3 vertices per triangle
    private float[] vertices = new float[3 * COMPONENTS_NUM_PER_TRIANGLE * MAX_TRIANGLES_NUM];
    //horizontal and vertical speed for each triangle
    private float[] speeds = new float[2*MAX_TRIANGLES_NUM];

    public MainMenu(MyGame game) {
        this.game=game;

        screenWidth=Gdx.graphics.getWidth();
        screenHeight=Gdx.graphics.getHeight();

        //2 components for position, 4 components for color
        trianglesMesh = new Mesh(true, 3*MAX_TRIANGLES_NUM, 0, new VertexAttribute(Usage.Position, 2, "a_position"),
                                                           new VertexAttribute(Usage.Color, 4, "a_color"));
        initTriangles();
    }

    private void fillRandomColor(int curTriangle, int init, int max, Random random){
        for(int i=init;i<max;i++){
            vertices[curTriangle*COMPONENTS_NUM_PER_TRIANGLE+i]=random.nextFloat();
        }
    }
    private void initTriangles(){
        /*
         * How it works: Each triangle has an initial position that is inside the
         * visible area. Each one is given a speed to a random direction. Once a
         * triangle becomes invisible, there is a possibility that another one will
         * come into place. This possibility is true as long as the current number of
         * available triangles is less than MAX_TRIANGLES_NUM
         * */
        Random random = new Random();
        for(int currentTriangle=0;currentTriangle<MAX_TRIANGLES_NUM;currentTriangle++){
            //1st triangle point
            //X and Y init is [-0.1, 0.1]
            float firstX=(2*random.nextFloat()-1)/10, firstY=(2*random.nextFloat()-1)/10;

            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE]=firstX;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+1]=firstY;
            fillRandomColor(currentTriangle, 2, 6, random);
            //2nd triangle point
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+6]=firstX-0.02f;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+7]=firstY-0.02f;
            fillRandomColor(currentTriangle, 8, 12, random);
            //3rd triangle point
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+12]=firstX+0.02f;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+13]=firstY+0.02f;
            fillRandomColor(currentTriangle, 14, 18, random);
            //setting up the continuous speed for the triangle
            speeds[currentTriangle*2]=(2*random.nextFloat()-1)/2000;
            speeds[currentTriangle*2+1]=(2*random.nextFloat()-1)/2000;
        }
    }

    private void updateTriangles(){
        /*
         * Updates the position of the triangles, discards the ones not visible
         * and possibly adds new ones.
         * */

        for(int currentTriangle=0;currentTriangle<MAX_TRIANGLES_NUM;currentTriangle++){
            //updating the position of every point in triangle

            //get the speed
            float speedX=speeds[currentTriangle*2];
            float speedY=speeds[currentTriangle*2+1];

            //update the Xs
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE]+=speedX;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+6]+=speedX;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+12]+=speedX;

            //update the Ys
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+1]+=speedY;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+7]+=speedY;
            vertices[currentTriangle*COMPONENTS_NUM_PER_TRIANGLE+13]+=speedY;
        }
        trianglesMesh.setVertices(vertices);
    }

    @Override
    public void render(float delta) {
        // TODO Auto-generated method stub
        updateTriangles();

        Gdx.gl.glClear(GL20.GL_COLOR_CLEAR_VALUE);
        trianglesMesh.render(GL20.GL_TRIANGLES, 0, vertices.length);
        /*
         * TODO
         * Here must check when to go off the main menu screen.
         *
         * if(condition){
         *     game.setScreen(someOtherAwesomeScene);
         * }
         *
         * */
    }

    @Override
    public void resize(int width, int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void show() {
        // TODO Auto-generated method stub

    }

    @Override
    public void hide() {
        // TODO Auto-generated method stub

    }

    @Override
    public void pause() {
        // TODO Auto-generated method stub

    }

    @Override
    public void resume() {
        // TODO Auto-generated method stub

    }

    @Override
    public void dispose() {
        // TODO Auto-generated method stub

    }

}

Preview of what I see: http://i.imgur.com/fF7djBt.gif
And I repeat that I would just expect the triangles to stay as small as they are moving with some velocity to the edges of the screen. I do not get

*

*How do they become larger?

*How do they stop being equilateral?

*Why does the speed seems to decrease?

A: The problem was that COMPONENTS_NUM_PER_TRIANGLE should be initialized to be 18 and then
private float[] vertices = new float[COMPONENTS_NUM_PER_TRIANGLE * MAX_TRIANGLES_NUM];

redpajama_set_name: RedPajamaStackExchange


text:
Q: @MapKey breaks with hibernate version 4.3.9 onwards. It works fine with 4.3.8 We have the below entity mapping in our project. It is working fine until hibernate version 4.3.8 but when i upgrade to 4.3.11, the test cases started failing with the below error.
Entity mapping:
@Entity
@Table(name = "EMPLOYEE")
public class Employee
{
  @Id
  @Column(name = "EMPLOYEE_ID")
  private long id;

  @OneToMany(mappedBy="owner", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @MapKey(name = "phoneType")
  private Map<PhoneType, Phone> phones = new HashMap<PhoneType, Phone>()

  ...
}

@Entity
@Table(name = "PHONE")
public class Phone
{
  @Id
  @ManyToOne
  @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMPLOYEE_ID")
  @NotNull
  private Employee owner;

  @Id
  @ManyToOne
  @JoinColumn(name = "PHONE_TYPE_ID", nullable = false)
  @NotNull
  @Fetch(FetchMode.SELECT)
  private PhoneType phoneType;

  @NotNull
  @Column(name = "PHONE_NUMBER")
  private String phoneNumber;

  ...
}

@Entity
@Table(name = "PHONE_TYPE")
public class PhoneType
{
  @Id
  @Column(name = "PHONE_TYPE_ID")
  private long id;

  @NotNull
  @Column(name = "PHONE_TYPE")
  private String phoneType;

  ...
}

Caused by: java.lang.IllegalStateException: Could not locate collection index join within collection join [ : OneToManyPersister(com.xyz.Employee.phones)]
    at org.hibernate.loader.plan.exec.internal.LoadQueryJoinAndFetchProcessor.renderCollectionJoin(LoadQueryJoinAndFetchProcessor.java:353)
    at org.hibernate.loader.plan.exec.internal.LoadQueryJoinAndFetchProcessor.renderJoin(LoadQueryJoinAndFetchProcessor.java:163)
    at org.hibernate.loader.plan.exec.internal.LoadQueryJoinAndFetchProcessor.processQuerySpaceJoin(LoadQueryJoinAndFetchProcessor.java:138)
    at org.hibernate.loader.plan.exec.internal.LoadQueryJoinAndFetchProcessor.processQuerySpaceJoins(LoadQueryJoinAndFetchProcessor.java:133)
    at org.hibernate.loader.plan.exec.internal.LoadQueryJoinAndFetchProcessor.processQuerySpaceJoins(LoadQueryJoinAndFetchProcessor.java:114)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadQueryDetails.generate(AbstractLoadQueryDetails.java:171)
    at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails.(EntityLoadQueryDetails.java:107)
    at org.hibernate.loader.plan.exec.internal.BatchingLoadQueryDetailsFactory.makeEntityLoadQueryDetails(BatchingLoadQueryDetailsFactory.java:73)
    at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.(AbstractLoadPlanBasedEntityLoader.java:100)
    at org.hibernate.loader.entity.plan.EntityLoader.(EntityLoader.java:134)
    at org.hibernate.loader.entity.plan.EntityLoader.(EntityLoader.java:55)
    at org.hibernate.loader.entity.plan.EntityLoader$Builder.byUniqueKey(EntityLoader.java:98)
    at org.hibernate.loader.entity.plan.EntityLoader$Builder.byPrimaryKey(EntityLoader.java:94)
    at org.hibernate.loader.entity.plan.AbstractBatchingEntityLoaderBuilder.buildNonBatchingLoader(AbstractBatchingEntityLoaderBuilder.java:47)
    at org.hibernate.loader.entity.BatchingEntityLoaderBuilder.buildLoader(BatchingEntityLoaderBuilder.java:76)
    at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:2506)
    at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:2528)
    at org.hibernate.persister.entity.AbstractEntityPersister.createLoaders(AbstractEntityPersister.java:4035)
    at org.hibernate.persister.entity.AbstractEntityPersister.postInstantiate(AbstractEntityPersister.java:4017)
    at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:481)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564)
    ... 44 more
SKIPPED CONFIGURATION: @BeforeMethod springTestContextBeforeTestMethod
SKIPPED: testPhone

A: You should be using @MapKeyJoinColumn if the key is an entity.


text:
Q: JsonMediaTypeFormatter mock I have no idea if anyone can help me but I'll ask all the same.
I am trying to Mock/Stub JsonMediaTypeFormatter in my unit test and I seem to be having trouble setting up the stub properties. I would like to be able to set the mock with this setting
SerializerSettings = { TypeNameHandling = TypeNameHandling.All };

Like such
_mockFormatter.SetUp(f => f.SerializerSettings = { TypeNameHandling = TypeNameHandling.All });

However, this is not a possibility in Moq. Does anyone know how this can be achieved.

A: Try this. I'm not at a .net compiler so I can't test/tweak it but if this doesn't work, it should get you headed in the right direction.
_mockFormatter.SetUp(
    f => f.SerializerSettings = () =>
    { TypeNameHandling = TypeNameHandling.All }
);

You have to account for you are passing a function into the setup, even though the function is just setting up an anonymous object with one property. The () => lambda should take care of that for you.


text:
Q: HTML YouTube to Show All Videos? Anyone know how to add the full upload feed from YouTube to a website using html coding??? I've been able to get single videos, but haven't found anything regarding all videos.

A: if you want to use the Youtube Data API you can retrieve all videos on a specific channel.
If you just wanted to embed a full upload feed from a channel, as this question states you can use the channel embed code, for example:
<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>


text:
Q: How to export data in a specified time to csv with cassandra? I can use this command to export all the data to csv:
COPY data  TO '/usr/local/cassandra/my_data.csv';

But now I want to export the data of the specified time to csv, such as this condition:
select * from data where upload_time >='2020-10-16 00:00:00.000+00' and upload_time <'2020-10-17 00:00:00.000+0000' allow filtering ;

What should I do with command?

A: You can use DSBulk utility with custom query, but you need to be careful and put the optimized condition so it will perform full scan, but using the token ranges (see this blog post for details).
Something like (replace pk with the name of the actual partition key column, and unsplit query string - I split it just for readability):
dsbulk unload -url data.csv \
-query "SELECT * FROM ks.table WHERE token(pk) > :start AND token(pk) <= :end
  AND upload_time >='2020-01-01 00:00:00.000+00'
  AND upload_time <'2021-01-01 00:00:00.000+0000' allow filtering"

Another way is to use Spark with Spark Cassandra Connector (even in the local master mode) - it will do the same under the hood, something like this (example for spark-shell in Scala, could be done similarly via pyspark):
import org.apache.spark.sql.cassandra._
val data = spark.read.cassandraFormat("table", "keyspace").load()
val filtered = data.filter("upload_time >= cast('2020-01-01 00:00:00.000+00' as timestamp) AND upload_time <= cast('2021-01-01 00:00:00.000+0000' as timestamp)")
filtered.write.format("csv").save("data.csv")


text:
Q: Using Application.Workbooks.Open to open .txt file, but it cuts away long numbers I have this script
Sub IMport()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("B1:K200").Copy
        ThisWorkbook.Worksheets("Hent Data").Range("B2").PasteSpecial xlPasteValues
        OpenBook.Sheets(1).Range("A1:A200").Copy
        ThisWorkbook.Worksheets("Hent Data").Range("A2").PasteSpecial Format:="Text"
    End If

Application.ScreenUpdating = True

End Sub

I'm using this script to open a txt file and copying it to an excel sheet.
The problem is the numbers in column A are 23 numbers long, so when it is opened in excel a lot of the numbers have been removed.
How can I prevent Excel cutting off a lot of the numbers?
Update:
i made a mistake and posted the VBA script where i tried to fix the problem.
the real script is:
Sub IMport()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A1:K200").Copy
        ThisWorkbook.Worksheets("Hent Data").Range("A2").PasteSpecial xlPasteValues
    End If

Application.ScreenUpdating = True

End Sub

A: The problem is that Excel while opening text file interprete the string of digits separated with delimiter as a  number, integer or float.
To avoid this you must use formatting options to treat the input as text, not as numbers.
Example.
Suppose that input text contains no more than 2 numeric fields separated with space(s)
The method
Workbooks.OpenText FileName:= "sample number list.txt", Space=True, FieldInfo=Array(Array(1,2),Array(2,2))
will perform input to first two columns of the new worksheet with no text to number conversion
FieldInfo parameter contains array of formatting options for each field of input file

A: I've struggled with this a lot because I made the dumb mistake of generating  barcode numbers that may have a leading zero. Excel cuts off the leading zero on numbers and kept ruining those barcode numbers.
The solution I found was to first take the unchanged values into an array, and then add an equals sign and quotes around the value so when it is pasted into excel, it is a literal string and cannot be changed by their number formatting.
In my experience simply setting the sheets number formatting to "@" was not enough, excel would still try to remove leading zeroes on numbers and still try to display long numbers in scientific notation. But entering a number as "=""" & number & """" will force excel to not do that.
Here's the function I wrote to do this to a 2D array:
Private Function ForceString(ByRef InputArr As Variant) As Variant
    Dim OutputArr() As Variant
    OutputArr = InputArr
    Dim i As Long, j As Long
    For i = LBound(OutputArr) To UBound(OutputArr)
        For j = LBound(OutputArr, 2) To UBound(OutputArr, 2)
            OutputArr(i, j) = "=""" & OutputArr(i, j) & """"
        Next j
    Next i
    ForceString = OutputArr
End Function


text:
Q: short for python dictionary I tried a few searches but I didn't really know how to ask. I understand short form for loops but this portion within a dictionary is confusing me.
resistances = {k: v if random.random() > self.mutProb else
    not v for k, v in self.resistances.items()}

Is it setting k as the key initially and then cycling through it later on? I'm having difficulty imagining what the 'long hand' would be.

A: You have a dictionary comprehension, and for each iteration of the for loop, two expressions are executed. One for the key, and one for the value.
So in the expression:
{k: v if random.random() > self.mutProb else not v
 for k, v in self.resistances.items()}

both k and v if random.random() > self.mutProb else not v are expressions, and the first produces the key, the second the value of each key-value pair for the resulting dictionary.
If you were to use a for loop, the above would be implemented as:
resistances = {}
for k, v in self.resistances.items():
    key = k
    value = v if random.random() > self.mutProb else not v
    resistances[key] = value

In your example, the key is simply set to the value of the variable k, but you can use more complex expressions too.
Dictionary comprehensions are a specialisation of Dictionary Displays; the other form produces a dictionary without looping, from a static list of key-value pairs, and is perhaps more familiar to you:
d = {key1: value1, key2: value2}

but the documentation states:

A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual "for" and "if" clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.


text:
Q: dropdown list selected value does not refresh when using jQuery mobile empty function I have the following cascading select dropdown list in my page.
Country -> City

On my desktop, if I previously selected "USA" and "New York" and I then changed the country to France. The city dropdown would display "Choose a city" and this is what I want.
These are the code I used to populate the city list and set the default value.
$("#country").on("change", function(event) {
    getCities($("#country").val(), $("#city").val());
});

function getCities(country) {
    $.ajax({
        url: window.location.pathname.substring(0, window.location.pathname.indexOf("index.cfm")) + "index.php/search/getCities?format=json"
        , dataType: "json"
        , data: {country:country}
        , success: function(data, status) {
            populateCities(data);
        }
    });
}

function populateCities(data) {
    if (data.length > 0) {
        $("#city").empty();

        $("#city").prepend($('<option></option>').attr("value", "").attr("selected", "selected").text("- Choose a city -"));
        $.each(data, function () {
            $("#city").append($('<option></option>').attr("value", this.CITY).text(this.CITY));
        });
    }
}

But on a mobile, the city dropdown still says "New York".
Does anyone have any ideas on how to fix this?
Thanks a lot
edit:
also tried these changes (as suggested below). still not working as intended
function populateAgencies(data) {
    if (data.length > 0) {
        $("#agency").empty();

        $("#agency").prepend('<option value="" selected>- Choose a city -</option>');
        $.each(data, function () {
            $("#agency").append('<option value="'+this.CITY+'">'+this.CITY+'</option>');
        });("#city").enhanceWithin();
    }
}


text:
Q: SQL query image column to file I want to run a query over a table in SQL Server to save out the data as files.
The table has one column with a filename in it and one column that is an image column with binary file contents data in it.
I'm sure I saw some syntax that would let me do this, but I cannot for the life of me find it anymore.
Is this possible?

A: You can do this with the bcp.exe from the command line which you could call through xp_cmdshell.
bcp "select MyBlobField from myTable WHERE a=b " queryout "c:\MyImage.jpg" -T -n

You can probably do it through OLE automation natively in SQL Server; but its not something I have tried.
An easy alternative is (if you have 2005/8) a CLR into the DB to do the job. THere are lots of code examples on the web how to do that.


text:
Q: How to prevent output from running twice when inputs are inter-dependent? I'm developping an R Shiny-based application.
I want to keep my input consistent with available data, thus I update the selected values in selectInput.
When I change selected value in input 1, then the value of input 2 is updated, then the data is updated (just once). OK
BUT if I change selected value in input 2, then the data is updated, then the value of input 1 is updated, then the data is updated AGAIN.
Check out the "check latest_value" that is printed twice.
Initially I used renderUI rather than updateSelectInput, but at initialisation, the data is computed twice.
library(shiny)
library(DT)
library(dplyr)
my_data=data.frame(CO2)
# Running a Shiny app object
app <- shinyApp(
  ui = bootstrapPage(
    selectInput('type','Choix du type',choices = unique(my_data$Type)),
    uiOutput('plant_ui'),
    DTOutput('plot')
  ),
  server = function(input, output) {

    data=reactive({
      # req(input$type)
      my_data_temp=my_data
      if(length(input$type)>0){
        my_data_temp=my_data_temp%>%filter(Type%in%input$type)
      }
      if(length(input$plant)>0){
        my_data_temp=my_data_temp%>%filter(Plant%in%input$plant)
      }

      my_data_temp
    })

    latest_plant_value=reactive({
      if(is.null(input$plant))data()$Plant[1]
      else input$plant
    })

    output$plant_ui=renderUI({
      sub_data=data()
      selectInput(inputId = 'plant',"filtre par plant",choices = unique(sub_data$Plant),
                  selected=latest_plant_value())
    })

    output$plot <- renderDT({
      print("check latest_value")
      datatable(data()) })
  }
)
runApp(app)

That's why I decided to use updateSelectInput based on this Alternate control of a sliderInput between a derived value and user selected value but the sequential structure of the code makes the data to be computed twice when I change input 2 value.
library(shiny)
library(DT)
library(dplyr)
my_data=data.frame(CO2)
# Running a Shiny app object
app <- shinyApp(
  ui = bootstrapPage(
    selectInput('type','Choix du type',choices = unique(my_data$Type),selected=my_data$Type[1]),
    selectInput('plant','Choix du type',choices = unique(my_data$Plant),selected=my_data$Plant[1]),
    DTOutput('plot')
  ),
  server = function(input, output,session) {

    data=reactive({
      # req(input$type)
      my_data_temp=my_data
      if(length(input$type)>0){
        my_data_temp=my_data_temp%>%filter(Type%in%input$type)
      }
      if(length(input$plant)>0){
        my_data_temp=my_data_temp%>%filter(Plant%in%input$plant)
      }

      my_data_temp
    })

    observeEvent(input$type,{
      print("update type changed")
      updateSelectInput(session, "plant",
                        selected =  unique(my_data%>%filter(Type%in%input$type)%>%.$Plant)[1])
    })
    observeEvent(input$plant,{
      print("update plant changed")
      updateSelectInput(session, "type",
                        selected =  unique(my_data%>%filter(Plant%in%input$plant)%>%.$Type)[1])
    })

   output$plot <- renderDT({
     print("check latest_value")

     datatable(data()) })
  }
)
runApp(app)

Fixes like this one don't work in that case because I'm not trying to achieve the same thing three interdependent selectInput in R/Shiny application
I want the default selected value of each input to be consistent so that the filter returns at least 1 value. This of any input I change.

A: One way to get around this is to create a reactiveVal that tells the app that an updating operation is in progress, and require data to wait until that flag returns to False before running.
I've added 5 lines to your second shiny app:
To server():
# Create update in progress flag
updating_type_inprogress <- reactiveVal(FALSE)

To observeEvent(input$type ...:
# When type is changed, set flag to TRUE
updating_type_inprogress(TRUE)

To observeEvent(input$plant ...:
# Once this function has run, the updating operation is done
updating_type_inprogress(FALSE)

To data():
# Stops updating data() if the in-progress flag is TRUE
req(!updating_type_inprogress())

To renderDT():
# Stops updating renderDT() if the in-progress flag is TRUE
#  this is probably optional unless there's resource-intensive code
#    that doesn't depend on changes in data()
req(!updating_type_inprogress())

Here's the whole code:
library(shiny)
library(DT)
library(dplyr)
my_data=data.frame(CO2)
# Running a Shiny app object
app <- shinyApp(
    ui = bootstrapPage(
        selectInput('type','Choix du type',choices = unique(my_data$Type),selected=my_data$Type[1]),
        selectInput('plant','Choix du type',choices = unique(my_data$Plant),selected=my_data$Plant[1]),
        DTOutput('plot')
    ),
    server = function(input, output,session) {

        data=reactive({
            req(!updating_type_inprogress())
            print(input$type)
            print(input$plant)
            my_data_temp=my_data
            if(length(input$type)>0){
                my_data_temp=my_data_temp%>%filter(Type%in%input$type)
            }
            if(length(input$plant)>0){
                my_data_temp=my_data_temp%>%filter(Plant%in%input$plant)
            }

            my_data_temp
        })

        observeEvent(input$type,{
            updating_type_inprogress(TRUE)
            updateSelectInput(session, "plant",
                              selected =  unique(my_data%>%filter(Type%in%input$type)%>%.$Plant)[1])
        })
        observeEvent(input$plant,{
            updating_type_inprogress(FALSE)
            updateSelectInput(session, "type",
                              selected =  unique(my_data%>%filter(Plant%in%input$plant)%>%.$Type)[1])
        })

        updating_type_inprogress <- reactiveVal(FALSE)

        output$plot <- renderDT({
            req(!updating_type_inprogress())
            print("check latest_value")
            datatable(data()) })
    }
)
runApp(app)

As you can see, when you change input$type, the data() and renderDT() functions only run once with the correctly updated values:
[1] "check latest_value"
[1] "Quebec"
[1] "Qn1"
[1] "check latest_value"
[1] "Mississippi"
[1] "Mn1"
[1] "check latest_value"
[1] "Quebec"
[1] "Qn1"

A: Interesting problem and not easy to solve! Interestingly, what you are asking for is not what you need. Observation:

*

*If the user selects Qn2 while Input1 is "Mississippi", you first set Input1 on Quebec and then hard set Input2 on Qn1, changing the choise of the user. This is bad.

*Datatable is always updated once any of the two inputs changes, hence the many re-calculations of the table.

The solution therefore is twofold:

*

*Don't overwrite the user's choice of e.g. Qc2 to Qc1. I used an if condition for that.

*Install a watchguard to only update
the datatable when its contents actually changed. I do this with a reactiveVal() that I only update when the choice of the two inputs was valid (i.e. when the result set is greater than 0).

See the result below. Watch the console output to observe the decisions.
library(shiny)
library(DT)
library(dplyr)
my_data=data.frame(CO2)

shinyApp(
  ui = bootstrapPage(
    selectInput('type','Choix du type',choices = unique(my_data$Type),selected=my_data$Type[1]),
    selectInput('plant','Choix du plant',choices = unique(my_data$Plant),selected=my_data$Plant[1]),
    DTOutput('plot')
  ),
  server = function(input, output,session) {

    latest_data <- reactiveVal(my_data)
    observe({
      result <- my_data %>% filter(Type %in% input$type, Plant %in% input$plant)

      if(nrow(result) > 0){
        latest_data(result)
      }else{
        cat(format(Sys.time(), "%H:%M:%S"), "Didn't update the dataframe because the choice was not valid.\n")
      }
    })

    observeEvent(input$type,{
      if(! input$plant %in% my_data$Plant[my_data$Type == input$type]){
        old <- input$plant
        new <- my_data %>% filter(Type %in% input$type) %>% slice(1) %>% pull(Plant) %>% as.character()
        updateSelectInput(session, "plant", selected = new)
        cat(format(Sys.time(), "%H:%M:%S"), "Updated input$plant from", old, "to", new, "so that it represents a valid choice for", input$type, "\n")
      }else{
        cat(format(Sys.time(), "%H:%M:%S"), "Didn't update input$plant", input$plant, "because it is a valid choice for", input$type, "already\n")
      }
    })
    observeEvent(input$plant,{
        updateSelectInput(session, "type",
                          selected = my_data %>% filter(Plant %in% input$plant) %>% slice(1) %>% pull(Type))
    })

    output$plot <- renderDT({
      cat(format(Sys.time(), "%H:%M:%S"), "updating datatable to only include", isolate(input$plant), "and", isolate(input$type), "\n\n")
      latest_data()
      datatable(latest_data())
    })
  }
)


text:
Q: Why doesn't the decoder of MediaCodec output a unified YUV format(like YUV420P)? "The MediaCodec decoders may produce data in ByteBuffers using one of the above formats or in a proprietary format. For example, devices based on Qualcomm SoCs commonly use OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m (#2141391876 / 0x7FA30C04)."
This make it difficult even not possible to deal with the output buffer.Why not use a unified YUV format?And why there are so many YUV color formats?
@fadden,I find it possible to decode to Surface and get the RGB buffer(like http://bigflake.com/mediacodec/ExtractMpegFramesTest.java.txt), Can I transfer the RGB buffer to YUV format and then encode it?
And,fadden,I tried to use API 18+ and came across some problems.I refered to the ContinuousCaptureActivity and ExtractMpegFramesTest code.
In ContinuousCaptureActivity:
    mEglCore = new EglCore(null, EglCore.FLAG_RECORDABLE);
    mDisplaySurface = new WindowSurface(mEglCore, holder.getSurface(), false);
    mDisplaySurface.makeCurrent();

    mFullFrameBlit = new FullFrameRect(
            new Texture2dProgram(Texture2dProgram.ProgramType.TEXTURE_EXT));
    mTextureId = mFullFrameBlit.createTextureObject();
    mCameraTexture = new SurfaceTexture(mTextureId);
    mCameraTexture.setOnFrameAvailableListener(this);
    mCamera.setPreviewTexture(mCameraTexture);

The FullFrameRect creates a SurfaceTexture and it is set to the camera preview texture.
But in ExtractMpegFramesTest, a CodecOutputSurface is used and it also creates a texture.How can I use the CodecOutputSurface and FullFrameRect together?(one supplies surface to receive the decoder output and one rescale and render to the encoder input surface.)

A: Let me try to answer the 'why' part. With your kind permission, I will change the order of the questions.

And why there are so many YUV color formats?

YUV is only one of many color spaces used to represent visual information. For many technical and historical reasons, this color space is most popular for photographical data (including video). Wikipedia claims that YUV was invented when television began to transform from BW to color. Back then, these were analogue signals. Later, different engineers in different corporations and countries began to independently invent the ways to store this YUV data in digital format. No wonder that they did not come up with one format.
Furthermore, the YUV formats differ in the volume of chroma information they store. It's quite natural that YUV 420, 422, and 444 all have right to exist, giving different compromises between precision and size.
Finally, some of the differences in YUV formats are related to physical layout of the pixels, and are optimized for different optical sensors.
Which brings us to the first part of your question:

Why not use a unified YUV format?

Transfer of photo information from the optical sensor to computer (smartphone) memory is a technical challenge. When we speak about a many-megapixel live high-speed video stream, the bandwidth limitations and electronic noise become important. Some YUV formats, like uyvy or OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m, are optimized to reduce electron congestion on the way from optical sensor to byte buffer.
These formats may have significant advantage if used on the proper integrated circuit, or no advantage at all if used on a different type of hardware.
Same is true for hardware codecs. Different implementations of h264 decoder may take advantage of cache locality for different interlaced YUV formats.


text:
Q: Java Business Intelligence framework with ad-hoc web reporting? I need a reporting framework that supports web views with ad-hoc reporting, as well as styled, canned PDF reports.
My users will be non-power users, so I'll need to present something usable for the ad-hoc reporting.
What's the best current solution in the java world?

A: There's a jasper reports plugin for grails
Not used it yet myself tho...

A: Candidates are Eclipse BIRT, JasperReports (has Grails plugin), Google Chart (has a Grails plugin I think), Pentaho and possibly Flying Saucer (Grails plugin named "rendering") if you just want the PDF generation and do the reporting yourself with eg JFreeChart.
However, you probably won't find much of ad-hoc reporting in those tools and I believe it to be hard to make a generic ad-hoc tool. It's hard to give a final recommendation since they all have their strength and weaknesses.

A: check out pentaho. it's open-source, free to use, but has paid support model

A: Depending on the number of users you have and the amount of money you want to spend, Inetsoft's product line might work for you.  It's a java web app that allows you to create simple logical data models which users can then use to create adhoc reports.
Our organization has had success with it on a small scale, but have encountered a lot of issues trying to scale it for 2000+ users.


text:
Q: Image crop picker save images to gallery on click from camera in react native Hi I am using react native image crop picker and using this code
ImagePicker.openCamera({
      width: 300,
      height: 400,
      compressImageQuality: Platform.OS === 'android' ? 0.7 : 0.8,
      cropping: false,
      // includeBase64: true,
    })

But the problem is that when i am using this it saves images in the temp folder. So I want to know how can i save images to phone gallery on Click from camera.r


text:
Q: How do you install m2e-android-plugin in Eclipse? I am trying to get setup to use Maven and pom.xml files in Eclipse for my Android projects. I have Eclipse Indigo setup (m2e included), Android SDK installed, ADT installed. I am struggling to understand what it means to "Install the m2e-android-plugin" (I am always taken to this page which provides instructions on installing it, but which I cannot follow) Specifically, when I go through the instruction on that page, after I complete all the steps in part 2, my structure does not have "Maven Dependencies" and my pom.xml file shows the following error:
Project build error: Unresolveable build extension: Plugin
com.jayway.maven.plugins.android.generation2:android-maven-plugin:3.1.1 or one of its dependencies could
not be resolved: The following artifacts could not be resolved:
com.jayway.maven.plugins.android.generation2:android-maven-plugin:jar:3.1.1,
com.android.ddmlib:ddmlib:jar:r16, org.sonatype.sisu:sisu-inject-bean:jar:2.1.1,
org.sonatype.sisu:sisu-guice:jar:no_aop:2.9.4, org.codehaus.plexus:plexus- archiver:jar:2.0.1, junit:junit:jar:3.8.1,
org.codehaus.plexus:plexus-io:jar:2.0.1, org.codehaus.plexus:plexus-utils:jar:3.0, commons-jxpath:commons-
jxpath:jar:1.3, commons-io:commons-io:jar:2.0.1, org.ow2.asm:asm:jar:4.0, commons-lang:commons-lang:jar:
2.6, org.sonatype.aether:aether-util:jar:1.12: Failure to transfer
com.jayway.maven.plugins.android.generation2:android-maven-plugin:jar:3.1.1 from http://repo1.maven.org/
maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central
has elapsed or updates are forced. Original error: Could not transfer artifact
com.jayway.maven.plugins.android.generation2:android-maven-plugin:jar:3.1.1 from/to central (http://
repo1.maven.org/maven2): No response received after 60000

along with:
Project build error: Unknown packaging: apk

on the line
<packaging>apk</packaging>

A: I have tried set up a fresh second IDE myself and everything works as expected, suppose you have installed both Android SDK and Maven properly (better to use latest version), these are the only Eclipse plugins required to work with Mavenized Android Project:

*

*adt

*m2e

*m2e-android

Check out my screenshot Help -> Install New Software... -> what is already installed:

If you follow instructions from this page starting with a new project, the <packaging> error is most likely due to earlie version of maven-release-plugin (if you do not explicitly specify one). By hovering mouse on <packaging> element in pom.xml, you should get some hint like:

maven-resources-plugin prior to 2.4 is not supported by m2e. Use maven-resources-plugin version 2.4 or later.

Adding the following plugin under <plugins>:
<plugin>
  <artifactId>maven-resources-plugin</artifactId>
  <version>2.5</version>
</plugin>

Then Right-click on new project and select Maven -> Update Project Configuration, this should fix all error and give you a working example.

A: I had the same problem trying to install the android m2e in eclipse JUNO.
Then tried to install through "Install new software" wizard, instead of market place.
Add the following as an update site and select "Android For Maven eclipse" from the listed softwares and install.
http://rgladwell.github.com/m2e-android/updates - Thanks to @NullNoname for providing the update site.


text:
Q: Background color css does not apply properly

Selected Items

X Test 1A:

Test 2A X

Test 3A X

X Test 1B:

Test 2B X

X Test 1C:

Test 2C X

Test 3C X

X Test 1D:

Test 2D X

Test 3D X

Test 4D X

Test 5D X

Style added for popup-data is(in a css file)
#popup-data {
  background-color:aliceblue;
}

What is see is background-color is incorrectly added as shown below

What is incorrect in the html, I even checked but did not find any incomplete div


text:
Q: Why a for loop stops at 2nd iteration reading an UTF coming from the client? im trying the following: im doing a Server-Client message exchange. Im asking to the client the number of tasks he wants to perform and asking for a description and status of the task in the first for loop, and later create a object from the class i've created, and put it inside the ArrayList. When it comes the second iteration the console hangs and never asks for the third or any number of iteration that is further from the 2nd one. Then i guess that the same problem is happening in the status... That is the code i've writed for the excercise, sorry if is for someone a silly question, im new and im trying to learn. Thank you very much
Server.java
package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class Server {

    private final int Port = 9876;
    private ServerSocket serverSocket;
    private Socket socket;
        ArrayList<Tarea> tarea = new ArrayList<Tarea>();
        Scanner sc = new Scanner(System.in);

    public Server() throws IOException {
        serverSocket = new ServerSocket(Port);
        socket = new Socket();
    }

    public void iniciarServidor() throws IOException {

        while (true) {
            System.out.println("Esperando al cliente");
            socket = serverSocket.accept();

            System.out.println("El cliente se ha conectado");
            DataOutputStream input = new DataOutputStream(socket.getOutputStream());
            DataInputStream output = new DataInputStream(socket.getInputStream());

            input.writeUTF("Introduzca el nombre del cliente: ");
            String nombre = output.readUTF();
            System.out.println("Nombre cliente: " + nombre);

            String descripcion = "";
                        boolean estado;

            Tarea t = new Tarea();
                input.writeUTF("Muy buenas " + nombre
                        + " especifique numero de tareas:");
                                int numeroTareas = output.readInt();

                                for(int i = 0;i<numeroTareas;i++){

                                    input.writeUTF("Especifique descripcion para la tarea "+i+" :");
                                    descripcion = output.readUTF();
                                    input.writeUTF("Especifique el estado 'true o false' para la tarea "+i+" :");
                                    estado = output.readBoolean();

                                    t = new Tarea(descripcion,estado);
                                    tarea.add(t);

                                }

                                sc.nextLine();

                                input.writeUTF("El servidor va a enviar todas las tareas");

                                for(int i = 0;i<tarea.size();i++){
                                    input.writeUTF("Numero tarea: "+i);
                                    input.writeUTF("Descripcion: "+tarea.get(i).getDescripcion());
                                    input.writeUTF("Estado: "+tarea.get(i).isEstado());
                                }

            socket.close();
            System.out.println("Cliente desconectado");
            output.close();
            input.close();
        }
    }

}

Client.java
package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import server.Tarea;

public class Client {

    private final String Host = "localhost";
    private final int Port = 9876;
    private final Socket socket;
    ArrayList<Tarea> tarea = new ArrayList<Tarea>();

    public Client() throws IOException {
        socket = new Socket(Host, Port);
    }

    public void iniciarCliente() throws IOException {

        String descripcion;
        boolean estado;

        DataInputStream input = new DataInputStream(socket.getInputStream());
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());

        Scanner sc = new Scanner(System.in);
        //Servidor solicita nombre usuario
        System.out.println(input.readUTF());
        output.writeUTF(sc.nextLine());
        //Numero de tareas a realizar
        System.out.println(input.readUTF());
        output.writeInt(sc.nextInt());
        sc.nextLine();
        //Servidor solicita descripcion tarea
        System.out.println(input.readUTF());
        descripcion = sc.next();
        output.writeUTF(descripcion);
        //Servidor solicita estado de tarea
        System.out.println(input.readUTF());
        estado = sc.nextBoolean();
        output.writeBoolean(estado);
        //Servidor confirma que va a enviar las tareas
        System.out.println(input.readUTF());
        //Servidor envia todas las tareas;
        System.out.println(input.readUTF());
        System.out.println(input.readUTF());
        System.out.println(input.readUTF());

        socket.close();
        input.close();
        output.close();
        System.out.println("Fin, Desconectado del servidor");
        sc.close();

    }

}

Tarea.java
package server;

import java.util.ArrayList;

/**
 *
 * @author Lluis
 */
public class Tarea {

    private String descripcion;
    private boolean estado;

    public Tarea(){

    }

    public Tarea(String descripcion, boolean estado){
        this.descripcion = descripcion;
        this.estado = estado;
    }

    public String mandarDesc(ArrayList<Tarea> tarea) {

        for(int i=0; i<tarea.size(); i++) {
            setDescripcion(tarea.get(i).getDescripcion());
        }

        return getDescripcion();
    }

    public boolean mandarEstado(ArrayList<Tarea> tarea) {

        for(int i=0; i<tarea.size(); i++) {
            setEstado(tarea.get(i).isEstado());
        }

        return isEstado();
    }

    public String toString() {
        return getDescripcion()+ " Estado: /n " + isEstado();
    }

    /**
     * @return the descripcion
     */
    public String getDescripcion() {
        return descripcion;
    }

    /**
     * @param descripcion the descripcion to set
     */
    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    /**
     * @return the estado
     */
    public boolean isEstado() {
        return estado;
    }

    /**
     * @param estado the estado to set
     */
    public void setEstado(boolean estado) {
        this.estado = estado;
    }

}

A: What jumps to my attention:
Server.java
Scanner sc = new Scanner(System.in);
...
sc.nextLine();

Is it possible that your server is waiting for a keypress on stdin rather than on the network socket?


text:
Q: find mean batting average ("Ave") and total number of centuries by country but only including records for which starting year is 2010 or later I have a dataset of cricket players and want to find mean batting average "Ave" and total number of centuries "Hundreds" by country (column) but only including records for which starting year "From" is 2010 or later
Ave, Hundreds, Country, From are the columns name
new_data.groupby(['Country'])['Ave'].mean()
new_data.groupby(['Country'])['Hundreds']

I want to apply these two in a single line and also want to use the condition that starting Year should be 2010 or later

A: I am assuming you have two columns only Ave and Hundreds. You can do it by using Pandas .agg method.
grouped_data = new_data[new_data['From'].year >= 2010].groupby(['Country'])
grouped_data.agg(['mean', 'sum'])

Let me know if it doesn't work.

A: new_data[new_data['From'].year >= 2010].groupby(['Country'])['Ave'].mean()

You can do the same for 'Hundreds'.


text:
Q: Meta and Stack Overflow footer broken When I reduced my browser size, the footer on Meta and Stack Overflow appears broken:

This happens on any other Stack Exchange site:

But it's working perfectly for Code Review (still in Beta).

A: An answer to a related question I had asked recently
html{min-width:1000px;}

would also work here, because if I understand right, this bug occurs when you make the window small and scroll sideways, correct?


text:
Q: Error invalid conversion from 'char' to 'est*' -fpermissive Es mi primera vez en este sitio, entonces, ¡aquí vamos!. He estado tratando de resolver este error, pero no he encontrado la manera. Este es el código completo. El error aparece en la línea 44. El programa es sobre añadir N números de estudiantes y organizarlos por su peso mediante el método de inserción.
#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;
struct Estudiante{ //Estructura que almacenará los datos de los estudiantes
    char nomb;
    float peso;
};
Estudiante *est = new Estudiante[100]; //Puntero para añadir nuevo estudiante
void Insercion(int total, struct est* nomb, struct est* peso){ //Aplicación del método de inserción
    int i,aux;
    for(i = 0; i < total; i++){
        aux = est[i].peso;
        while((i > 0) && (est[i-1].peso > aux)){
            est[i] = est[i-1];
            i--;
        }
        est[i].peso = aux;
    }
}
void Mostrar(int total){ //Función para mostrar los estudiantes organizados con respecto a su peso
    int i;
    cout<<"Lista de peso de estudiantes:"<<endl<<endl;
    for(i = 0; i < total; i++){
        cout<<"Nombre: "<<est[i].nomb<<endl;
        cout<<"Peso: "<<est[i].peso<<endl<<endl;
    }
}

int main(){ //Función principal del programa, donde se añaden nuevos estudiantes, se ordenan y se muestran
    int i, total;
    cout<<"Cuantos estudiantes desea registrar?: ";
    cin>>total;
    cout<<endl;
    do{
        cout<<"**** ESCUELA PUBLICA ****"<<endl<<endl;
        cout<<"\tDatos de nuevo estudiante"<<endl;
        cout<<"* Ingrese el nombre: ";
        cin>>est[i].nomb;
        cout<<endl;
        cout<<"* Ingrese el peso (kg.): ";
        cin>>est[i].peso;
        cout<<endl;
        Insercion(total,est[i].nomb,est[i].peso);
    }while(i == total);
    Mostrar(total);
    return 0;
}

A: El error es claro y conciso. Tal vez no lo entiendas por estar en inglés, te lo traduzco:

Error invalid conversion from 'char' to 'est*'

Error conversión no válida de 'char' a 'est*'

Sucede al llamar a la función Insercion:
Insercion(total,est[i].nomb,est[i].peso);

Cuya firma es:
Insercion(int total, struct est* nomb, struct est* peso)

*

*Primer parámetro, de tipo int.

*Segundo parámetro, de tipo struct est*.

*Tercer parámetro, de tipo struct est*.

¿Con qué parámetros la estás llamando?
//                             char
//                      /‾‾‾‾‾
//                      |
//                 vvvvvvvvvvv
   Insercion(total,est[i].nomb,est[i].peso);
//           ^^^^^             ^^^^^^^^^^^
//             |                    |
//              \___ int             \_____ float

El segundo y tercer parámetro son incompatibles con el tipo definido en la firma de la función pues el segundo parámetro espera un struct est* y le pasas un char mientras que el tercer parámetro espera un struct est* y le pasas un float.


text:
Q: Django Queryset - Get counts by model.choices I have below model, which has all the details about customer Leads. Customer wants to see his Leads followup statuses.
class FollowUp(models.Model):
    CALL_CHOICES = [("0", "Call Unanswered"),
                  ("1", "Call Later"),
                  ("2", "Visit Scheduled"),
                  ("3", "Not Visited"),
                  ("4", "Not reachable"),
                  ("5", "Wrong Number"),
                  ("6", "Not Interested"),
                  ("7", "Deal Closed")]
    status = models.CharField(_("Call Status"),
            max_length = 20,
            choices = CALL_CHOICES,
            default = '1'
        )
    next_action_on = DateTimeField(_("Next Action"), auto_now_add=False,
                null=True, blank=True)
    reminder = models.BooleanField(_("reminder"), default=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

class Lead(models.Model):
    followups = models.ManyToManyField(FollowUp, verbose_name=_("Follow up"), blank=True)
    ...

How can I get Lead counts of each status choice. such as
{
 'Call Unanswered': 12 #Leads,
 'Call Later': 10 # Leads
 'Visit Scheduled': 20, #Leads,
 ...
}

A: Try this:
Lead.objects.aggregate(
    **{
        choice[1]: Count(
            'followups', filter=Q(followups__status=choice[0])
        ) for choice in Followup.CALL_CHOICES
    }
)

This would return something like:
{'Call Unanswered': 0,
 'Call Later': 0,
 'Visit Scheduled': 0,
 'Not Visited': 0,
 'Not reachable': 0,
 'Wrong Number': 0,
 'Not Interested': 0,
 'Deal Closed': 0}

A: I think you can use the for iterator to iterate through CALL_CHOICES and filter the rows based on the status.
queryset = Leads.objects.all()
res = {}
for i in FollowUp.CALL_CHOICES:
    res[i[1]] = queryset.filter(followups__status=i[0]).aggregate(total=Count('pk'))['total']
print(res)

At the end of the script you will get each pair of values.

A: You would get the count like this:
>>> Leads.objects.filter(follow_up__status=0).count()
>>> 10


text:
Q: Split-Path with : in the path I have an odd Registry path that Autodesk AutoCAD uses, and I need to do a Split-Path on it to then push a value to Default. The path is
HKCU\Software\Autodesk\DWGCommon\shellex\Apps{F29F85E0-4FF9-1068-AB91-08002B27B3D9}:AutoCAD(Default)
That : before AutoCAD is making trouble in PoSH 2.0, where Split-Path -parent returns everything before the :, rather than including :AutoCAD as it should. I tried -literalPath and it seems that's newer than 2.0, correct? Anyone have any thoughts?
EDIT: To clarify, a correct result would be a parent of
HKCU\Software\Autodesk\DWGCommon\shellex\Apps{F29F85E0-4FF9-1068-AB91-08002B27B3D9}:AutoCAD
and a leaf of
(Default)
The info above is somewhat erroneous in that I am typing a BACKSLASH between AutoCAD & (Default) but it is getting dropped by the editor. :( And I just noticed the same is true of a \ after Apps and before the opening curly brace. I just tried escaping the curly braces, on a lark, but that didn't help. It still treats the : as a drive delimiter and barfs looking for a drive called
HKCU\Software\Autodesk\DWGCommon\shellex\Apps{F29F85E0-4FF9-1068-AB91-08002B27B3D9}, but with the backslash after Apps that still won't show up. Dang, maybe I just need to give up and go have a beer. It is 9:30 on a Friday night after all.

A: In order for Split-Path to recognize the path as rooted, you'll have to introduce an artifical ":" after the first component:
$Path = "HKCU\Software\Autodesk\DWGCommon\shellex\Apps{F29F85E0-4FF9-1068-AB91-08002B27B3D9}:AutoCAD(Default)"

# Find first occurrence of \
$FirstSplit = $Path.IndexOf('\')

if($Path[$FirstSplit - 1] -ne ':'){
    $RootedPath = $Path.Insert($FirstSplit, ':')
}

$Value = Split-Path $RootedPath -Leaf
# Remove ":" again
$Key = (Split-Path $RootedPath -Parent).Remove($FirstSplit,1)

Now, they should have been split properly:
PS C:\> "{0}`n  {1}" -f $key,$value
HKCU\Software\Autodesk\DWGCommon\shellex
  Apps{F29F85E0-4FF9-1068-AB91-08002B27B3D9}:AutoCAD(Default)


text:
Q: How do browsers implement event polling? So I am trying to get an idea of how browsers are internally implemented. The browser must poll the event queue for events, but I am wondering how frequently this is done or If there is some sort of pattern/known solution to go about this?
You clearly can't do
while(1) {
    //check the event queue for events
}

B/c that would lock up the entire thread and the browser uses a single-threaded execution model in which it checks the event queue for any events, if there is an event in the event queue - then it executes it. (At least that's how I understand it)


text:
Q: Doubling elements of a list in f# I am attempting to double the elements of a given list but am getting an error "
This expression was expected to have type
    ''a list'
but here has type
    'int'
"
when defining a new list
let list1 = [5;10;15;20;25;30]
let rec doubleListElements list =
    match list with
    |[]-> 0
    |head::tail ->
        let doubledList = [head*2::doubleListElements tail]
        0
let printList = doubleListElements list1
printfn "%A" printList

I am very new to f# and don't fully understand how things work, I am more used to an object oriented approach

A: The function in your question will work with some changes:
let rec doubleListElements list =
  match list with
  | [] -> []
  | head::tail -> head*2::doubleListElements tail

First important thing to keep in mind is "what do I want to give to and receive from this function". In your case, your input is a int list and desired output is an int list. This means wherever your function returns a value it must be an int list. Your function has two places where a value is returned:
  | [] -> [] // return empty list
  | head::tail ->
      head*2::doubleListElements tail // return a list (but recurse)

In your original function your return values are always 0 which of course doesn't satisfy the int list return type.
|[]-> 0 // return value
|head::tail ->
    let doubledList = [head*2::doubleListElements tail]
    0   // return value

In this expression, a doubledList is created but that value is essentially discarded because it is unused and it's not the return value. The return value is the final value in the expression: 0. I think this is a very common mistake to see as people learn functional languages that are expression-based coming from imperative statement-based languages.
In this particular expression only the final value matters. In a statement-based language you might've mutated some program state before returning a value (which is also totally possible in F# but mutability is usually avoided).
let foo x =
  let y = x + x // the value of this expression is discarded: y is unused
  x * x         // the value of this expression is returned

The only other necessary change is to not wrap your returned list in another list in each recursion. head*2::doubleListElements tail is just a list. [head*2::doubleListElements tail] is the same list inside of another list because it's wrapped in square bracket list literals. After that change it works:
val printList : int list = [10; 20; 30; 40; 50; 60]

A: You can make use of different kinds of data structures, such as sequences:
namespace FSharpBasics

module DoubleList =

    let private list1 = [ 5; 10; 15; 20; 25; 30 ]

    (*operations*)
    let doubleList (list: List<int>) =
        Seq.init list.Length (fun index -> list.[index] * 2)
            |> Seq.toList

    [<EntryPoint>]
    let main argv =
        doubleList list1
            |> printf "%A"
        System.Console.ReadKey() |> ignore
        0


text:
Q: How to post form data to Google Apps Script What is the best/easiest way to post form data from my HTML page to my GAS script?
$(document).ready(function() {
  $.getJSON(SCRIPT_URL+"?callback=?", { method:"addRow"}, function (data) { alert(JSON.stringify(data)); });
});

A: If you are using Apps Script HTML Service, you can use google.script.run.
Google Documentation - Client-side API - call server-side Apps Script functions
From a app or site outside of Google, make an HTTP Request to the Apps Script URL.


text:
Q: How do I enable the radio button after I disable it? I put my code like this, so when I select that radio button it will disable the same button in other form. But I realized if I select another radiobutton it will not enable, which means my code will only help me disable the radiobutton but not help me enable it back. But I have no idea how to.
Here's my code
If RadioButton1.Checked = True Then
        Form1.TextBox1.Text = "Literary Studies and Creative Writing 10"
        Form12.RadioButton1.Enabled = False
        Form20.RadioButton1.Enabled = False
    End If

A: The question you're asking is somewhat ambiguous, but just for the sake of helping I want to throw in some ideas.
You could make a "reset state" function inside your forms and that function can enable back all the radios or empty textbox, etc.
So whenever you want to enable back the controllers in a different form you can re enable them calling that function maybe on some event related to the form.
For example :
Function EnableRadios()
  RadioButton1.Enabled = True
  RadioButton2.Enabled = True
End Function

Also if you make your forms work as a template your function could work in any form, the more standard your form is the better approach you will have on the task.


text:
Q: MIP SDK 1.10.97 silently exits with -1073740791 I'm developing an Azure Function for removing information protection from files using the
MIP SDK v. 1.10.97. After some successfull calls to protect or unprotect files the Azure Function silently crashes with code -1073740791.
This did not happen with version 1.9.X.
Any ideas what's happening here?
Thomas


text:
Q: hive load external table from dynamic location(partitioned) I need to create a hive table(external) to load data generated by another process. I need to be partitioned by date, But the problem is, there is a random string in the path.
Example input paths :
/user/hadoop/output/FDQM9N4RCQ3V2ZYT/20170314/
/user/hadoop/output/FDPWMUVVBO2X74CA/20170315/
/user/hadoop/output/FDPGNC0ENA6QOF9G/20170316/
.........
.........

Here 4th field in the directory is dynamic(which cannot be guessed). Each of these directories will have multiple .gz files
What location would I give while creating the table?
CREATE EXTERNAL TABLE user (
userId BIGINT,
type INT,
date String
)
PARTITIONED BY (date String)
LOCATION '/user/hadoop/output/';

is this correct? if so how do I partition it based on the date(last field in the directory)?

A: Since you are not using the partition convention you'll have to add each partition manually.

*

*The table location does not matter, but for clarity leave it as it is now.

*I would recommend to use date type for the partition or at least the ISO format, YYYY-MM-DD.

*I would not use date as a column name (nor int,string etc.).

PARTITIONED BY (dt date)

alter table user add if not exists partition (dt=date '2017-03-14') location '/user/hadoop/output/FDQM9N4RCQ3V2ZYT/20170314';
alter table user add if not exists partition (dt=date '2017-03-15') location '/user/hadoop/output/FDPWMUVVBO2X74CA/20170315';
alter table user add if not exists partition (dt=date '2017-03-16') location '/user/hadoop/output/FDPGNC0ENA6QOF9G/20170316';


text:
Q: Zend framewirk session data get changing and displaying other user data not the logged user data if someone can help with zend returning data from wrong user
Our current problem is when multiple users use our zend application it frequently returning data from other users to another curently loged user,. ie it is mixing users data. We have tried reinstaling the PC, changing browsers, disabling caching..., nothing helped.
Any help apreciated

A: In zend 2 you can use container, and whenever user has logged in and you want track his session you can do this as following:
$loggedUser = new Container('user');
$loggedUser->loggedIn = true;
var_dump($loggedUser->loggedIn); //will print true

In case you want to track guest session, simply you can use new different Container for it
$guest = new Container('guest');
$guest->visited = true;
var_dump($guest->visited); //will print true

also you can use offsetGet, offsetSet instead of setting variables directly
$guest = new Container('guest');
$guest->offesetSet('visited') = true;
var_dump($guest->offsetGet('visited'));


text:
Q: Ghostscript with AES-256 password protection for PDF 2.0 documents A password protected pdf file can be generated with ghostscript:
gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=protect.pdf -sOwnerPassword=pwd1 -sUserPassword=pwd2 -dCompatibilityLevel=2.0 test.pdf

The output file has the newest pdf version 2.0 which has unicode support for password protection. But according to pdfinfo the obsolete RC4 algorithm was used:
pdfinfo protect.pdf -upw pwd2
CreationDate: Sat Apr 21 09:10:14 2018 CEST
ModDate: Sat Apr 21 09:10:14 2018 CEST
Tagged: no
UserProperties: no
Suspects: no
Form: none
JavaScript: no
Pages: 26
Encrypted: yes (print:yes copy:yes change:yes addNotes:yes algorithm:RC4)
Page size: 612 x 792 pts (letter)
Page rot: 0
File size: 288060 bytes
Optimized: no
PDF version: 2.0

According to https://www.pdflib.com/knowledge-base/pdf-password-security/encryption/ the PDF 2.0 version is able to encrypt PDF files with the AES-256 standard. How can I do this with ghostscript?

A: The Ghostscript pdfwrite device doesn't support anything except the original RC4 algorithm for encrypting PDF files. The PDF interpreter can decrypt documents using later algorithms.
So as sneep says, you can't do this with Ghostscript and the pdfwrite device.


text: Q: Facebook Web SDK for login Resize I have used Facebook WEB SDK for LOGIN in ROR web application, login popup is what i am getting is in small size, so from background i can use the app without login to facebook, I want to change the width and height of popup so that it should restrict the app from background?Does any know about it, please let me know.


text:
Q: How to calculate Standing Waves in Electrical Cables? I have a 20 metre Coaxial Cable. I send digital signals down the cable ranging from 5 KHz to 50 KHz.
I have noticed a pattern in the noise ratio, an oscillating wave. I predict this is to do with standing waves in the cable.
How can I calculate at what Frequencies these standing waves would occur in the cable?

A: Your oscillatory pattern can't be owing to standing waves. The speed of light in such cables is of the order of $0.5\,c$ to $0.7\,c$, so your first standing wave resonant frequency (depending on the impedance connected to the cable's end) will be at least about 1MHz. This statement depends of course on how much of the "oscillating noise" period you saw - I presume you mean the noise varies sinusoidally with frequency. If the reflexion co-efficient from the cable's far end is $\Gamma$ (set by the impedance connected to the far end), then the impedance seen at the cable's input is:
$$Z_{in} = \frac{1 + \Gamma \exp\left(i\frac{4\,\pi\,\nu}{c_c} \ell\right)}{1 - \Gamma \exp\left(i\frac{4\,\pi\,\nu}{c_c} \ell\right)}$$
where $c_c\approx 0.5\,c$ is the speed of light in the cable, $\nu$ the source frequency and $\ell$ the cable's length. Your varying noise arises because the load $Z_{in}$ presented to the source varies with frequency, and thus affects the source's noise performance. If $Z_{in}$ is indeed modelled by the above equation, I plot the variation in this quantity below for frequency between 0Hz and 5MHz below for various values of $\Gamma$

and below, for a small value of $\Gamma = 0.1$ in the same frequency range:

As you can see, the variation in the range 0Hz to 50kHz is negligible.
Therefore I agree with user1038377's answer: the coaxial cable is acting as a lumped impedance (theorised to be an LC circuit by user1038377) and you are maybe seeing resonances, although I can't explain how you would get a sinusoidal variation with frequency out of a lumped ciruit.
To calculate the standing wave frequencies for your particular values, note that you will get a peak in input impedance when $\arg(\Gamma) + \frac{4\,\pi\,\nu}{c_c} \ell = 2 j \pi;\;j\in\mathbb{Z}$ and a trough in impedance when $\arg(\Gamma) + \frac{4\,\pi\,\nu}{c_c} \ell = (2 j +1)\pi;\;j\in\mathbb{Z}$. Note than:
$$\Gamma = \frac{Z_0 - Z_{load}}{Z_0 + Z_{load}}$$
where $Z_0$ is the coax line's characteristic impedance (probably $50\Omega$) and $Z_{load}$ is the load connected to the line's far end. Since the latter is generally complex, note that $\arg(\Gamma)$ can be nonzero. And you don't actually get standing waves (i.e. waves with nodal points) unless the $\Gamma = \pm1$, you get instead constant points of minimum and maximum amplitude at points with axial co-ordinate $z$ measured backwards towards the source from the load on the end of the line as follows:
$$\arg(\Gamma) + \frac{4\,\pi\,\nu}{c_c} z_{max} = 2 j \pi;\;j\in\mathbb{Z}$$
defines the points where there is maximum voltage amplitude and minimum current amplitude and:
$$\arg(\Gamma) + \frac{4\,\pi\,\nu}{c_c} z_{min} = 2 j \pi + 1;\;j\in\mathbb{Z}$$
defines the points where there is minimum voltage amplitude and maximum current amplitude. A quantity often defined is the Standing wave ratio, which is the ratio of minimum voltage / current to maximum voltage / current and it is given by $SWR = (1-|\Gamma|)/(1+|\Gamma|)$;
More information can be found on the Wikepedia "Transmission Line page.

A: It's simply an LC circuit. The linear frequency is $f = 1/(2\pi\sqrt{LC})$. If you use the approximation of a thin long wire to compute L and C, then you may obtain $LC \propto l^2$ where $l$ is the length of the wire. So $f \propto 1/l$.

A: Sorry, can't comment the answer of Rod Vance so writing a new one. My previous offer regarding to the LC-circuit was wrong because accurate estimation of the eigenfrequency gives f ~ 1 MHz. The observed frequency ~50kHz may be formally connected with a speed ~(0.05-0.1)c but there is no such velocities in the experiment.
At the other side, the wavelength of the 50kHz signal is about tens times higher than the cable length. Maybe the phenomena observed is (a) seesaw of the electrons by the (b) force which is truncated in the frequency space. Fourier image of the meander has a series of diminishing maxima separated by frequency of the meander. The cable itself may act as a filter, so the smooth shifting of the input frequency leads to the periodical variation of the integrated power spectrum of the meander inside the filtering window of the cable. However, I'm not a specialist in this area, so I and can't make more detailed calculations.


text: Q: DC Coaxial Power Connector Rated for 20A I have a 12V 20A power adapter seen here (https://www.ledwholesalers.com/v2/index.php?route=product/product&path=40_117&product_id=999). I would like to connect to this power supply, but my issue is that it ends with a coaxial connector and I can't find a compatible item. I've found something close to what I want (https://powerwerx.com/21mm-coaxial-socket-powerpole-adapter), but this is only 18awg whereas I'm looking for 12awg. Is there something better suited for the job or something I'm missing?


text:
Q: Why does Zsh have two processes? When I look at pstree output, an instance of zsh is a stack of two processes.
 ├─tmux: server─┬─tmux: server
 │              ├─13*[zsh───zsh]
 │              ├─zsh─┬─pstree
 │              │     └─zsh
 │              └─zsh─┬─vim
 │                    └─zsh

Here you can see this system's tmux server has 13 zsh's sitting idle at the shell, one running pstree, and one running vim.
When I run a program in one, the child-zsh is a sibling of that program.
I'm curious what this child zsh process's function is.


text:
Q: WPF Button template I am trying to learn to customize WPF Buttons.
Earlier I used images as Content of the Button but I want to change that into XAML-based objects.
I am trying to fit a Path into the Button's Content but can't get it right.
My version is below
<Window.Resources>
     <Style x:Key="MyStyle" TargetType="{x:Type Button}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <Rectangle RadiusY="2" RadiusX="2" Stroke="Black" Fill="Gray" />
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="0,0,0,0" Visibility="Visible"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Height" Value="22" />
        <Setter Property="Width" Value="22" />
    </Style>
</Window.Resources>

<Button VerticalAlignment="Center" HorizontalAlignment="Center" Style="{DynamicResource MyStyle}">
    <Path Fill="Black" RenderTransformOrigin="0.375,0.375"  >
        <Path.RenderTransform>
            <ScaleTransform ScaleX="0.375" ScaleY="0.375" CenterX="0" CenterY="0"/>
        </Path.RenderTransform>
        <Path.Data>
            <PathGeometry Figures="M22,18L22,8 18,8 18,18 8,18 8,22 18,22 18,32 22,32 22,22 32,22 32,18z" />
        </Path.Data>
    </Path>
</Button>

but it doesn't end up too nicely and I cant get the ScaleTransform to work correctly:

I'm trying to get this kind of result:

A: Not sure, that transorm - is what you need, if you just want centered cross - this is more simple solution (no any changes, except Path in your Button):
        <Path
            Fill="Black"
            Stretch="Uniform"
            Margin="7"
            Data="M22,18L22,8 18,8 18,18 8,18 8,22 18,22 18,32 22,32 22,22 32,22 32,18z"
            />

Actually is Stretch property controls how is your shape is resized to fill its allocated space: MSDN


text:
Q: Number of group homomorphisms from $D_4$ to $S_{3}$
How many group homomorphisms are there from the dihedral group  $D_4$ with eight elements to $S_{3}$?

I am really confuse about this type of problem. How do we find all the group homomorphisms between them, I don't even know how to define the function between them. Can anyone tell me about that?

A: Let $f:D_4\to S_3$ be a group homomorphism .By First Isomorphism Theorem;
$D_4/\ker f \cong \text{Image }f$.
Possible orders of $\text{Image }f=1,2,3,6$ .Now $|\text{Image }f|\neq 3,6$
If $|\text{Image }f|=1\implies f(a)=e \forall a\in D_4$ where $e$ denotes the identity mapping in $S_3$.
If $|\text{Image }f|=2\implies |\ker f|=4$ .
Take  $\text{Image }f=\{e,(12)\}/\{e,(23)\}/\{(e,13)\}$.
Also $D_4$ has three normal subgroups of order $4$ denote them by $T_1,T_2,T_3$.
So we can have $3\times 3$ choices for homomorphisms when $|\text{Image }f|=2$
So we have $9+1=10$ group homomorphisms.

A: Hint: The dihedral group with eight elements is the set of symmetries of a polygon with 4 vertices, symbolized $D_4$. The group is generated by a rotation $r$ of order 4, and a reflection, $s$ of order 2. That is, $D_4=\langle r, s\rangle$. So any group homomorphism from $D_4$ into $S_3$ must assign $r$ to an element whose order is divisible by 4, and $s$ to an element whose order is divisible by 2. These selections will determine the homomorphism completely.
So now the question becomes - how many elements of order 1,2, or 4 are there in $S_3$?


text:
Q: Voltage divider, no power I made a voltage divider using 2k4 and 4k7 resistors.
If I check the voltage with the multimeter, the voltage is correctly converted from 5V to 3.3V however when connect a consumer(small electric motor that should work with very low power) it does not work.
Why would this happen?

A: You need a voltage regulator to drop 5 volt to 3.3 volts if you want to provide a decent enough current to drive an electric motor. A resistor divider will produce 3.3 volts open circuit but, as soon as you connect a load, you draw current and largely destroy the potential dividers ability to deliver a constant 3.3 volts.
Use a voltage regulator.

A: The problem is that a voltage divider made with simple resistor can not guarantee a fix voltage output if a load is apply. By adding this load, the resistance of the circuit change and then change the output :

simulate this circuit – Schematic created using CircuitLab
\$V_{out} = V_{in}*\frac{R_2 // R_{load}}{R_1+R_2//R_{load}}\$
As you can see, \$V_{out}\$ may change if you add a load.
As said @AndyAka, you remplace the voltage divider by a voltage regulator. It's extremely easy to use (few resistor and capacitor) and it will fit your need.


text:
Q: Is there a way to run a perl script on a windows system without having to install anything? I have a handy perl script that I use on my linux systems to check some database information in mysql.  I'd like to have a portable version of this available for Windows (specifically Windows 2008 and 2012) so I can perform the same database checks.
Is there a way I can bundle a runtime (non-install) implementation of perl?  Or do I need to fully install perl?

A: You can use the PortableZIP edition of Strawberry Perl, available here.
There's also a ZIP edition that doesn't require admin privileges, but you need to run some post-install scripts manually after unzipping.
Depending on your script something like Perl2Exe might also help:

Perl2Exe is a command line program for converting Perl scripts to
  executable files.
This allows you to create stand alone programs in Perl that do not
  require the Perl interpreter. You can ship the executable files
  without having to ship your Perl source code.
Perl2Exe can generate executables for Windows and Unix target hosts.
Perl2Exe can generate cross-platform code.  For example you can
  generate code for Solaris from a Linux machine.
Perl2Exe also allows you to create no-console programs using Tk.


text:
Q: Get all P Tags in the UL tags, Javascript Regex I am racking my brain trying to figure out a regex for this. I have the following invalid html:
...some html tags above...

Bullet points:

point 1

point 2

Other Bullet points:

point 3

point 4

...some html tags below...

I'm trying to get all the data between the

 tags that are within

 tags and replace them with valid li tags. I.e. I plan to replace the above with the below:
...some html tags above...

Bullet points:

point 1

point 2

Other Bullet points:

point 3

point 4

...some html tags below...

A: You should do 2 RegeXp for that, first to get the inner HTML of the UL tags, and then replace the P tags with LI tags.
First  get all UL tags:
var UL_tags=/
([\s\S]*?)<\/ul>/g
// [\s\S] Mean any char including new lines.

Now, all you have to do:
new_html=myHtml.replace(UL_tags,function(r0,innerHTML){
    return innerHTML.replace(/
/g,'
').replace(/<\/p>/g,'
')
})

Be aware that it is not working for nested UL tags (UL inside UL)
UPDATE: Now, you need to support attributes inside the UL, for example:
 so we need to ignore the tag attributes, so the Regexp need to be little more complicated (sorry):
 var UL_tags=/
]*?>([\s\S]*?)<\/ul>/g
 // [^>] Mean any char except closing tag.

A: Try this in jQuery:
$('p').each(function(index){
    p_str = $(this).text();
    ....
})


text:
Q: How to get Image width and height from Multiples Files input? I want to get each of images width and height from multiple input files in Javascript or JQuery. I search in google and tried many ways, but I can't found the way to do it.
Here is my code:
<input id="uploadBtn" type="file" class="upload" multiple="multiple" name="browsefile" style="display: none !important;" />

<input type="button" class="btn submit-btn" value="ファイル追加" onclick="document.getElementById('uploadBtn').click();" style="float: right;"/>

<input id="filename" type="hidden" />

Here is my Javascript:


text:
Q: Restore FragmentManager backstack I have different layouts for portrait and landscape. My UI uses fragments stacked in back stack. On device rotation I need to set a different layout for landscape/portrait and restore the stack of fragments(note that each fragment also has different layouts for portrait and landscape). I need to preserve data in EditTexts, selections etc.
To make it easier imagine that in portrait I have the following fragments in my backstack FragmentA->FragmentB->FragmentC. Then I rotate the device, a different layout loads for my activity and I need to restore FragmentA->FragmentB->FragmentC again but with their views for landscape. How should I proceed?


text:
Q: How to get the count of unread messages in React native with gifted chat library? Am currently using react native gifted chat for the message/chat feature in my application.
Now I want to show the unread messages for the user, does anyone have an idea about it or any suggestions to tackle this.
Any help/Suggestion will be appreciated,
Thanks in advance.
React native gifted chat link

A: There is no such feature right now. But you can do that on chat list screen by managing the messages.
After you receive a message you can mark as delivered and store and when you open mark as read. So you can count no. of messages with unread status. you have to manage it using redux.


text:
Q: How to handle timeout exception in protractor I'm using protractor to automate my application.
My test result is displaying 0 failures after getting timeout error
My Code
var EC = protractor.ExpectedConditions;
        browser.wait(EC.presenceOf(element(by.id('xoxoxoxo'))), 5000).then(function () {
        element(amkailogo).getAttribute('src').then(function (val) {
        if (val.indexOf('Amkai-Company-Logo') > -1) {
        /.../
        }
        else {
          /.../
         }
         });
        }, function (err) {
         console.log(err.stack);
        });

i gave some random text as a locator xoxoxoxo, and the error message is
**********Error: Waiting for header displayName
Wait timed out after 5000ms

But my test result is
Finished in 6.115 seconds
1 test, 0 assertions, 0 failures

how to make expected conditions to catch timeout error so that my console should display 1 failure instead of 0 failure

A: Your test doesn't fail because it doesn't have an assertion/expect.

A: As @Brine already pointed out, you don't assert anything in your test, you just have a wait that resulted in an error. In other words, 3 things might happen during a test run:

*

*test passes

*test fails (expectation failed)

*error (this is what happens here)

Your test fails with an error - a timeout error thrown by the browser.wait(). And it is quite a normal situation when a test did not pass because of the error as opposed to because of the expectation failure. We just usually provide a meaningful error message to ease debugging:
browser.wait(EC.presenceOf(element(by.id('xoxoxoxo'))), 5000, "Element did not become present");
element(amkailogo).getAttribute('src').then(function (val) {
    if (val.indexOf('Amkai-Company-Logo') > -1) {
    /.../
    }
    else {
      /.../
    }
});

And we are actually enforcing to have this message provided for every browser.wait() in the project by using eslint-plugin-protractor plugin to ESLint static code analysis tool.


text:
Q: mounting permission denied in docker I was facing issues installing docker on cloud server according to the official guide(Install Docker Engine on Ubuntu). I finished old version's uninstallation, the repository setting up and docker engine installation (sudo apt-get install docker-ce docker-ce-cli containerd.io). However, I got an error when running hello-world.
wyf@VM1103-Timi:~$ sudo docker run hello-world
docker: Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "process_linux.go:449: container init caused \"rootfs_linux.go:58: mounting \\\"proc\\\" to rootfs \\\"/var/lib/docker/overlay2/e9fedf64e8983aa01e513cee591cdfd7fc60962466a476b51fc1ead682ec8022/merged\\\" at \\\"/proc\\\" caused \\\"permission denied\\\"\"": unknown.
ERRO[0000] error waiting for container: context canceled

I tried restart docker and server, but the problem still exists.
So, it would be great if someone can guide me in fixing this error.
Please let me know if you have any idea about this issue.
Thank you very much!
Ps:
My system is Ubuntu 18.04. Thus, I did not have selinux. Instead of selinux, I checked AppArmor log.
May 19 21:14:55 VM1103-Timi networkd-dispatcher[155]: WARNING:Unknown index 37 seen, reloading interface list
May 19 21:14:55 VM1103-Timi systemd-networkd[126]: veth71cf495: Link UP
May 19 21:14:55 VM1103-Timi containerd[170]: time="2020-05-19T21:14:55.679793295+08:00" level=info msg="shim containerd-shim started" address="/containerd-shim/moby/4c207ce1273d2c863ee419c5ebb271163a031394bd4c17ee75d44267d631954d/shim.sock" debug=false pid=106265
May 19 21:14:55 VM1103-Timi containerd[170]: time="2020-05-19T21:14:55.767796543+08:00" level=info msg="shim reaped" id=4c207ce1273d2c863ee419c5ebb271163a031394bd4c17ee75d44267d631954d
May 19 21:14:55 VM1103-Timi dockerd[15100]: time="2020-05-19T21:14:55.776863367+08:00" level=error msg="stream copy error: reading from a closed fifo"
May 19 21:14:55 VM1103-Timi dockerd[15100]: time="2020-05-19T21:14:55.776953910+08:00" level=error msg="stream copy error: reading from a closed fifo"
May 19 21:14:55 VM1103-Timi systemd-networkd[126]: veth71cf495: Link DOWN
May 19 21:14:55 VM1103-Timi dockerd[15100]: time="2020-05-19T21:14:55.927805156+08:00" level=error msg="4c207ce1273d2c863ee419c5ebb271163a031394bd4c17ee75d44267d631954d cleanup: failed to delete container from containerd: no such container"

The strange thing is that there is no record of permission-denied error.
Here are my ubuntu version, kernal version and docker info:
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.4 LTS
Release:        18.04
Codename:       bionic

5.3.18-3-pve

Client:
 Debug Mode: false
Server:
 Containers: 8
  Running: 0
  Paused: 0
  Stopped: 8
 Images: 1
 Server Version: 19.03.8
 Storage Driver: overlay2
  Backing Filesystem: <unknown>
  Supports d_type: true
  Native Overlay Diff: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.3.18-3-pve
 Operating System: Ubuntu 18.04.4 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 2
 Total Memory: 4GiB
 Name: VM1103-Timi
 ID: 3G3F:LTVZ:NO25:C7LA:XKQV:ETMB:B6QU:3ZFJ:KBA5:R3KK:QZEA:ZONC
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

It seemed that the AppArmor Profile "docker-default" was lost. "docker-default" was not correctly generated. Check as follows:
root@VM1103-Timi:/etc/apparmor.d# aa-status
    apparmor module is loaded.
    12 profiles are loaded.
    12 profiles are in enforce mode.
       /sbin/dhclient
       /usr/bin/man
       /usr/lib/NetworkManager/nm-dhcp-client.action
       /usr/lib/NetworkManager/nm-dhcp-helper
       /usr/lib/connman/scripts/dhclient-script
       /usr/lib/lightdm/lightdm-guest-session
       /usr/lib/lightdm/lightdm-guest-session//chromium
       /usr/sbin/mysqld
       /usr/sbin/tcpdump
       docker-default
       man_filter
       man_groff
    0 profiles are in complain mode.
    1 processes have profiles defined.
    1 processes are in enforce mode.
       /usr/sbin/mysqld (258)
    0 processes are in complain mode.
    0 processes are unconfined but have a profile defined.

A: Solution is probably to open ports needed. Your system might be running selinux and (ufw or firewalld or iptables) ?and/or others?. Read up a bit on linux firewall tools, in particular the ones running on your system.
For the selinux case, you need to check selinux logs, is it blocking access? Add exceptions using selinux commands.
https://wiki.centos.org/HowTos/SELinux  These tools are well worth learning but can be complicated. A quick test disabling selinux and firewalld can confirm that this is the source of problem and you can enable selinux and firewalld later and allow/open ports in a secure way.
Simple test: disable selinux and firewalld, e.g. on CentOS
systemctl stop firewalld;
setenforcing 0;

If you can create containers with selinux disabled then you have confirmed selinux is your problem. You can enable firewall and selinux and then add exceptions and open ports as needed later.
This looks good (specific to ubuntu but general enough IMHO), It details ufw commands, firewalld commands and iptables commands needed for opening ports to allow docker swarm to work) https://www.digitalocean.com/community/tutorials/how-to-configure-the-linux-firewall-for-docker-swarm-on-ubuntu-16-04
I originally got useful info on ufw commands to open ports needed from here:
Error response from daemon: attaching to network failed, make sure your network options are correct and check manager logs: context deadline exceeded
ufw allow 2376/tcp
ufw allow 2377/tcp
ufw allow 7946/tcp
ufw allow 7946/udp
ufw allow 4789/udp
ufw enable #maybe
ufw reload
systemctl restart docker

This is a common enough problem where something usually selinux is not allowing access to ports needed.
e.g.
https://github.com/google/cadvisor/issues/333


text:
Q: Jquery Ui tabs url problem with page base I have a problem with jqueryui tabs.
I have this code :
//The jQuery Tabs
$( "#tabs" ).tabs();

//Code to open the correct tab if i write the hash on the url. It works fine
var hash = window.location.hash;
var index = $("#tabs a").index($('#link-'+hash.replace('#','')));
if(index>=0) $("#tabs a").eq(index).click();

It works fine if I don't put in the page base href=... I can open the tab in new page with right button of the mouse and the page opens with the correct tab selected.
If I put in my page  base href=http://$_SERVER['HTTP_HOST']/ When I open the tab in new window with the right button of the mouse, the page opened is incorrect. Only get the base of page, lose the most of url.
Help please. Sorry for my english

A: I don't understand the

If I put in my page /" />

bit,
but the two last lines could already be reduced to one i think:
$('#link-'+hash.replace('#','')).click();


text:
Q: EMACS rebinding C-spc disable highlight of selected region EMACS 24.1.
I need to Rebind Ctrl-space to a custom function that:

*

*go to end of line

*delete trailing spaces if any

*set the Mark (as normal Ctrl-space)

This is my code not working:
(define-key global-map [?\C- ] 'my-set-mark-command)
(defun my-set-mark-command()
   (interactive)
   (end-of-line)
   (delete-char (* -1 (skip-chars-backward "\t\s")));;delete trailing spaces
   (set-mark-command nil))

When no trailing spaces it works normally: start to select and highlight the region.
When trailing spaces: it deletes trailing spaces, stop at end of line, set Mark but don't highlight the region.
If I remove the last command (set-mark-command) and I run it manually M-xset-mark-command it works.
Please can somebody help me to make this function works properly??

A: Modification commands cause the variable deactivate-mark to be reset, causing the mark to be lost. In the documentation for save-excursion it says how to disable that behavior, by binding the deactivate-mark variable with let. You can then change the code to:
(defun my-set-mark-command ()
   (interactive)
   (end-of-line)
   (let (deactivate-mark)
     (delete-char (* -1 (skip-chars-backward "\t\s"))))  ;;delete trailing spaces
   (set-mark-command nil))

or even include the whole let inside a save-excursion.
See manual:
http://www.gnu.org/software/emacs/manual/html_node/elisp/The-Mark.html#index-deactivate_002dmark-2801

A: Diego's explained what you want to know.  I just want to note that remapping
C-SPC is not a good idea.  C-SPC manipulates the mark ring,
which is extremely useful.  See manual, in particular see C-u C-SPC


text:
Q: Camera Initialization Failure in OpenCV In OpenCV—when initializing a VideoCapture object with a USB webcam—once every 2 or 3 runs the camera will fail to initialize. I have this incredibly ugly piece of code to fix that, but maybe somebody knows what can cause the camera init failure and how I can prevent it?
// Initialize video capture
camera_ = cv::VideoCapture(1);
camera_.set(CV_CAP_PROP_CONVERT_RGB , false);

camera_ >> frame_full_;
while (frame_full_.empty()){ // Could be !cap.isOpened
    cerr << "Camera failure." << endl;
    camera_.release();
    camera_ = cv::VideoCapture(1);
    camera_.set(CV_CAP_PROP_CONVERT_RGB , false);
    camera_ >> frame_full_;
}

/// Do something with the camera feed.

When I close my program, I do get Cleaned up camera. in the console, so I'm thinking it's being released properly.
Added information: On the runs in which the camera fails to init, the call to >>/.read() takes really long to return.
Edit: There is no difference between using the >> operator and .read(), as suggested by @4nonymou5.

A: If you meant, you need video feed out of camera and want to do some processing on the individual frames, the the following code might help you.
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std
int main(int argc, char *argv[])
{
  VideoCapture cap(1);
 if ( !cap.isOpened() )  // if not success, exit program
 {
     cout << "Cannot access camera" << endl;
     return -1;
 }
namedWindow("cam",1);
while(true)
        {
        Mat frame;
         bool check = cap.read(frame); // read a new frame from video

        if (!check) //if not success, break loop
         {
                    cout << "Cannot read the frame from video file" << endl;
                    break;
        }

// do what ever processing you want to do on frame

        imShow("cam", frame);
        waitKey(33);
    }
 return 0;
}

And for your code to respond,
add
camera_.read(frame_full_);

just before while loop, it would work.