text:
Q: How to tidy multiple column data sets in a better way I wanted to tidy the following data frame.
discipline applications_total applications_men applications_women awards_total awards_men awards_women
1   Chemical sciences                122               83                 39           32         22           10
2   Physical sciences                174              135                 39           35         26            9
3             Physics                 76               67                  9           20         18            2
4          Humanities                396              230                166           65         33           32
5  Technical sciences                251              189                 62           43         30           13
6   Interdisciplinary                183              105                 78           29         12           17
7 Earth/life sciences                282              156                126           56         38           18
8     Social sciences                834              425                409          112         65           47
9    Medical sciences                505              245                260           75         46           29
  success_rates_total success_rates_men success_rates_women
1                26.2              26.5                25.6
2                20.1              19.3                23.1
3                26.3              26.9                22.2
4                16.4              14.3                19.3
5                17.1              15.9                21.0
6                15.8              11.4                21.8
7                19.9              24.4                14.3
8                13.4              15.3                11.5
9                14.9              18.8                11.2

I come up with the following scripts (after several hours researching answers here)

library(dplyr)
library(tidyr)
library(stringr)
library(dslabs)

data("research_funding_rates")
research_funding_rates

#using gather

dat <- research_funding_rates %>%
  select(-applications_total,-awards_total, -success_rates_total) %>%
  gather(gender1, rate, starts_with("success_rates_")) %>%
  mutate(gender1 = str_sub(gender1,15)) %>%
  gather(gender2, applications, starts_with("applications_")) %>%
  mutate(gender2 = str_sub(gender2,14)) %>%
  gather(gender, awards, starts_with("awards_")) %>%
  mutate(gender = str_sub(gender,8)) %>%
  filter(gender1 == gender2 & gender1 == gender) %>%
  select(discipline, gender, applications, awards, rate)

#using pivot_longer

research_funding_rates %>%
  select(-applications_total,-awards_total, -success_rates_total) %>%
  pivot_longer(-discipline, names_to = "Name", values_to = "Count") %>%
  mutate(gender = ifelse(row_number() %% 2 == 1, "men","women") ) %>%
  mutate(Name = str_remove_all(Name,c("_men","_women"))) %>%
  group_by(Name) %>%
  spread(Name, Count, convert = TRUE) %>%
  arrange(gender)

I am trying to figure out if there is a more efficient way to do this task.

A: I found a more efficient script using gather.
research_funding_rates %>%
  select(-applications_total,-awards_total, -success_rates_total) %>%
  rename( rate_men = success_rates_men, rate_women = success_rates_women) %>%
  gather(key, value, -discipline) %>% #-discipline have to come last
  separate(key, c("type", "gender")) %>%
  spread(type, value)

separate() "knows" which string character to use. Using rename and separate should streamline the pivot_longer solution.


text:
Q: Jeditable edit multiple fields at once with single submit button I've so far been able to accomplish what's shown in this jsfiddle:
http://jsfiddle.net/Sk8erPeter/qjrJX/
I want there to only be a single submit button for the entire row to submit all values, whether they've been edited or not, and a single cancel button for the entire row as well.
For the sake of simplicity, let's assume my code is the exact same as the jsfiddle listed above.  Once I know how to accomplish it, I can modify my own code accordingly.
$(document).ready(function () {
$(".charcounter").editable("http://www.appelsiini.net/projects/jeditable/php/save.php", {
    indicator: "<img src='http://www.appelsiini.net/projects/jeditable/img/indicator.gif'>",
    type: "charcounter",
    submit: 'OK',
    tooltip: "Click to edit...",
    onblur: "ignore",
    charcounter: {
        characters: 60
    },
    event:'dblclick'
});

$('.edit_all_btns').click(function () {
    $(this).parent().siblings("td").find('.edit').dblclick();
});

});

A: I was having a equivalent issue.
This is what I did, Page Load I set a value var EnableSubmit = False;
On any Edit I set EnableSubmit = True, and Made a "Submit" button visible.
.makeEditable({
                    oEditableSettings:{event:'click'},
                    sUpdateURL:function(value,settings){
                        var RowID = oTable.fnGetPosition(this)[0];
                        var ColID = oTable.fnGetPosition(this)[2];
                        var sColumnTitle = oTable.fnSettings().aoColumns[ColID].sTitle;
                        return(UpdateCellData(RowID,sColumnTitle,value));
                    },
                    aoColumns:[
                        null,
                        null,
                        null,
                        {placeholder: ' ',cancel :'Cancel', submit:'OK',},   // Part Number (Allow Editing)
                        null,   // Quanity
                        null,   // UOM
                        null,   //  Date
                        {placeholder: ' ', cancel :'Cancel',  submit:'OK',},
                        {placeholder: ' ',cancel :'Cancel', submit:'OK',},
                        null    // Line Total
                        ]
                });

            function UpdateCellData(RowId,ColumnName,NewValue)
        {
            if(ColumnName!="")
            {
                var AutoChangeCheck = false;
                switch(ColumnName)
                {
                    case "Number":
                        AutoChangeCheck = true;
                        TableData.Info.Items[RowId].Number = NewValue;
                        break;
                    case "Date":
                        AutoChangeCheck = true;
                        TableData.Info.Items[RowId].DateInput = new Date(NewValue).toDateString();
                        break;
                    case "Price":
                        AutoChangeCheck = true;
                        TableData.Info.Items[RowId].Price = NewValue;
                        break;
                }
            }
            if(AutoChangeCheck)
            {
                // If Change is Valid show Change Request Button.
                var elem = document.getElementById('Request_Change');
                $(elem).show();
            }
            UpdateDataTable();
            return NewValue;
        }

This allows them to make all the changes to the whole table (and expanded tables if needed)
After they're all done, the button "Request_Change" is now visible.  And on Click I call
            function SendChageRequest()
        {
            // Send Change Request Query
            var elem = document.getElementById('Request_Change');
            $(elem).hide(); // Hide after Change Request Submitted so they don't double click.
                //console.log("Send Without Files");
                NameSpace.Content.ServerCalls.PushRequest(TableData.Info,OnCompleateChageRequest,OnError)
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring boot embedded tomcat listening but not responding When spring boot application is started with command "mvn spring-boot:run", tomcat server start listening at port 8080.

But when we access http://localhost:8080/index.html from browser tomcat will NOT respond.

Below is the POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test.des</groupId>
    <artifactId>trackerapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>trackerapp</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.15.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <version.commons-io>2.4</version.commons-io>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.7</java.version>
        <tomcat.version>7.0.90</tomcat.version>
        <start-class>com.test.des.trackerapp.trackerappApplication</start-class>
    </properties>

    <dependencies>
        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>
            </dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
        <!--WebJars -->
        <!-- <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId>
            </dependency> -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-ldap</artifactId>
            <!-- <version>2.0.8.RELEASE</version> -->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

The starter class is shown below.
package com.test.des.trackerapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@ComponentScan
@EnableJpaRepositories(basePackages = "com.test.des.trackerapp.repositories")
public class trackerappApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(trackerappApplication.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(trackerappApplication.class, args);
    }
}

The folder structure for static content are shown below.

Can anyone help me to find what is the problem ?
Thanks.

A: Tomcat is working as expected because you get a HTTP staus code 404  (Not Found).
But you don't have any static content or RestController that returns any content.
So you could go ahead and add a index.html to src/main/resources/static or add a RestController with path "/" and then you will see output.

A: I have found the issue. Its with server.contextPath property in application.properties.
It was set to server.contextPath=/trackerappApplication, changing this property to server.contextPath=/ will fix the issue.


text:
Q: Ignore json POJO fields not mapped in object in spring boot I have pojo which has many fields. I have set value some field. But when i create json, whole pojo create a json . here is the code i have used:

*

*Pojo
public class BasicInfoModel  {
  private String client_id="";
  private String father_name="";
  private String mother_name="";
  private String gendar="";
 //Getter and setter
 }

*Repository code
 public BasicInfoModel getBasicInfo() {
    BasicInfoModel lm = new BasicInfoModel();
    lm.setFather_name("Enamul Haque");
    return lm;
   }

*Controller code
  @RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
  public @ResponseBody BasicInfoModel getBasicinfo(){
   return repository.getBasicInfo();
  }

*But my json is resposne like bellow:
{
"client_id": "",
"father_name": "Enamul Haque",
"mother_name": "",
"gendar": ""
}

I have set value to father_name but i have seen that i have found all the value of pojo fields. I want get only set value of father_name and ignor other value which is not set in repository.

*My json look like bellow: I will display only father_name.how to display bellow like json from above code?
 {
 "father_name": "Enamul Haque"

 }

Please help me..

A: Json include non null values to ignore null fields when serializing a java class
@JsonInclude(Include.NON_NULL)

Jackson allows controlling this behavior at either the class level:
@JsonInclude(Include.NON_NULL)
public class BasicInfoModel { ... }

at the field level:
public class BasicInfoModel  {
   private String client_id="";

   @JsonInclude(Include.NON_NULL)
   private String father_name="";

   private String mother_name="";

   private String gendar="";

   //Getter and setter
}

from jackson 2.0 use here use
@JsonInclude(JsonInclude.Include.NON_NULL)

You can also ignore the empty values
@JsonInclude(JsonInclude.Include.NON_EMPTY)

A: Add the @JsonIgnoreProperties("fieldname") annotation to your POJO.
Or you can use @JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:
 @JsonIgnore
 @JsonProperty(value = "client_id")
 @RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
 public @ResponseBody BasicInfoModel getBasicinfo(){
  return repository.getBasicInfo();
 }

A: You can ignore field at class level by using @JsonIgnoreProperties annotation and specifying the fields by name:
@JsonIgnoreProperties(value = { "client_id" })
public class BasicInfoModel  {
      private String client_id="";
      private String father_name="";
      private String mother_name="";
      private String gendar="";
     //Getter and setter
     }

Or you can use @JsonIgnore annotation directly on the field.
public class BasicInfoModel  {
  @JsonIgnore
  private String client_id="";
  private String father_name="";
  private String mother_name="";
  private String gendar="";
 //Getter and setter
 }

You can read here more about this.


text:
Q: Eigenvectors complementary solution for system of linear differential equations Recently came across to solve system of linear differential equation with the matrix method, I have learnt that the eigenvectors forms part of the complementary function.
A matrix method such as :
$$ dy/dt = 5x+7y$$
$$ dx/dt =9x +4y $$
which then we replace a vector x $=(x,y)$ and a matrix M with entries (5 7,9 4)
Is there any reason for this (such as the one in ordinary Differential equation is due to the fact that the exponential is the eigenfunction if the differential which also exist as a matrix method, but why the eigenvectors in the front of it?)

A: Make a variable substitution. If you have a homogeneous linear system of ODEs $\dot{x} = Ax$, where $A$ has a basis of eigenvectors $v_1, \ldots, v_n$ and corresponding eigenvalues $\lambda_1, \ldots, \lambda_n$, then make a substitution in terms of a new vector variable $y$, the coordinate vector of $x$ with respect to $v_1, \ldots, v_n$. Then,
$$x = y_1 v_1 + \ldots + y_n v_n \implies \dot{x} = \dot{y}_1 v_1 + \ldots + \dot{y}_n v_n.$$
Hence, the system becomes,
\begin{align*}
\dot{x} &= Ax \\
\dot{y}_1 v_1 + \ldots + \dot{y}_n v_n &= A(y_1 v_1 + \ldots + y_n v_n) \\
&= y_1 Av_1 + \ldots + y_n A v_n \\
&= \lambda_1 y_1v_1 + \ldots + \lambda_ny_nv_n.
\end{align*}
By the linear independence of $v_1, \ldots, v_n$, we may equate the (non-constant, but still scalar) coefficients of $v_i$ to obtain
$$\dot{y}_i = \lambda_iy_i,$$
for each $i$. In other words, we have now decoupled the system into $n$ totally independent first order ODEs, in terms of the coordinates of $y$. These have the usual solutions:
$$y_i = A_ie^{\lambda_i t},$$
for some constant $A_i$. Thus, changing back,
$$x = y_1 v_1 + \ldots + y_n v_n = A_1 e^{\lambda_1 t} v_1 + \ldots + A_n e^{\lambda_n t} v_n.$$


text:
Q: how to receive from two serial port in interrupt The code below receives data from serial port of friendlyarm board.Signal handler is able to receve data if only one port is used.When i configured another port the signalhandler get executed on reception of data at two serial ports(SGIO signal is generated from both ports). What is the method of identifying the source of data so  that i can seperate the data from two ports correctly.
main()
{ Spo2fd=open("/dev/ttySAC1", O_RDWR | O_NOCTTY | O_NDELAY,0);
         if (Spo2fd == -1)
         {
            perror("open_port: Unable to open /dev/ttySAC3\n");
            exit(1);
         }

         sbio.sa_sigaction = &spo2signal_handler_IO;//sbio is a    structure of type sigaction
         sbio.sa_flags = SA_SIGINFO;//=0
         sbio.sa_restorer = NULL;

         sigaction(SIGIO,&sbio,NULL);

         fcntl(Spo2fd, F_SETFL, FNDELAY);
         fcntl(Spo2fd, F_SETOWN, getpid());
         fcntl(Spo2fd, F_SETFL,  O_ASYNC );

         cfsetispeed(&spo2term,B4800);
         cfsetospeed(&spo2term,B4800);
              spo2term.c_cflag &= ~PARENB;
              spo2term.c_cflag &= ~CSTOPB;
              spo2term.c_cflag &= ~CSIZE;
              spo2term.c_cflag |= CS8;
              spo2term.c_cflag |= (CLOCAL | CREAD);
              spo2term.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
              spo2term.c_iflag &= ~(IXON | IXOFF | IXANY);
              spo2term.c_oflag &= ~OPOST;
              tcsetattr(Spo2fd,TCSANOW,&spo2term);
              printf("spo2term configured....\n");

             tcflush(Spo2fd,TCIFLUSH); // Flush input buffer
             tcflush(Spo2fd,TCOFLUSH);  // Flush output buffer

 while(1)
 {

  // process the received data here.
 }

 }

signal handler
static void spo2signal_handler_IO (int sig, siginfo_t *siginfo, void *context)
{printf("\nspo2 data received\n");
unsigned int temp1;
unsigned int a=128,c;
//printf("\nSpo2");
res_spo2 = read(Spo2fd,&bufspo2,1);
//printf("\n%x",bufspo2);
temp1=bufspo2;
c=a&temp1;

if(c==128)
    spo2count=1;
if(spo2count==1)
    firstdataflag=true;
else if(spo2count==2)
    seconddataflag=true;
else if(spo2count==3)
    thirddataflag=true;
else if(spo2count==4)
    fourthdataflag=true;
else if(spo2count==5)
    fifthdataflag=true;
}


text:
Q: How to created a new object through nested routes in rails? So, following is the way I have defined the routes for my application:
Rails.application.routes.draw do
  resources :operators do
       resources :cabs
  end
end

As understood, my app has a few cab operators and each operator has a certain number of cabs associated with them:
class Operator < ActiveRecord::Base
    has_many :cabs
end

The problem comes when I am trying to create a new cab, as:
<%= link_to 'New Cab', new_operator_cab_path %>

The new cab creation form looks like this:
<%= form_for @cab, url: operator_cabs_path, method: :post do |f| %>
                  <% if @cab.errors.any? %>

<%= pluralize(@cab.errors.count, "error") %> prohibited this cab from being saved:

                      <% @cab.errors.full_messages.each do |message| %>

<%= message %>

                      <% end %>

                  <% end %>

                    <%= f.label :category %>

                    <%= f.text_field :category %>

                    <%= f.label :number %>

                    <%= f.text_field :number %>

                    <%= f.submit %>

                <% end %>

I had to explicitly define the url and the method in the form as the default url (cabs_path) wouldnt exist according to the way the routes have been defined.
Though my links are working fine, but no new cab gets created. Following is my cabs_controller:
class CabsController < ApplicationController
  before_action :set_cab, only: [:show, :edit, :update, :destroy]

  # GET /cabs
  # GET /cabs.json
  def index
    @cabs = Operator.find(params[:operator_id]).cabs
  end

  # GET /cabs/1
  # GET /cabs/1.json
  def show
  end

  # GET /cabs/new
  def new
    @cab = Cab.new
    @operator = Operator.find(params[:operator_id])
  end

  # GET /cabs/1/edit
  def edit
    @operators = Operator.all
  end

  # POST /cabs
  # POST /cabs.json
  def create
    @cab = Cab.new(cab_params)

    respond_to do |format|
      if @cab.save
        format.html { redirect_to operator_cabs_path, notice: 'Cab was successfully created.' }
        format.json { render :show, status: :created, location: @cab }
      else
        format.html { render :new }
        format.json { render json: @cab.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /cabs/1
  # PATCH/PUT /cabs/1.json
  def update
    respond_to do |format|
      if @cab.update(cab_params)
        format.html { redirect_to operator_cabs_path(operator_id: @operator.id), notice: 'Cab was successfully updated.' }
        format.json { render :show, status: :ok, location: @cab }
      else
        format.html { render :edit }
        format.json { render json: @cab.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /cabs/1
  # DELETE /cabs/1.json
  def destroy
    @cab.destroy
    respond_to do |format|
      format.html { redirect_to operator_cabs_path(operator_id: @operator.id), notice: 'Cab was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_cab
      @cab = Cab.find(params[:id])
      @operator = Operator.find(params[:operator_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def cab_params
      params.require(:cab).permit(:category, :number)
    end
end

A: A few questions and pointers:

*

*Does your Cab model include belongs_to :operator, as well as an operator_id column of type integer?

*Your new_operator_cab_path needs to be told which operator the cab belongs to, like this: new_operator_cab_path(@operator).

*The same problem as above exists in your form URL: @cab, url: operator_cabs_path. In this case, you can simply fix it by replacing it with [@cab.operator, @cab], which Rails will translate to the appropriate URL.

*Since this is a nested resource, you'll want to build your new cabs a little differently. Instead of Cab.new in your new and create actions, you'll want to use Operator.find(params[:operator_id]).cabs.build. This will specifically build a cab belonging to your operator.

Here are some related resources you may find useful:

*

*Rails Association Basics

*Rails Routing: Creating Paths and URLs from Objects


text:
Q: The issue with using images as vertices in igraph R I'm trying to set images to vertices by their attribute (type), using this code:
library(igraph)
library(png)

gi <- graph.formula(child -- org -- person)

img1 <- readPNG("baby-boy.png")
img2 <- readPNG("knife.png")
img3 <- readPNG("detective.png")

V(gi)$raster <- ni$type
V(gi)$raster <- gsub("child", "img1", V(gi)$raster)
V(gi)$raster <- gsub("org", "img2", V(gi)$raster)
V(gi)$raster <- gsub("person", "img3", V(gi)$raster)

plot(gi, layout_as_star(gi),
 vertex.label.cex = 0.5,
 edge.arrow.size = 0.1,
 vertex.shape="raster",
 vertex.size = 16,
 vertex.size2 = 16)

As a result I get the following error message:
"Error in rasterImage(ras, coords[i, 1] - size[i], coords[i, 2] - size2[i],  :
invalid color name 'img1'"

and no vertices are plotted.
How could I solve this problem?

A: You seem to be treating V(gi)$raster as a list of the names of images.  It is supposed to contain the actual rasters. Here is a small example. In order to get the list
library(igraph)
library(png)

set.seed(1234)
g = erdos.renyi.game(4, 0.5)

## Sorry. This part is not reproducible.
## You will need to get your own images.
img1 = readPNG("006.png")
img2 = readPNG("040.png")
img3 = readPNG("068.png")
img4 = readPNG("104.png")

V(g)$raster = replicate(vcount(g), img1, simplify=FALSE)
V(g)$raster[[2]] = img2
V(g)$raster[[3]] = img3
V(g)$raster[[4]] = img4

plot(g, vertex.shape="raster", vertex.label=NA)


text:
Q: power of a fraction I am having trouble understanding where the numbers are coming from in this question.
John and Melissa wonder about the potential increase in the value of their house. Assuming a 6% appreciation per year, the formula for the value of the house after  years is
, where  starts from 0.

*

*Where did the 53 over 50 come from?

*Why couldn't I just calculate 6% of 219,000 for 13,140$ a year and multiply by 3 and add that to the original value?

*53\50 is in parenthesis so I should divide that first? then apply the power of 3?

A: 1) $$\dfrac{53}{50}=1.06=\text{6% increase or 106% of the corrent value}$$
2) It is because for example, at $n=2$, the function calculates $6$% OF THE CURRENT VALUE, not the first value, $219000$. Eg at $n=2,$ it would increase by $6$%, to $\$232776$, then increase $6$% FROM $\$232776$ to $232776\times 1.06$
3) It does not matter,$$ \left( \frac{53^n}{50^n}\right)=(1.06)^n$$


text:
Q: Blurry SVGs in Firefox My SVG graphics are not rendering crisply in Firefox.  For example, the following should produce a 14px x 14px square with a 2px stroke width:
<svg width='14' height='14'><rect x='1' y='1' width='12' height='12' stroke='black' stroke-width='2' fill='transparent'/></svg>

Firefox usually produces a square with antialiased edges.  This can be seen in the following jsfiddle.  In fact, when I resize the browser window, the fuzziness changes: sometimes it appears crisp and sometimes it gets fuzzy.
http://jsfiddle.net/auq8x3ce/
Chrome and Safari draw the SVGs fine.  I've only seen this happen in Firefox.  Any help would be appreciated.


text:
Q: How to iterate on different lists according to a parameter I have a script that can get a list of folders or get them automatically with find. I'd like to write a single loop that handles both cases: if there are parameters, use them, otherwise, create the list automatically.
So far, I have something like:
if [ "$#" -gt 0 ]
then
    for value in "$@"
    do
        v1=$(process_data "$value")
        <do things with $v1>
    done
else
    for value in "$(find ...)"
    do
        v1=$(process_data "$value")
        <do things with $v1>
    done
fi

I'd like to do something like:
if [ "$#" -gt 0 ]
then
    data="$@"
else
    data="$(find ...)"
fi

for value in "${data[@]}"
do
    v1=$(process_data "$value")
    <do things with $v1>
done

but this data assignment can be potentially big. In a language with pointers this should not be a problem, but in bash it doesn't look good.
Is there a better way to achieve my needs?

A: These don't look right:

data="$@"
data="$(find ...)"

If you want data to be an array, you need
data=("$@")
data=($(find ...))

What you can do is assign to the positional parameters:
#!/bin/bash

if [ "$#" = 0 ]
then
    # no arguments; default to all matching files
    set -- $(find ...)
fi

for value in "$@"
do
    # things
done

This does mean that the loop can't start until the find command finishes.  To solve that, an alternative might be to turn it around and make using "$@" more like the output of find, i.e. stream it to a pipe, like this:
#!/bin/bash

args_or_find() {
    if [ "$#" -gt 0 ]
    then
        printf '%s\n' "$@"
    else
        find ...
    fi
}

while read -r value
do
    # things
done < <(args_or_find)

The natural extension to improve robustness using \0 instead of \n as separator is left as an exercise.

A: You may use a script like this to have processing loop only once:
if (($#)); then           # arguments are passed
    arr=("$@")
else                      # build array from find command's result
    arr=()
    while IFS= read -rd '' f; do
        arr+=("$f")
    done < <(find . -name '*.txt' -print0)
fi

# main processing loop
for line in "${arr[@]}"; do
    echo "processing... <$line>"
done


text:
Q: Test Axios get request in React and Jest I'm new to React testing and was essentially wondering how to mock the behaviour of a successful get request from Axios.
Any help would be greatly appreciated, if you need me to provide more info please let me know (I've only posted the relevant code). Alternatively if anyone knows of any useful links to React testing with Axios that would also be appreciated! :)
the test
it("Submit button should make a fetch request return a given Github user.", () => {
    render(<FavouriteLanguage />);
    let mock = new MockAdapter(axios);
    userEvent.click(screen.getByText("Submit"));
    const searchGithubUsers = mock.onGet(
        `https://api.github.com/users/thatguy560/repos?per_page=100`,
        { language: "JavaScript" }
    );
    expect(searchGithubUsers).toHaveBeenCalled();
});

Code
import { Component } from "react";
import axios from "axios";
import sortKeysByValue from "sort-keys-by-value";
import Swal from "sweetalert2";
import "./css/FavouriteLanguage.css";

class FavouriteLanguage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchedUsername: "",
            programmingLanguagesUsed: "",
        };
    }

    searchGithubUsers = (event) => {
        this.setState({ searchedUsername: event.target.value });
    };

    getData = () => {
        let username = this.state.searchedUsername;
        axios
        .get(`https://api.github.com/users/${username}/repos?per_page=100`)
        .then((res) => {
            let allProgrammingLanguages = res.data
            .map((data) => data.language)
            .filter((lang) => lang !== null);
            this.setState({ programmingLanguagesUsed: allProgrammingLanguages });
            Swal.fire({
                title: `${
                    username[0].toUpperCase() + username.slice(1).toLowerCase()
                }'s Favourite Programming Language Is:`,
                text: `${this.determineFavouriteLanguage()}`,
                width: 625,
            });
        })
        .catch((error) => {
            Swal.fire({
                title: `${this.DisplayErrorInfo(error)}`,
                icon: "error",
            });
        });
    };

    render() {
        return (

Find a user's favourite programming language

Please enter a valid Github username:

                        <form onSubmit={this.getData}>
                            <input
                                type="text"
                                placeholder="Github username..."
                                onChange={this.searchGithubUsers}
                            />
                        </form>
                        <button
                            id="Submit"
                            type="button"
                            className="btn"
                            onClick={this.getData}
                        >
                            Submit
                        </button>

        );
    }
}

export default FavouriteLanguage;

Error
Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {"abortRequest": [Function abortRequest], "abortRequestOnce": [Function abortRequestOnce], "networkError": [Function networkError], "networkErrorOnce": [Function networkErrorOnce], "passThrough": [Function passThrough], "reply": [Function reply], "replyOnce": [Function replyOnce], "timeout": [Function timeout], "timeoutOnce": [Function timeoutOnce]}

A: You're on right track! I'd recommend moving your MockAdapter into its own file (for reusability):
utils/mockAxios.js
import MockAdapter from "axios-mock-adapter";
import axios from "axios";

const mockAxios = new MockAdapter(axios);

export default mockAxios;

Then you can import it, add some mocks to it (you can chain axios responses with replyOnce and/or reply to test both failing/successful API responses, see chaining is also supported), and then make assertions against the result (in this case, spy on Swal.fire and make assertions on how its being called):
__tests__/FavouriteLanguage.js
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Swal from "sweetalert2";
import FavouriteLanguage from "./FavouriteLanguage";
import mockAxios from "./utils/mockAxios";

// spying on Swal.fire, turning into a "spy" mocked function
const mockSpy = jest.spyOn(Swal, "fire");

const username = "example";
const API_URL = `https://api.github.com/users/${username}/repos?per_page=100`;

// chaining axios responses...
mockAxios
  .onGet(API_URL)
  .replyOnce(404) // at first, it fails to fetch
  .onGet(API_URL)
  .reply(200, [{ language: "Javascript" }]); // then it successfully returns an array of objects, where each object refers to the user's projects; in this simple example, I'm just returning a single project

beforeEach(() => {
  mockSpy.mockClear(); // clear any previous calls to this spy mock
});

afterAll(() => {
  mockSpy.mockRestore(); // restore spy mock to original Swal.fire
});

it("fails to make an API request to retrieve a github user and displays a sweet alert error", async () => {
  render(<FavouriteLanguage />);

  // updates input with "example" username
  userEvent.type(screen.getByTestId("username"), username);

  // submits the form
  userEvent.click(screen.getByTestId("submit"));

  // using "waitFor" because submitting the form calls an async request
  // therefore you need to "waitFor" the request to resolve
  await waitFor(() => {
    // expect Swal.fire to be called with an error
    expect(Swal.fire).toHaveBeenCalledWith({
      title: "Error: Request failed with status code 404",
      icon: "error",
    });
  });
});

it("makes an API request to retrieve a github user's details and displays a sweet alert with user's favorite language.", async () => {
  render(<FavouriteLanguage />);

  userEvent.type(screen.getByTestId("username"), username);

  userEvent.click(screen.getByTestId("submit"));

  await waitFor(() => {
    // expect Swal.fire to be called with user's favorite language
    expect(Swal.fire).toHaveBeenCalledWith({
      text: "Javascript",
      title: "Example's Favourite Programming Language Is:",
      width: 625,
    });
  });
});

I tweaked your code a bit to make the above work, but you can retweak it to work with your code:
FavouriteLanguage.js
import { Component } from "react";
import axios from "axios";
// import sortKeysByValue from "sort-keys-by-value";
import Swal from "sweetalert2";
// import "./css/FavouriteLanguage.css";

class FavouriteLanguage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchedUsername: "",
      programmingLanguagesUsed: "",
    };
  }

  searchGithubUsers = (event) => {
    this.setState({ searchedUsername: event.target.value });
  };

  getData = (e) => {
    e.preventDefault(); // make sure to call e.preventDefault when submitting a form; otherwise, it'll refresh the page

    const username = this.state.searchedUsername;
    axios
      .get(`https://api.github.com/users/${username}/repos?per_page=100`)
      .then((res) => {
        let allProgrammingLanguages = res.data
          .map((data) => data.language)
          .filter((lang) => lang !== null);

        this.setState({ programmingLanguagesUsed: allProgrammingLanguages });

        Swal.fire({
          title: `${
            username[0].toUpperCase() + username.slice(1).toLowerCase()
          }'s Favourite Programming Language Is:`,
          text: `${res.data[0].language}`,
          width: 625,
        });
      })
      .catch((error) => {
        Swal.fire({
          title: `${error.toString()}`,
          icon: "error",
        });
      });
  };

  render() {
    return (

Find a user's favourite programming language

Please enter a valid Github username:

            <form onSubmit={this.getData}>
              <input
                data-testid="username"
                type="text"
                placeholder="Github username..."
                onChange={this.searchGithubUsers}
              />

              {/*
                 Since you're already using a form,
                 put the button inside of it and use type="submit".
                 Clicking the "submit" button calls "this.getData"!
               */}
              <button data-testid="submit" type="submit" className="btn">
                Submit
              </button>
            </form>

    );
  }
}

export default FavouriteLanguage;

Result:


text:
Q: How to put Admob ads on a unity Game? I have uploaded my game to the play store but haven't put ads yet its my first time and i am encountering many issues i am following many issues in this , Every time there is a new issue some time is says "Gradle failed to fetch dependencies" , sometimes a loading bar comes with heading "Resolving android Dependencies" and never goes and does not show any progress, and if i do the coding the games doesn't builds , can some one please help me throughout the process like what plugins I have to installs , Google play services , ads manager services all i am confused.

A: Unity3D is a game engine that dedicated to software program to make games. It has features like 3d modelling, physics, camera. etc.
If you're going to use Visual Studio as your editor to develop a game using Unity3D, you can debug your code with MonoDevelop or use a third-party plug-in, UnityVS.
Based from here:

You can't use Visual Studio as a debugger without UnityVS because when
  you debug your game, you aren't debugging Unity.exe, you're debugging
  a virtual environment inside of Unity, using a soft debugger that's
  issued commands and performs actions.

With UnityVS, you connect the Visual Studio back to Unity instead.
On the other hand, android studio is dedicated for android development. You can follow the starter for Google Mobile Ads SDk for Unity.
See for more details:

*

*Android Development Setup

*Gradle Troubleshooting


text:
Q: variadic templates - compile error Could you help me in fixing the compile error in the following code:
#include <sstream>
#include <iostream>

using namespace std;

template<typename T, typename ...P>
class Mystrcat{
 public:
 Mystrcat(T t, P... p){init(t,p...);}

 ostringstream & get(){return o;}

 private:
 ostringstream o;
 void init(){}
 void init(T t, P... p);
};

template<typename T, typename ...P>
void Mystrcat<T,P...>::init(T t, P ...p){
  o << t;
  if (sizeof...(p)) init(p...);
}

int main(){
 Mystrcat<char*,char *> m("Amma","Namasivayah");
 cout << m.get().str();
}

I get the error, no matching function for call to
'Mystrcat<char*, char*>::init(char*&)'

note: candidates are:
void Mystrcat<T, P>::init() [with T = char*, P = char*]
void Mystrcat<T, P>::init(T, P ...) [with T = char*, P = char*]

gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
Thanks
suresh

A: You're getting this error because there isn't a way to unpack your p into either init function.  In your instantiation Mystrcat<char*, char *>, unpacking a P... will yield a single thing in the type: char*, which doesn't have an init with that signature (the instantiated version will have a void init() and void init(char*, char*), whereas you are trying to call init(char*)).
In fact, your template is impossible to instantiate, since init will always take one more argument than you give it in void Mystrcat<T,P...>::init(T t, P ...p).  If you change the definition to call what you have defined:
template<typename T, typename ...P>
void Mystrcat<T,P...>::init(T t, P ...p){
  o << t;
  if (sizeof...(p)) init(t, p...);
}

then this will work (at least in g++-4.5.2).

EDIT: I think this is what you're actually looking for:
#include <sstream>
#include <iostream>

class MyCollector
{
public:
    template <typename... T>
    explicit MyCollector(const T&... args)
    {
        init(args...);
    }

    std::string str()
    {
        return _stream.str();
    }

private:
    void init()
    { }

    template <typename First, typename... Rest>
    void init(const First& first, const Rest&... rest)
    {
        _stream << first;
        init(rest...);
    }

    std::ostringstream _stream;
};

int main()
{
    MyCollector collector("Whatever ", "stuff like ", 2, " or ", 3.14, "\n");
    std::cout << collector.str();
    return 0;
}


text:
Q: Second Cell appearing only after first cell is selected in Tableview ios When I run my ios app, only the first cell displays in the TableView, then when clicked the second cell displays. I would like them both to display at the same time, but I cannot figure out this behavior.
Here is the code for my view did load
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"ProductCellId";

    ProductTableCell *cell =
        (ProductTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"ProductTableCell" owner:self options:nil];
        cell = self.productCell;
    }

    Product *product = [products objectAtIndex:indexPath.row];
    [cell configureForProduct:product];

    return cell;
}

Any help would be much appreciated!

A: Since you are loading your cell from Interface builder try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:   (NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ProductTableCell"];
        if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ProductTableCell" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
    }

Product *product = [products objectAtIndex:indexPath.row];
[cell configureForProduct:product];

    return cell;
}

Change this:
static NSString *CellIdentifier = @"ProductCellId";

to:
static NSString *CellIdentifier = @"ProductTableCell";

You can find additional information for what you are trying to do in this question: Load cells from XIB files


text:
Q: OBIEE Error: [46137] CSF error encountered. Error code:43131 I have install Oracle Business Intelligence 12c on Redhat Linux 7.0 using Oracle 12 C database. Three servers are failing to run or start and these are obips1, Obisch1, obis1. In the logs are receiving error [46137] CSF error encountered. Error code:43131.
How can I resolve this problem. I have checked user oracle accounts and are  showing that they are ok. Please help. How can I resolve this problem?

A: I had your problem when I used for the RCU a 12.2.0.1 Oracle database, there seems to be a bug in that version and Oracle support recommended using a 12.1.0.2.0 Database.
Regards


text:
Q: How to set different forecolor to single label? lblOperationType.Text = "Text";
Label l1 = new Label();
int len = lblOperationType.Text.Length - 1;
string b = Convert.ToString(lblOperationType.Text.ToCharArray()[0]);
string a = lblOperationType.Text.Substring(1, len);
l1.Text = (b);
l1.ForeColor = Color.Red;
lblOperationType.Text = l1.Text + a;

Is this correct code? I have to make a single label Text like 1st Letter should be red in color.

A: No, in general (i.e. without custom rendering yourself) a label only has a single foreground colour. Assuming this is Windows Forms, it sounds like you might want a RichTextBox instead - that allows multiple colours, fonts etc within a single control.
As an example:
using System;
using System.Drawing;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        var rtb = new RichTextBox {
            Text = "Test",
            ReadOnly = true
        };
        rtb.Select(1, 3);
        rtb.SelectionColor = Color.Red;
        rtb.DeselectAll();
        var form = new Form { Controls = { rtb } };
        Application.Run(form);
    }
}

That's not terribly nice code - it would be better to set the Rtf property directly, with the control codes necessary to set the colour, but I'm having a tricky time getting the exact format of the RTF right.


text:
Q: Extract xml from api.hostip.info. Minidom works on local GAE but not Google GAE Trying to upload xml latitude, longitude coordinates from api.hostip.info. Python minidom works fine in local GAE (and iPython) but does not work in Google GAE. I can throw the code below but I think I'm missing something specific to Google GAE in extracting xml from another website.
ip = self.request.remote_addr
IP_URL = "http://api.hostip.info/?="
def get_coords(ip):
    url = IP_URL + ip
    xml = None
    try:
        xml = urllib2.urlopen(url).read()
    except urllib2.URLError, e:
        return "in URLError "+ e.code
    try:
        if xml:
            s = minidom.parseString(xml)
        else:
            return "unable to parse content"
    except:
        return "exception error unable to parse content"
    try:
        if s:
            coords = s.getElementsByTagName("gml:coordinates")
        else:
            return "unable to get coords"
    except:
        return "exception error unable to get coords"
    try:
        if coords:  #Google GAE fails on this if statement
            p = coords[0].childNodes[0].nodeValue
        else:
            return "unable to get node value- points"
    except:
        return "exception unable to get node-value points"
    try:
        lon, lat = coords[0].childNodes[0].nodeValue.split(',')
        points = [Point(lat,lon)]
        return points
    except:
        return "unable to return points"
    return None + "dropped to bottom"

A: Problem solved. api.hostip.info not generating location based on sent IP address except on a one or two time basis. ap.host.info ignores IP address given and then defaults to ip location of sender. I used a different IP geolocator api and it worked fine


text:
Q: Formatting time in Python? How would I go about formatting time in Python?
Lets say I have
time = 9.122491

The time is in hours and I need to convert it to h:m format. So the desired output should be:
9:07

Any help would be greatly appreciated!

A: Using the datetime module:
>>> from datetime import datetime, timedelta
>>> mytime = 9.122491
>>> temp = timedelta(hours=mytime)
>>> print((datetime(1, 1, 1) + temp).strftime('%H:%M'))
09:07

A: If you don't want to use a module, you can do it fairly simply like this:
>>> t = 9.122491
>>> print '%d:%02d' % ( int(t), t%int(t)*60 )
9:07

%02d formats numbers to have leading zeros if they're less then 2 digits long
t%int(t) effectively gets rid of whole digits (11.111 becomes .111), then *60 converts the decimal fraction to minutes


text:
Q: C# Keep track of the amount of written bytes I was looking into writing data and I used:
System.IO.File.WriteAllBytes(path, GetBytes());

This worked for me but then I wanted to get the progress of the written bytes so I can have a progressbar added to it. I found out that my method can't connect to a progressbar so I decided to use this:
using (BinaryWriter writer = new BinaryWriter(System.IO.File.Open(path, FileMode.Create))) {
            byte[] nextBytes = GetBytes(); // your logic to get what to write;
            writer.Write(nextBytes);
        }

This writes my file succesfully but after a lot of searching (maybe not enough) I can't seem to find out how to keep track of the amount of bytes being written until it's complete. Maybe I'm using a wrong method, if anyone could help me out, would be awesome! (I use a WPF)
Thanks in advance,
Update:
On top of the project I delcare BackgroundWorker()
    BackgroundWorker bw;

Then when I start the download I haev this:
bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

            bw.RunWorkerAsync(data);

My doWork method:
        private void bw_DoWork (object sender, DoWorkEventArgs e) {
        downloadData data = (downloadData) e.Argument;
        _source = data.DownloadLocation + @"\";

        sem.WaitOne();

        //enters
        updateStatusBar("- Downloading -", data, 0);
        Video vid = youtube.GetVideo(data.Url);
        byte[] bytes = vid.GetBytes();

        using (var writer = new BinaryWriter(System.IO.File.Open(_source + vid.FullName, FileMode.Create))) {

            // do your read logic here and read into bytes

            var bytesLeft = bytes.Length;
            var bytesWritten = 0;
            while (bytesLeft > 0) {
                int chunk = Math.Min(64, bytesLeft);

                writer.Write(bytes, bytesWritten, chunk);
                bytesWritten += chunk;
                bytesLeft -= chunk;

                // calculate progress bar status
                bw.ReportProgress(bytesWritten * 100 / bytes.Length, data);
            }
        }
        // Leaves
        updateStatusBar("- Done -", data, 100);

        sem.Release();
    }

My Progresschanged method:
    private void bw_ProgressChanged (object sender, ProgressChangedEventArgs e) {
        YoutubeData data = (YoutubeData) e.UserState;
        updateStatusBar("Downloading: " + e.ProgressPercentage, data, e.ProgressPercentage);
    }

Method for updating status bar:
        private void updateStatusBar(string txt, downloadData data, int progress) {
        _downloadData.Remove(data);
        data.ProgressText = txt;
        data.Status = progress;
        _downloadData.Add(data);

        Dispatcher.Invoke(new Action(() => {
            lv_DownloadData.ItemsSource = null;
            lv_DownloadData.ItemsSource = _youtubeData;
        }));
    }

But now it freezes my WPF.

A: Write bytes in chunks and use a BackgroundWorker
    using(var writer = new BinaryWriter(System.IO.File.Open(path, FileMode.Create)))) {

       // do your read logic here and read into bytes

        var bytesLeft = bytes.Length;
        var bytesWritten = 0;
        while(bytesLeft > 0) {
            int chunk = Math.Min(64, bytesLeft);
            writer.WriteBytes(array, bytesWritten, chunk);
            bytesWritten += chunk;
            bytesLeft -= chunk;

            // calculate progress bar status
            backgroundWorker.ReportProgress(bytesWritten * 100 / array.Length);
        }
    }

Update
OK, this is purely untested.. but stay we me..
Each BinaryWriterwill do its work on a BackgroundWorker
so you set up the background worker
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

Then you need to start the BackgroundWorker somewhere using bw.RunWorkerAsync()
void bw_DoWork(object sender, DoWorkEventArgs e)
{
    // Do your task here

     // report its progress
    bw.ReportProgress(..);
}

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // update your progress bar here

}


text:
Q: Cast a (void const *x) to a (unsigned char const *y) I'm going through a source code analyzing its implementations where I have a method defined :
unsigned int rs_calc_weak_sum(void const *p, int len) {
unsigned char const    *buf = (unsigned char const *) p;
}

What type of parameter should be passed into this method??
please help me.
thanks.

A: Any pointer can be passed to a void * parameter.   What 'should' be passed, depends on what the code does with that parameter.
char array[12] = "Hello World";
unsigned in res = 0;
res = rs_calc_weak_sum(array, 12);

#include <stdio.h>
int main ( void )
{
  char filename[] = "file.txt";
  FILE *file = fopen ( filename, "r" );

  if (file != NULL) {
    char line [1000];
    while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
      res = rs_calc_weak_sum(line, 1000);
    }

    fclose(file);
  }
  else {
    perror(filename); //print the error message on stderr.
  }

  return 0;
}


text:
Q: Cloud firestore: get() always timesout in a python create trigger I have a straightforward Cloud Firestore "on-create" trigger that needs to query another collection. But, the get() for a document within that collection always times out. The collection being queried is empty and the only thing in the logs is a "timeout".
This works outside by itself.
Maybe it has something to do with the way the "db" client is being initialized?

import firebase_admin
from firebase_admin import firestore

firebase_admin.initialize_app()

def on_insert(data, context):
    print("fields:", data["value"]["fields"])
    workgroup_id, namespace_id = None, None
    try:
        workgroup_id = data["value"]["fields"]["workgroup_id"]["stringValue"]
        namespace_id = data["value"]["fields"]["namespace_id"]["stringValue"]
    except KeyError:
        print("!!Ignoring trigger with unexpected workgroup_id/namespace_id values")
        return
    print (f"workgroup_id: {workgroup_id}, namespace_id: {namespace_id}")
    db = firestore.client()
    print("getting ref")
    ref = db.collection(u"ExtendedAttributesCounter").document(workgroup_id)
    print("before get()")
    # gets stuck here
    doc = ref.get()
    print("exists", doc.exists)

A: The issue turned out to be that the service account @appspot.gserviceaccount.com was disabled.
Interestingly, a NodeJS trigger (with the same functionality) gave a more detailed error message that pointed to an authentication error. Python function logs just noted a timeout.


text:
Q: Points multiplication of elliptic curve Let an elliptic curve $ E(a,b )$ $$E(a,b ) = \{(x,y)\,|\,y^2=x^3+ax + b\}$$
Where the points of the line $xm + n$:
$$P =(x_1, y_1),\,  Q =(x_2, y_2),\,   R =(x_3, y_3) \in E(a, b)$$

How can you calculate the product between them? $$Q\cdot P =\, ?$$

A: Say we have the line $(x_0+ct,y_0+dt)$ which intersects the curve in 3 points : at $t=-1,t=1$ and $t= ?$
Finding $?$ means solving the 3rd root of the cubic polynomial
$$P(t) = (y_0+td)^2- (x_0+tc)^3-a(x_0+tc)-b$$
And obtain the factorization
$$P(t) = -c^3 (t+1) (t-1)(t-?)$$
Therefore
$$? = \frac{P(0)}{c^3}=\frac{y_0^2-x_0^3-ax_0-b}{c^3}$$
From which we obtain the group law
$$(x_0-c,y_0-d)+(x_0+c,y_0+d) = (x_0+\frac{y_0^2-x_0^3-ax_0-b}{c^2}, -y_0-d\frac{y_0^2-x_0^3-ax_0-b}{c^3})$$


text:
Q: Generating Pop-up Help on input I am working on a form and I am trying to generate help pop-up in case a user poorly fill an input field. Knowing fields have their own RegEx to control their validity, I want to generate the pop-up when the user click on its specific help-button.
I tried with a loop but I still have the uncaught error. I thought it was due to the querySelector, but even with a getElementById my function. Am I using the good way to create this event or maybe is there any method to link locally two HTML elements, I mean two elements inside the same div?
cart.js:172 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at HTMLButtonElement.<anonymous> (cart.js:172)

This is my JS:
let z = document.querySelectorAll(".help-popup");
    for(let i = 0; i < z.length; i++) {
        let getHelpPopUp = document.getElementById(`help-icon-${i}`);
        getHelpPopUp.addEventListener("click", (event) => {
            event.preventDefault();

            let reachPopup = document.getElementById(`popup-${i}`);
            reachPopup.classList.toggle("show-popup");
            })
    }

HTML :

    Nom :

    <input class="input-entry letter-input" id="input-nom" name="nom" type="text" required>
     Pour ce champs veillez à n'utilisez que des lettres

    Prénom :

    <input class="input-entry letter-input" id="input-prenom" name="prenom" type="text" required>
     Pour ce champs veillez à n'utilisez que des lettres

CSS :
    .help-icon{
    font-size: 14px;
    position: relative;
    grid-area: help;
    cursor: pointer;
}

.help-popup{
    grid-area: popup;
    border: solid;
    position: absolute;
    left: 50%;
    z-index: 2;
    background-color: #555;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 0 5px;
    visibility: hidden;
    margin-left: 10px;
    max-height: 2em;
    width: max-content;
}

.help-popup::after {
    position: absolute;
    content: "";
    right: 100%;
    border-style: solid;
    border-width: 10px;
    top: 10%;
    border-color: transparent #555 transparent transparent;
}

.show-popup{
    visibility: visible;
    animation: fadeIn 1s;
}

/*Animation Popup*/
@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
  }

A: You're using the i of the for loop to construct your css selector help-icon-${i}. The i starts from zero and help-icon-0 doesn't exists. That's why it can't read addEventListener from null because getHelpPopUp is null because it couldn't be found.
Try changing your loop to this, so it will start from 1:
 for(let i = 1; i <= z.length; i++) {

Edit:
There also seems to be an extra qoute in your HTML ".
<i id=""help-icon-2" it should be <i id="help-icon-2"
How it looks after the changes and the CSS you added later
Gif example
JSFiddle

A: Your code is looking for numbers staring at zero and not one. You also have an extra quote which messes up the attributes and it can not find the elements.

let z = document.querySelectorAll(".help-popup");
for (let i = 0; i < z.length; i++) {
  console.log(`help-icon-${i+1}`)
  let getHelpPopUp = document.getElementById(`help-icon-${i+1}`);
  getHelpPopUp.addEventListener("click", (event) => {
    event.preventDefault();
    let reachPopup = document.getElementById(`popup-${i+1}`);
    reachPopup.classList.toggle("show-popup");
  })
}
.help-icon {
  font-size: 14px;
  position: relative;
  grid-area: help;
  cursor: pointer;
}

.help-popup {
  grid-area: popup;
  border: solid;
  position: absolute;
  left: 50%;
  z-index: 2;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 0 5px;
  visibility: hidden;
  margin-left: 10px;
  max-height: 2em;
  width: max-content;
}

.help-popup::after {
  position: absolute;
  content: "";
  right: 100%;
  border-style: solid;
  border-width: 10px;
  top: 10%;
  border-color: transparent #555 transparent transparent;
}

.show-popup {
  visibility: visible;
  animation: fadeIn 1s;
}

/*Animation Popup*/

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />

  Nom :

  <input class="input-entry letter-input" id="input-nom" name="nom" type="text" required>
   Pour ce champs veillez à n'utilisez que des lettres

  Prénom :

    <input class="input-entry letter-input" id="input-prenom " name="prenom" type="text " required>
     Pour ce champs veillez à n'utilisez que des lettres

Personally I would avoid all the looping and not add a bunch of event listeners. I would use event delegation and check to see if the help icon was clicked. If it was look for the pop up in that parent.

document.querySelector(".wrapper").addEventListener("click", function (evt) {
  const help = evt.target.closest('.help-icon');
  if (help) {
    help.closest('.label-container').querySelector('.help-popup').classList.toggle('show-popup');
  }
});
.help-icon {
  font-size: 14px;
  position: relative;
  grid-area: help;
  cursor: pointer;
}

.help-popup {
  grid-area: popup;
  border: solid;
  position: absolute;
  left: 50%;
  z-index: 2;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 0 5px;
  visibility: hidden;
  margin-left: 10px;
  max-height: 2em;
  width: max-content;
}

.help-popup::after {
  position: absolute;
  content: "";
  right: 100%;
  border-style: solid;
  border-width: 10px;
  top: 10%;
  border-color: transparent #555 transparent transparent;
}

.show-popup {
  visibility: visible;
  animation: fadeIn 1s;
}

/*Animation Popup*/

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />

    Nom :

    <input class="input-entry letter-input" id="input-nom" name="nom" type="text" required>
     Pour ce champs veillez à n'utilisez que des lettres

    Prénom :

    <input class="input-entry letter-input" id="input-prenom" name="prenom" type="text" required>
     Pour ce champs veillez à n'utilisez que des lettres


text:
Q: Scala future strange error on completion I am just getting started with futures and stumbled upon an error which seems quite strange to me:
Using play-ws to perform a post request and map the result:
wsClient.url(url).withHeaders("Content-Type" -> "application/json")
      .post(payload)
      .map { wsResponse =>
        if (!(200 to 299).contains(wsResponse.status)) {
          sys.error(s"Received unexpected status, open-cpu error ${wsResponse.status} : ${wsResponse.body}")
        }
        println(s"OK, received ${wsResponse.body}")

        wsResponse.json.validate[Seq[MyClass]] match {
          case JsSuccess(result, _) => result.map(outlierRes => Map("key" -> outlierRes.attr, "key2" -> outlierRes.attr2, "key3" -> outlierRes.val3))
          case JsError(error) => throw new MyException(error.toString())
        }
      }

works just fine. The println of the body shows everything is there, and the validation succeeds.
The problem lies here: aggregatedData = Await.result(theFutureFromAbove, 20.minutes)
This statement crashes with the following when run via the interactive console:
MyException
        at $anonfun$1.apply(<console>:44)
        at $anonfun$1.apply(<console>:44)
        at scala.util.Success$$anonfun$map$1.apply(Try.scala:206)
        at scala.util.Try$.apply(Try.scala:161)
        at scala.util.Success.map(Try.scala:206)
        at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
        at scala.concurrent.Future$$anonfun$map$1.apply(Future.scala:235)
        at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
        at scala.concurrent.impl.ExecutionContextImpl$$anon$3.exec(ExecutionContextImpl.scala:107)
        at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
        at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
        at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
        at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

Which would suggest a parsing exception.
However, when run via sbt run there is a different exception:
java.lang.NullPointerException

Which resembles this line:     wsClient.url(baseUrl + url).withHeaders("Content-Type" -> "application/json")
edit
It seems to be triggered by: wsClient.close() as if I closed the wsClient before the future completed.
However, in the documentation it states

If you create a WSClient manually then you must call client.close() to
  clean it up when you've finished with it.

so where should I close it? Initially, I thought it would be safe to close after the Await.result but that still is throwing the error.
edit 2
wsResponse.json.validate[Seq[MyClass]].fold(
          error => {
            println(error)
            Future.failed(new MyException("parsing failed" + error))
          },
          result => result.map(data => Map("period" -> data.period, "amount" -> data.totalAmount, "outlier" -> data.isOutlier))
        )

But this still does not compile as Future[nothing] does not match my return type of Future[Seq[Map[String, Any]]]

A: Based on https://github.com/studiodev/Mocky/blob/master/app/services/GithubRepository.scala I finally found something similar to
private def parseGistResponse(response: WSResponse): Future[GistResponse] = {
    if (response.status < 400) {
      logger.debug(s"<< (${response.status}) ${response.body}")
      response.json.validate[GistResponse].fold(
        error => {
          logger.error(s"Unable to parse GistResponse: $error")
          Future.failed(new RuntimeException("parse-json-failed"))
        },
        gistResponse => Future.successful(gistResponse))
    } else {
      logger.error("Unable to parse GitResponse, cannot contact WS\n" + debugResponse(response))
      Future.failed(new RuntimeException("ws-error"))
    }
  }


text:
Q: How to recognize current activity of user from a service? I have tried to make a service to recognize the user's current activity.
But this code crashes everytime.
It throws exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.location.DetectedActivity com.google.android.gms.location.ActivityRecognitionResult.getMostProbableActivity()' on a null object reference
at com.always_in_beta.ecodrive.service.UserTrackService.detectActivity(UserTrackService.java:51)
at com.always_in_beta.ecodrive.service.UserTrackService$1.run(UserTrackService.java:27)
The code is:
public class UserTrackService extends Service {

    public Handler handler = null;
    public Runnable runnable = null;
    int count = 0;
    public Context context = this;
    public Intent intentt;

    @Override
    public void onCreate() {
        handler = new Handler();
        runnable = new Runnable() {
            public void run() {
                detectActivity();
            }
        };
        handler.postDelayed(runnable, 4000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(context, "Service stopped", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        intentt = intent;
        return null;
    }

    public void detectActivity() {
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intentt);
        DetectedActivity activity = result.getMostProbableActivity();
        Toast.makeText(context, activity.toString(), Toast.LENGTH_SHORT).show();
        Log.d("tag_tag_tag", activity.toString());
    }
}

A: ActivityRecognitionResult#extractResult(android.content.Intent)

Returns
  an ActivityRecognitionResult, or null if the intent doesn't
  contain an ActivityRecognitionResult.

So, according to your null pointer stacktrace, that's expected because you can't run getMostProbableActivity() on a null.


text:
Q: making an array with the length of chars in unicode I am  writing a code in java , where every time a user types 1 character it checks if it is one of the special characters
char a = getFromInput();

if(a = '$'){
  //do something

}else if(a = '@'){
  //do something

}else if(a = '#'){
  //do something

}else if(a ='~'){
  //do something

}else if(a ='^'){
  //do something

}else if(a ='&'){
  //do something

}... // the if statements go on

However It came to me that this is inefficient since it uses to much if statements . To solve this, I came up with the idea to make an array of bytes with the length of the unicode index of the last special character
byte[] bytes = new byte[1000]

// the length 1000 is because I thought most of the special characters are
// index of less that 1000 in unicode UTF-8 mapping

Functor[] functors;

// functors are just objects that i made that contain function

char a = getFromInput();
if(byte[a] >100){
   // do nothing when byte[char] is larger that 100
}else {
    functors[byte[a]].func();
}

So basically what i'm trying to do is using the char variable as index of the array. What i'm curious is

*

*Would using more that 100 if statements for every character the user inputs be okay? are there any suggestions ?

*I know making an array would cost more memory but would it be better than using multiple (tons of ) if statement with respect to the performance ?

A: You should check range of characters instead of checking one character after the other. Something like
if (a < 'a' && a > 'z') {
    // do something
}

A:
Would using more that 100 if statements for every character the user inputs be okay? are there any suggestions ?

It is up to you to decide what is "okay" ... unless you provide us with the criteria.
However, there are a variety of other alternatives to lots of if statements:

*

*a switch statement

*if statements that test character ranges rather than individual characters

*an array of SomeFunction where the character is the array index

*an array of codes (indexed by character) that maps characters to code values (e.g. SomeEnum) that you then switch on

*an array of a custom PairOfCharAndFunction class sorted on the character field that you search using binary search

*a HashMap<Character, SomeFunction>

*a TreeMap<Character, SomeFunction> or TreeMap<Character, SomeEnum> that you use to implement range-based checking: hint the floorEntry method.

And so on.

I know making an array would cost more memory but would it be better than using multiple (tons of ) if statement with respect to the performance ?

Yes it would, provided that the array (or similar mapping data structure; see above) only needs to be set up once.
It is theoretically possible for the Java JIT compiler to turn a sequence of if tests into the machine equivalent of a switch in some circumstances, but I don't think it does.

... would a switch statement be generally faster than if statements?

Generally yes.  If not, the JIT compiler will translate the switch into a sequence of if statements.  (In fact, there is a time versus code-space trade-off here.)


text:
Q: Regex in vim for Makefile target I want to replace all the targets in a Makefile with something else using vim.  I'm sure this is possible with regex but I haven't figured out the syntax.
For example if I have
foo.o: $(src)/foo.c

I want to change this to:
SRC += $(src)/foo.c

I see that the vim search:
/\:

Gets me the colon.  But I'm not sure yet how to get the rest of the word (i.e. foo.o).

A: Not tested. Typing the following command you will apply a global change which change text to colon, with SRC += on lines matching the regexp ^[^[:space:]:]+
:g/\v^[^[:space:]:]+/normal ^cf: SRC +=

\v is the switch for very magic mode (which you want to use most of the time). ^ means begining of line ^ inside square brackets means not any of this characters. In this case not spaces and not colon + means one or more times the previous character class. At the end the normal command does the substitution you want.
I recommend you to position the cursor on a line you want to change and try typing:
^cf: SRC += to see if it's what you want to do


text:
Q: How to set session affinity between inner servicess inside a Kubernetes cluster Here is my problem: I have 3 services defined in a kubernetes yaml file:

*

*one front-end (website)

*one back-end : stateful, for user sessions

*one back-end : stateless

I need session affinity on the stateful service, but not on the stateless nor front-end service. I need the session affinity to be cookie-based, not clientIP based.
mydomain/stateful  ===> Front-End Service (3 pods) ===> Stateful Service (3 pods, need session affinity)
mydomain/stateless ===> Front-End Service (3 pods) ===> Stateless Service (3 pods, do not need session affinity)

I tried to use Ingress service, but I fail to see how I can use it as a proxy in-between 2 services inside the Kubernetes Cluster. All the examples I see show how to use Ingress as a router for request coming from outside the Cluster.
Here is my poc.yaml so far:
####################################################################
######################### STATEFUL BACKEND #########################
# Deployment for pocbackend containers, listening on port 3000
apiVersion: apps/v1
kind: Deployment
metadata:
  name: stateful-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: stateful-backend
      tier: backend
  template:
    metadata:
      labels:
        app: stateful-backend
        tier: backend
    spec:
      containers:
      - name: pocbackend
        image: pocbackend:2.0
        ports:
           - name: http
             containerPort: 3000
---
# Service for Stateful containers, listening on port 3000
apiVersion: v1
kind: Service
metadata:
  name: api-stateful
spec:
  selector:
    app: stateful-backend
    tier: backend
  ports:
  - protocol: TCP
    port: 3002
    targetPort: http
  #sessionAffinity: ClientIP
---
#####################################################################
######################### STATELESS BACKEND #########################
# Deployment for pocbackend containers, listening on port 3000
apiVersion: apps/v1
kind: Deployment
metadata:
  name: stateless-backend
spec:
  replicas: 3
  selector:
    matchLabels:
      app: stateless-backend
      tier: backend
  template:
    metadata:
      labels:
        app: stateless-backend
        tier: backend
    spec:
      containers:
      - name: pocbackend
        image: pocbackend:2.0
        ports:
           - name: http
             containerPort: 3000
---
# Service for Stateless containers, listening on port 3000
apiVersion: v1
kind: Service
metadata:
  name: api-stateless
spec:
  selector:
    app: stateless-backend
    tier: backend
  ports:
  - protocol: TCP
    port: 3001
    targetPort: http
---
#############################################################
######################### FRONT END #########################
# deployment of the container pocfrontend listening to port 3500
apiVersion: apps/v1
kind: Deployment
metadata:
  name: front-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: frontend
      tier: frontend
  template:
    metadata:
      labels:
        app: frontend
        tier: frontend
    spec:
      containers:
      - name: pocfrontend
        image: pocfrontend:2.0
        ports:
           - name: http
             containerPort: 3500
---
# Service exposing frontend on node port 85
apiVersion: v1
kind: Service
metadata:
  name: frontend-service
spec:
  type: LoadBalancer
  selector:
    app: frontend
    tier: frontend
  ports:
  - protocol: TCP
    port: 85
    targetPort: http

Do you know how to solve my problem?
Thanks!

A: Natively Kubernetes itself does not provide session affinity on service [concept] level.
The only way that comes to my mind is to use Istio and it's Destination Rules. Taken from the istio manual:

DestinationRule defines policies that apply to traffic intended for a service after routing has occurred. These rules specify configuration for load balancing, connection pool size from the sidecar, and outlier detection settings to detect and evict unhealthy hosts from the load balancing pool.

This document shows how to to configure sticky session with istio.


text:
Q: Looping through a Self Referencing Object I have an object such that it can contain a list of its own type. For example, an items class contains various properties. Another class, ItemSet consists of  a list of items but can also have a nested Item set. In other words, an ItemSet can contain other item sets. This looks as follows:
public class Item
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }
    public int Property3 { get; set; }
    public int Property4 { get; set; }
}

public class ItemSet
{
    public List<Item> Items { get; set; }
    //.
    //.
    //.
    //.
    public List<ItemSet> ItemSets { get; set; }

}

I've gone in circles(haha get it?) trying to figure out how to loop through the ItemSet object. I have been unable to adjust for the infinite possibilities of parent and child sets. I feel like i a making this much harder than it needs to be.
ItemSets = getItemSets(....);
bool hasSets = false;
ItemSet currentItemSet;
foreach(ItemSet itemSet in currentItemSets)
{
     currentItemSet = itemSet;
     hasSets = HasSets(currentItemSet);

     if(hasSets == false)
     {
         //do stuff with currentItemSet
     }

     while(hasSets == true)
     {
         List<ItemSet> SubSets = getItemSets(CurrentItemSet);
         foreach(subset in SubSets)
         {
             currentItemSet = subset;
             //do stuff with currentItemSet

             hasSets = HasSets(currentItemSet);

             ??????????????????????????
         }

     }
}

I know im significantly off here but was hoping for some pointers. I do need to be able to discern if the Itemset contains children subsets and handle appropriately.

A: Define a method for your ItemSet class that can loop through the sets and recursively call the same method on each of them. Something like this:
class ItemSet
{
    public List<ItemSet> ItemSets { get; set; }
    public bool hasSets { get; set; }

    public void Loop()
    {
        if (hasSets)
        {
            ItemSets.ForEach(s => s.Loop());
        }

        // do stuff here
    }
}

Update
Or just use a recursive method
void Loop(ItemSet set)
{
    set.ItemSets?.ForEach(i => Loop(i));
}


text:
Q: FileWriter only displays the last line When I display the variable data using System.out.println(data), it displays the content (all lines) of the "filename.txt".
However, when I use myWriter.write(data), it only writes the last line of the initial file.
My task is to read a file (in this case, filename.txt) and copy its content into a new file (new.txt).
package javaapplication13;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class readFile {
    public static String data;

    public static void main(String[] args) throws IOException{
        try{
            File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\filename.txt");
            try (Scanner myReader = new Scanner(myObj)) {
                do{
                     data = myReader.nextLine();
                }
                while (myReader.hasNextLine());

                  PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
                  FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
                  myWriter.write(data);

                  myWriter.close();
                  out.close();
                  myReader.close();

            }
        }
        catch (FileNotFoundException e){
            System.out.println("An error occurred.");
        }
    }
}

A: Every iteration of the loop opens a new writer, and then writes to it, thus overwriting the file. Instead, you should open the writer once, before the loop, and close it once you're done writing. E.g.:
try (FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt")) {
    while (myReader.hasNextLine());
        myWriter.write(myReader.nextLine());
    }
}


text:
Q: Convert an animated 3D model to Quake 2's models I'm about to create an Augmented Reality application which requires to render 3d models with animation. What is the best way/plug-in or software to export a model to old quake (.md2) format?
I want to use popular modelling software like 3Ds MAX, Maya or Blender. I have search all over the internet but I only found some plug-ins which I had difficulty to work with.
Any commercial tool? I need a good support.

A: Hmmm... my favorite question.
It highly depends on what kind of animation you are willing to export.
3Ds Max
In 3Ds Max there is an awesome plugin called QTip. It only costs a few bucks but it's worth every single penny.
Maya
There is also another export plugin (MD2Export) for Maya. I didn't have much success with it but it's worth trying.
Blender
There are also some scripts written for Blender but none worked for me. But I think Blender 2.46 has a native export for MD2.
Stand-alone Software
Few lightweight applications have a support for export MD2:

*

*fragMOTION: Can import/export variety of formats and has support for MD2 and MD3

*MilkShape 3D: Same as fragMOTION but it also has an MD2 viewer which comes handy sometimes.

*Quake2 Modeller: It's very old and I didn't try it personally.

NOTE 1: As I said, it highly depends on your animation. If you have Vertex animation then QTip is your golden choice. fragMOTION and MilkShape do not support vertex animation. But if you make Bone animation, you may use the modeling software of your choice and import it to fragMOTION or MilkShape and then export it to MD2.
NOTE 2: I think you can find more information about MD2 here


text:
Q: SQL 2008 asynchronous replication with parent site I have SQL 2008 installed on Win 2008 VM on one hardware which is in subnet of (parent) 192.168.0.0.24 and second site has similar hardware with win2008+SQL2008 in 10.1.1.0/24 (child) and third one is in 172.16.1.0/24.
We want to know how do i enable block level SQL 2008 replication from one site to another and i have ipsec vpn of T1 link.
My objective is -1 day child site database in parent site and is there any way the database can be replicated at block level instead of replicating entire database. There are 3 databases with 15GB, 12GB and 1GB. I can initiate by copying manually and am not sure how to configure to asynchronous replication of the database between child to parent site.
Please help and am zero in SQL 2008

A: From your question, it is not entirely clear what the child sites are for. Are the child sites for disaster recovery only, are they read-only copies of the parent data or do you need to update the child copies and have the changes make it back into the parent?
SQL Server does not directly supply block level replication of any kind. All of SQL Server's replication features are data-level. You would either be doing full pulls all of the time or sending changes, depending on exactly what you need.
SQL Server has other relevant technologies besides the features that it calls "replication". Those technologies are Database Mirroring, Always-on Availability Groups and Log Shipping. Exactly what you might use depends heavily upon exactly what you are trying to do and your familiarity with SQL. If you are just interested in disaster recovery or maybe read-only copies, the simplest thing to do is probably log shipping. Log shipping has been around the longest, it works on any version of sql server and it's actually pretty simple, under-the-covers.
Normally, block-level replication is handled by smart SAN storage of some kind (Vmax and Symetrix jump to mind first, but there are many other options) or you might use something like DataKeeper's Steeleye, which is software only.
Block-level replication is normally one-way-only, with a primary and a secondary system. I've never seen a system with two secondaries, I am not a storage specialist but I am a SQL guy. Also note that in SQL Server setups that use block level-level replication (via SAN or similar technology), the scheme is really that of a active-passive failover cluster and the "child" copies are typically not available for any use.
Regardless of the method of replication, all of the data will have to be pushed from the parent to the child first, before replication can actually begin. After that, the child sites would only receive changes to the data. You say that you could manually copy the data. Usually, the first copy of the data is done using some wort of management tool that is tied to whatever product you are using. You can't just copy stuff from a command line using the regular windows tools.
A T1 line has a bandwidth of 1.544 mbit/sec. If my math is right, that is about 694.8 MBytes/hour. It will take about 42.27 hours to transfer those three databases the first time. That isn't very fast.
If your data gets many changes, it is very possible that the 1.544 mbit/sec will not be fast enough to keep up. If you do something like run a reindex command, which could change a lot of data in a block-replication scenario (but wouldn't change anything in a data-replication scenario), the replication will almost certainly fall behind. If you are running asynchronously, it is likely that there will be some sort of write buffer (a write queue or write cache) that will accept and hold changes on the parent side until they can be sent to the child side, but the size of the buffer may not be large enough to hold all of your data. Once the buffer fills up, you will effectively be running synchronously or your system will be loosing data (thereby destroying your databases).


text:
Q: Use user set custom cursor Java I know that it is possible for users to define their own system-wide cursors on Windows and OSX. However, I haven't found any way to use those cursors in a Java class.
For example, say I have a JFrame, and a custom drawn component, like so:

This cursor was set using setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)). But I want to use the link cursor set by the user so the application is more integrated with the OS. Is there any way to not use the Java defined link cursor? Do I need to explicitly ask for a file? Or do I need to use JNA or something?
---EDIT---
I think I need to make the question more clear.
Say the user set their system-wide link cursor (the cursor that appears when hovering over a link, say in a web browser) to a picture of a banana. How do I switch to the banana cursor when hovering over a custom-drawn component?

A: Have You tried jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); this method should get the system cursor as you wanted.


text:
Q: git error: gnutls_handshake() failed on push I have been using git for a while with no problems, then suddenly it started throwing this error when using git push:

error: gnutls_handshake() failed: A TLS packet with unexpected length was received. while accessing ...
  fatal: HTTP request failed

It was working fine, then suddenly it stopped.
What is the problem?
Thanks

A: It seems there is a problem with the gnutls package. As a workaround, you can try to compile git with openssl. More info on how to accomplish this you can find here.

A: The linked discussion on askubuntu references a version number for git that may not match up with your own. Instead of these two lines:
sudo dpkg-source -x git_1.7.9.5-1.dsc
cd git_1.7.9.5 8.

you need to account for the version of git you're using. In my case, it was 1.8.xxxxx.
sudo dpkg-source -x git_<git-version-number>.dsc
cd git_<git-version-number>

An easy way to get around this is to just copy the first part of the command and then hit Tab to autocomplete. This may not work perfectly if you have recompiled before.

A: In my case same error was caused by completely different thing.
Debian was upgraded from Wheezy to Jessie, and thus apache was upgraded 2.2.22 to 2.4.10. git was trying to push to https://www.example.com and it stopped working with error: gnutls_handshake() failed: A TLS packet with unexpected length was received
Turns out, www.example.com was resolving to both IPv4 and IPv6 addresses, and apache config was having <Virtualhost x.y.w.z:443> IPv4 address only. Changing that to <Virtualhost _default_:443> fixed the problem.
(just so if it helps somebody else with same problem... only found it after the tedious recompile of git with openssl didn't change anything at all)

A: This answer might help. I was surprised that the problems are nowhere to be linked together although the question is old.
Just to be sure the usefull info won't get lost, I copy a brief solution from the question:
hostname=XXX
port=443
trust_cert_file_location=`curl-config --ca`

sudo bash -c "echo -n | openssl s_client -showcerts -connect $hostname:$port 2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' >> $trust_cert_file_location"

A: I have also faced the same issue which was fixed later by disabling my Kaspersky antivirus in my local machine. I hope this may be helpful to others.


text:
Q: Use lenskit framework recommender system in google ApEngine Hy every one;
Can we use lenskit framework of recommender system in google AppEngin
or can we use other recommender Engine
Thanks by Advance

A: There should be no reason you can't use LensKit in Google AppEngine.  You will probably need to implement a data access backend that talks to your AppEngine storage, but most applications using LensKit implement a data access backend for their particular database anyway.


text:
Q: Storyboard show viewcontrollers in reversed Preview (Xcode 8.3.2) Xcode 8.3.2 shows the viewControllers in a reversed preview like a mirror (screenshot attached). I don't know whether it's an Xcode bug or a hidden feature. I'm facing a problem due to this. Is there any way to recover the viewControllers in the original preview and to resolve this issue?

A: I faced the same problem. Just close the Xcode project completely and then reopen it. It worked for me!!

A: Reinstall the Xcode.Because the same problem was faced by me.
I think it happens when me having many viewController in storyBoard and we keep changing the file at that time this occur.

A: Storyboard lagging due to many viewControllers and continuously changing the viewcontrollers causes this problem to occur in Xcode 8.3.2. So everytime I needed to quit and reopen the storyboard resolve this issue.
Now, I have updated Xcode to version Xcode 9.2 and issue has been resolved.


text:
Q: W3C Speech To Text: output values as you speak I've been using the W3C Speech Synthesizer for the web in my app. I'd like the words to start appearing as I speak them. This is because I want the user to have near-instant feedback on the current word they're speaking. Currently, the result events in the spec wait to append the entire array after a second or so of not speaking.
I've looked through the standards, but I've only found that it waits a bit to construct the final results list from the result event:
5.1.3 SpeechRecognition Events
result event: Fired when the speech recognizer returns a result
5.1.8 SpeechRecognitionEvent
results attribute: The array of all current recognition results for this session.
I've also tried retrieving the results in onstart and onpause methods:
            recognition = new webkitSpeechRecognition()

            recognition.onstart = function (event) {
                //append word
            };

            recognition.onpause = function (event) {
                //append word
            };

Anyone know a way to accomplish this "typing" effect of the words as you speak?

The other issue is, if the user stops speaking for a sec, and the results list is compiled (IE, the result event is fired), and they go to speak again, the results list is not updated.
This happens even if I set recognition.continuous = true;

A: Found it from Google Developers Introduction Video.
In addition to recognition.continuous = true, you also need recognition.interimResults = true;.
Then need to modify your logic slightly in the onresult handler to account for interim results:
recognition.onresult = function (event) {
  var final = "";
  var interim = "";
  for (var i = 0; i < event.results.length; ++i) {
    if (event.results[i].final) {
      final += event.results[i][0].transcript;
    } else {
      interim += event.results[i][0].transcript;
    }
  }
  final_span.innerHTML = final;
  interim_span.innerHTML = interim;
}


text:
Q: Why Records: [] is empty when i consume data from kinesis stream by python script? I am trying to consume data from kinesis data stream which is created and produce data to it successfully , but when running consumer script in python :
import boto3
import json
from datetime import datetime
import time

my_stream_name = 'test'

kinesis_client = boto3.client('kinesis', region_name='us-east-1')

response = kinesis_client.describe_stream(StreamName=my_stream_name)

my_shard_id = response['StreamDescription']['Shards'][0]['ShardId']

shard_iterator = kinesis_client.get_shard_iterator(StreamName=my_stream_name,
                                                      ShardId=my_shard_id,
                                                      ShardIteratorType='LATEST')

my_shard_iterator = shard_iterator['ShardIterator']

record_response = kinesis_client.get_records(ShardIterator=my_shard_iterator,
                                              Limit=2)

while 'NextShardIterator' in record_response:
    record_response = kinesis_client.get_records(ShardIterator=record_response['NextShardIterator'],
                                                  Limit=2)

    print(record_response)

    # wait for 5 seconds
    time.sleep(5)

But the output of the message data is empty ('Records': []):

{'Records': [], 'NextShardIterator':
'AAAAAAAAAAFFVFpvvveOquLUe7WO9nZAcYNQdcS6f6a+YGrrrjZo1gULcu/ZYxC7AB+xVlUhgL9UFPrQ22qmcQa6iIsmuKWl26buBk3utXlVqiGuDUYSgqMOtkp0Y7pJwa6N/I0fYfl2PLTXp5Qz8+5ZYuTW1KDt+PeSU3992bwgdOm7744cxcSnYFaQuHqfa0vLlaRBTOACVz4fwjggUBN01WdsoEjKmgtfNmuHSA7s9LLNzAapMg==',
'MillisBehindLatest': 0, 'ResponseMetadata': {'RequestId':
'e451dd27-c867-cf3d-be83-edbe95e9da9f', 'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amzn-requestid':
'e451dd27-c867-cf3d-be83-edbe95e9da9f', 'x-amz-id-2':
'ClSlC3gRJuEqL9YJcHgC2N/TLSv56o+6406ki2+Zohnfo/erFVMDpPqkEWT+XAeeHXCdhYBbnOeZBPyesbXnVs45KQG78eRU',
'date': 'Thu, 14 Apr 2022 14:23:21 GMT', 'content-type':
'application/x-amz-json-1.1', 'content-length': '308'},
'RetryAttempts': 0}}


text:
Q: How to clear Vinagre recent connections? How do I clear the items in Vinagre under Remote > Recent Connections?
I've done this and it does not work.  I've deleted the entire Vinagre profile directory ~/.local/share/vinagre and it somehow regenerates the recent connections list.  I uninstalled and reinstall Vinagre... still there!
Where the heck is this stubborn list stored that I can actually delete it?

A: Found it
Delete the file $HOME/.local/share/recently-used.xbel


text:
Q: terraform loop with a conditional key inside an object let's suppose we have this variable:
  foobars = {
    "first" : {
      specialkeys: [
        "a",
        "b",
        "c"
      ]
    }
    "second" : {}
  }

now let's say we would like to loop over that foobars object knowing that specialkeys doesn't exist in the "second" object.
This is what I tried but it complains that
This object does not have an attribute named specialkeys

My tries:
  data = flatten([
    for k, v in var.foobars : [
      for sk in v.specialkeys : {
          special = sk,
          foo = k
      }
    ]
  ])

A: I believe you would want to do the following:
data = flatten([
    for k, v in local.foobars :
    [
      for sk, sv in v :
      [
        for spec in sv : {
          special = spec,
          foo     = k
        }
      ]
    ]
  ])

This will output something like this:
[
  {
    "foo" = "first"
    "special" = "a"
  },
  {
    "foo" = "first"
    "special" = "b"
  },
  {
    "foo" = "first"
    "special" = "c"
  },
]