Q: FileMaker :- Compare textbox values with OBBC SQL DB I am trying to implement an Login module where,I need to Compare the list of values in  SQL DB. Here i want to compare text  box entered values with SQL DB.
Please share any views.

A: Depends on your SQL DB. You can add your SQL DB as ESS or you can use "Execute SQL" and run a SQL query on ODBC DNS to your database.
If you are in 16 and your SQL has any API, you can call them through CURL. You can do the same with previous versions of FileMaker using plugins.


Q: Is the set of sum of Linearly independent equations are linearly independent with the equations? If I have a set of linearly independent equations, E1, E2, ..., En. I am wondering if all the possible sums are linearly independent between them and between the original equations.
{E1, E2, .., En, E1+E2, E1+E3, E2+E3, ..., Ei+En}
are linearly independent?
If yes, how can I prove it? Thanks.

A: Of course not (unless $n=1$). Since your set contains $E_1$, $E_2$ and $E_1+E_2$, it cannot be linearly independent, because$$1\times E_1+1\times E_2+(-1)\times(E_1+e_2)=0.$$


Q: Acessing textutil source code Is it possible open the source code of the textutil command-line utility?
I'm not finding anything in google.
Thanks.


Q: Laravel Ajax working fine on page reload but when I use Ajax to filter data pagination with jsscroll does not work Pagination links working fine as normal pages when I refresh the whole page but when i reload just data with ajax pagination does not loading next pages
  $.ajax({
         url: '{{route('apply.filters')}}',
         type:'get',
         data: {cities:cities,
             category:category
         },
         success: function (data) {
             // $(".contentlist").load(location.href + " .contentlist");
             $('.contentlist').html(data);
         },
         error: function(xhr, status, errorThrown) {
             console.log(xhr.responseText);
         }
     });

this is my controller function
public function filter(Request $request)
{
     try {
     set_time_limit(390);
         $country=null;
         if(Auth::check() && $country==null){
             $country=Auth::user()->lat->country??'';
         }if(Session::has('country') && $country==null){
             $country=Session::get('country.0');
         }
        if(isset($request->cities)){
            $data =[
                'products' => Product::where([['category',$request->category],['country',$country??'']])->whereIn('city',$request->cities)->where('status',1)->Orderby('id','desc')->paginate(8),
            ];
        }
    if(isset($data)){
    return response()->json(view('front.home.ajaxindex',$data)->render());
    }else{
        return redirect()->route('home');
    }
     } catch(\Exception $e) {
        return back()->with('error',$e->getMessage());
    }
}

this is my jsscroll function working normally fine but not loading data comes with ajax
 $('ul.pagination').hide();
$(function() {
    $('.contentlist').jscroll({
        autoTrigger: true,
        loadingHtml: '', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
        padding: 0,
        nextSelector: '.pagination li.active + li a',
        contentSelector: 'div.contentlist',
        loadOnScroll: false,
        callback: function() {
            $('ul.pagination').remove();
            $('.elements').each(function(){
                var thisH = $(this).height();
                if (thisH > maxHeight) {
                    maxHeight = thisH;
                }
                $(this).height(maxHeight);
            });

        }
    });
});

this is my ajaxindex page this is new page only created for making html which is appended in the main page if data exists
@foreach($products as $product)

                    @if(\Illuminate\Support\Facades\Auth::guard('admin')->check())
                        id??''}}" onclick="deletes('{{$product->id}}',this)" class="fa fa-close fa-lg pull-right" style="margin-left: -20px; mix-blend-mode: hard-light; color: rgb(0, 255, 255); ">
                         preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","@","#"], '-',$product->title??'')).'-'.$product->id??''])}}">
                    @endif
                     preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","@","#"], '-',$product->title??'')).'-'.$product->id??''])}}">
                        @if(isset($product->atachedImage))
                            atachedImage->path.$product->atachedImage->name??'noimage.jpg')}}" title="{{$product->title??''}}_image" alt="">
                        @else
                            title??''}}_image">
                        @endif

title??''}}">{{str_limit($product->title??'',19)}}

@endforeach

    {{$products->appends(request()->except('page'))->links()??''}}


Q: C# - XML Document Won't Save document = new XmlDocument();
XmlNode docNode = document.CreateXmlDeclaration("1.0", "UTF-8", null);
document.CreateAttribute("EncryptionKey");
document.CreateAttribute("SaltKey");
document.CreateAttribute("VIKey");
document.CreateAttribute("EmailUsername");
document.CreateAttribute("EmailPassword");
document.AppendChild(docNode);
document.Save("Credentials.xml");

Apparently the root doesn't exist, even though I made one and applied it.
EDIT: What it should come out with: https://imgur.com/a/Crk3A

A: Maybe you need something like this. With a root node named "Credentials"
private void CreateXml()
{
    var document = new XmlDocument();
    XmlNode rootNode = document.CreateElement("Credentials");
    document.AppendChild(rootNode);

    rootNode.AppendChild(document.CreateElement("EncryptionKey"));
    rootNode.AppendChild(document.CreateElement("SaltKey"));
    rootNode.AppendChild(document.CreateElement("VIKey"));
    rootNode.AppendChild(document.CreateElement("EmailUsername"));
    rootNode.AppendChild(document.CreateElement("EmailPassword"));

    XmlNode declaration = document.CreateXmlDeclaration("1.0", "UTF-8", null);
    document.InsertBefore(declaration, rootNode);

    document.Save("Credentials.xml");
}

EDIT: Added declaration


Q: Using a custom CSS file - hiding a button I created a local.css file that works well with this content:
body {
    background: blue;
}

However, I want to use it to hide this button:
<button type="submit" title="Add to Cart" class="action tocart primary">Add to Cart</button>

How do I format the CSS to hide this button?

A: You can hide that button by local.css by the following rule:
.action.primary.tocart {
    display: none;
}

If it does not work, add !important to the property value:
.action.primary.tocart {
    display: none !important;
}


Q: Generalization of Hamiltonian cycle Let $G=(V,E)$ be a graph. For $v\in V$ we set $N(v) = \{w\in V: \{v,w\}\in E\}$.
Let us say that a graph is neighborly if there is an injective function $f: V\to V$ such that $f(v)\in N(v)$ for all $v\in V$. (Is there standard terminology for this? Any pointers appreciated!)
If a graph has a Hamiltonian cycle, let's call it a HC-graph. It is easy to see that HC-graphs are neighborly, as well as unions of HC-graphs, each of which has more than 1 vertex.
Is the following statement correct?

(?): If a finite graph $G=(V,E)$ is neighborly, then there is a partition of $V$ into subgraphs, each of which is a HC-graph and consists of more than 1 point.

(Remark: The nice thing about this definition is that there are neighborly graphs for any finite or infinite cardinality, but it is not obvious how to generalise Hamiltonian cycles to infinite graphs.)

A: I think this is true and trivial, and not really research-level.
Since $V$ is finite and $f$ is injective, it is a permutation.
Write it as a union of disjoint cycles.
Assuming the graph has no loop, $f$ has no fixed point and thus every cycle has length at least two.
The graph induced on each cycle is clearly HC, in fact the cycle of the permutation itself gives the graph cycle. Thus the orbits of the group generated by $f$ give the required partition.
All of this is clearly reversible.
In other words,  being neighborly is equivalent to containing a spanning subgraph that is a union of cycle, which is equivalent to being able to partition the vertex set such that the graph induced on each part is Hamiltonian.
(Note that, in all of the above, I am assuming that we consider K2 to be a degenerate cycle, as in your comment.)


Q: Question about the "Legendary" Badge When I was looking at the badges I started reading the Legendary Badge and noticed that it says:

Hit the daily reputation cap on 150 days

Now, I interpreted this as: "On the 150th day you have been here, if you get the daily reputation cap, you will earn this badge". Now, my first reaction was like "Wth?" because the Epic badge says "Hit the daily reputation cap on 50 days" and if you interpret it the way I did for the Legendary badge, you would probably think "Why is Epic only Silver and why is Legendary Gold?" Maybe it's just me, but, if I understand what you guys really mean wouldn't:

Hit the daily reputation cap for 150 days in a row

be better. Or am I completely misunderstanding this?

A: No, to get this badge you have to hit the daily rep cap on 150 days. The days are not consecutive; it should probably just say something like
"Hit the daily rep cap on 150 occasions"
This same logic also applies to the epic badge.


Q: Incremental build with GCC and manual makefile? I am coding to the NRF51822 bluetooth chip, in Eclipse with GCC and a makefile that I maintain myself.
My problem is that every time I press build, it will compile everything, which is beginning to take quite some time. I am not that experienced in creating and maintaining make-files, so I have no idea where to start in order to get it to build incremtal instead?
My makefile is composed like this (I know there's a lot, and I haven't created this myself - found it in a tutorial, so I don't know what's relevant and what's not :-) ):
PROJECT_NAME := my_project

export OUTPUT_FILENAME
#MAKEFILE_NAME := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
MAKEFILE_NAME := $(MAKEFILE_LIST)
MAKEFILE_DIR := $(dir $(MAKEFILE_NAME) )

TEMPLATE_PATH = nrf51_sdk/toolchain/gcc
ifeq ($(OS),Windows_NT)
include $(TEMPLATE_PATH)/Makefile.windows
else
include $(TEMPLATE_PATH)/Makefile.posix
endif

MK := mkdir
RM := rm -rf

#echo suspend
ifeq ("$(VERBOSE)","1")
NO_ECHO :=
else
NO_ECHO := @
endif

# Toolchain commands
CC              := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-gcc"
AS              := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-as"
AR              := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-ar" -r
LD              := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-ld"
NM              := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-nm"
OBJDUMP         := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-objdump"
OBJCOPY         := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-objcopy"
SIZE            := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-size"

#function for removing duplicates in a list
remduplicates = $(strip $(if $1,$(firstword $1) $(call remduplicates,$(filter-out $(firstword $1),$1))))

#source common to all targets
C_SOURCE_FILES += \
main.c \
file1.c \
file2.c \
file3.c \
file4.c \

#assembly files common to all targets
ASM_SOURCE_FILES  = nrf51_sdk/toolchain/gcc/gcc_startup_nrf51.s

#includes common to all targets
INC_PATHS  = -I Dir1/
INC_PATHS  = -I Dir2
INC_PATHS += -I Dir3
INC_PATHS += -I Dir4

OBJECT_DIRECTORY = _build
LISTING_DIRECTORY =$(OBJECT_DIRECTORY)
OUTPUT_BINARY_DIRECTORY =$(OBJECT_DIRECTORY)

# Sorting removes duplicates
BUILD_DIRECTORIES := $(sort $(OBJECT_DIRECTORY) $(OUTPUT_BINARY_DIRECTORY) $(LISTING_DIRECTORY) )

#flags common to all targets
CFLAGS  = -DSOFTDEVICE_PRESENT
CFLAGS += -DNRF51
CFLAGS += -DS110
CFLAGS += -DBOARD_PCA10028
CFLAGS += -DBLE_STACK_SUPPORT_REQD
CFLAGS += -mcpu=cortex-m0
CFLAGS += -mthumb -mabi=aapcs --std=gnu99
CFLAGS += -Wall -O0 -g3
CFLAGS += -mfloat-abi=soft
# keep every function in separate section. This will allow linker to dump unused functions
CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
#CFLAGS += -flto -fno-builtin

# keep every function in separate section. This will allow linker to dump unused functions
LDFLAGS += -Xlinker -Map=$(LISTING_DIRECTORY)/$(OUTPUT_FILENAME).map
LDFLAGS += -mthumb -mabi=aapcs -L $(TEMPLATE_PATH) -T$(LINKER_SCRIPT)
LDFLAGS += -mcpu=cortex-m0
# let linker to dump unused sections
LDFLAGS += -Wl,--gc-sections
# use newlib in nano version
LDFLAGS += --specs=nano.specs -lc -lnosys

# Assembler flags
ASMFLAGS += -x assembler-with-cpp
ASMFLAGS += -DSOFTDEVICE_PRESENT
ASMFLAGS += -DNRF51
ASMFLAGS += -DS110
ASMFLAGS += -DBOARD_PCA10028
ASMFLAGS += -DBLE_STACK_SUPPORT_REQD
#default target - first one defined
default: clean nrf51422_xxac_s110

#building all targets
all: clean
    $(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e cleanobj
    $(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e nrf51422_xxac_s110

#target for printing all targets
help:
    @echo following targets are available:
    @echo   nrf51422_xxac_s110
    @echo   flash_softdevice

C_SOURCE_FILE_NAMES = $(notdir $(C_SOURCE_FILES))
C_PATHS = $(call remduplicates, $(dir $(C_SOURCE_FILES) ) )
C_OBJECTS = $(addprefix $(OBJECT_DIRECTORY)/, $(C_SOURCE_FILE_NAMES:.c=.o) )

ASM_SOURCE_FILE_NAMES = $(notdir $(ASM_SOURCE_FILES))
ASM_PATHS = $(call remduplicates, $(dir $(ASM_SOURCE_FILES) ))
ASM_OBJECTS = $(addprefix $(OBJECT_DIRECTORY)/, $(ASM_SOURCE_FILE_NAMES:.s=.o) )

vpath %.c $(C_PATHS)
vpath %.s $(ASM_PATHS)

OBJECTS = $(C_OBJECTS) $(ASM_OBJECTS)

nrf51422_xxac_s110: OUTPUT_FILENAME := nrf51422_xxac_s110
nrf51422_xxac_s110: LINKER_SCRIPT=ble_app_hrs_gcc_nrf51.ld
nrf51422_xxac_s110: $(BUILD_DIRECTORIES) $(OBJECTS)
    @echo Linking target: $(OUTPUT_FILENAME).out
    $(NO_ECHO)$(CC) $(LDFLAGS) $(OBJECTS) $(LIBS) -o $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
    $(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e finalize

## Create build directories
$(BUILD_DIRECTORIES):
    echo $(MAKEFILE_NAME)
    $(MK) $@

# Create objects from C SRC files
$(OBJECT_DIRECTORY)/%.o: %.c
    @echo Compiling file: $(notdir $<)
    @echo arm-none-eabi-gcc $(CFLAGS) $(INC_PATHS) -c -o $@ $<
    $(NO_ECHO)$(CC) $(CFLAGS) $(INC_PATHS) -c -o $@ $<

# Assemble files
$(OBJECT_DIRECTORY)/%.o: %.s
    @echo Compiling file: $(notdir $<)
    $(NO_ECHO)$(CC) $(ASMFLAGS) $(INC_PATHS) -c -o $@ $<

# Link
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out: $(BUILD_DIRECTORIES) $(OBJECTS)
    @echo Linking target: $(OUTPUT_FILENAME).out
    $(NO_ECHO)$(CC) $(LDFLAGS) $(OBJECTS) $(LIBS) -o $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out

## Create binary .bin file from the .out file
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin: $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
    @echo Preparing: $(OUTPUT_FILENAME).bin
    $(NO_ECHO)$(OBJCOPY) -O binary $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin

## Create binary .hex file from the .out file
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex: $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
    @echo Preparing: $(OUTPUT_FILENAME).hex
    $(NO_ECHO)$(OBJCOPY) -O ihex $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex

finalize: genbin genhex echosize

genbin:
    @echo Preparing: $(OUTPUT_FILENAME).bin
    $(NO_ECHO)$(OBJCOPY) -O binary $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin

## Create binary .hex file from the .out file
genhex:
    @echo Preparing: $(OUTPUT_FILENAME).hex
    $(NO_ECHO)$(OBJCOPY) -O ihex $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex

echosize:
    -@echo ""
    $(NO_ECHO)$(SIZE) $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
    -@echo ""

clean:
    $(RM) $(BUILD_DIRECTORIES)

cleanobj:
    $(RM) $(BUILD_DIRECTORIES)/*.o

flash: $(MAKECMDGOALS)
    @echo Flashing: $(OUTPUT_BINARY_DIRECTORY)/$<.hex
    nrfjprog --reset --program $(OUTPUT_BINARY_DIRECTORY)/$<.hex)

## Flash softdevice
flash_softdevice:
    @echo Flashing: s110_softdevice.hex
    nrfjprog --reset --program nrf51_sdk/softdevice/s110/hex/s110_softdevice.hex

A:
all: clean

check this line. The default (first) Target of your Makefile depends on clean, so before any build is started, the clean target is executed that likely will remove all built files, to rebuild them.
Drop the clean and you should get the incremental behaviour make was designed for.


Q: Calculating variance
I am provided the following details (see picture) about a sample whereby $x$ is logarithm of income. How do I calculate the sample variance from this information?

A: I think it might do you some good to review the general formula for the sample variance, $\sum_{i=1}^n(x_i-\bar{x})^2\over{n-1}.$  Then explore how you might be able to algebraically manipulate this formula so that you can use the statistics or pieces of information that you have about the sample to solve the problem.


Q: How to send a lexicon to text-to-speech I'd like help with incorporating a new lexicon into the Azure Text-to-Speech API.
https://learn.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/hh378492%28v%3doffice.14%29
I've successfully sent text and have gotten mp3 files that work. Now I'm trying to incorporate a lexicon with difficult pronunciations.
I'm using the Python SDK for Text-to-Speech and have few questions from the documentation.

*

*Is this reference 'lexicon Element SSML (Microsoft.Speech)' outdated?

*What URI do I use?

*When I use the instructions in this document, I get the following error message: Status code: 400. Something went wrong. Check your subscription key and headers. How do I fix or investigate this?

*What format does the lexicon have to be in? I saw an example in the document that referenced a lexicon in a .pls format. How do I create this? Here is the reference:
<?xml version="1.0"?>
<speak
version="1.0"
xmlns="http://www.w3.org/2001/10/synthesis"
xml:lang="en-US">
<lexicon
uri="c:\Test\whatchamacallit.pls"
type="application/pls+xml"/>
 Gimme the whatchamacallit. </speak>

Here's part of the Python that I'm using:
xml_body = ElementTree.Element('speak', version='1.0')
xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
lexicon = ElementTree.SubElement(xml_body, 'lexicon')
lexicon.set('uri', '/User/.../Desktop/MedLex.pls')
lexicon.set('type', 'application/pls+xml')


Q: How can you make a PDE solution stabilize over time? Suppose I have a simple linear first order PDE of the form:
$$au_x+bu_y=0$$
I want to create a PDE in 3 variables, $x,y,t$ (so the function is now $u(x,y,t)$) such that given an initial condition $u(x,y,t)=u_0(x,y)$ (depending on just the first two variables):

*

*If $u_0$ satisfies the original PDE, then the solution to the new PDE is equal to $u_0$ at all times.

*Generally, as $t\rightarrow \infty$, the solution to the new PDE converges to a function of just two variables $u(x,y)$ which satisfies the original PDE. (converges in what topology? Naturally I'd prefer the topology to be as strong as possible, but I'm open to anything interesting)
So in a sense, I want my PDE to stabilize over time to a PDE of 'less' variables. For instance, I can create a PDE which satisfies the first condition by writing:
$$u_t=au_x+bu_y$$
But it does not generally satisfy the 2nd condition (I checked). An example which comes to mind is the heat equation, which usually stabilizes over time to a harmonic function. But I want something which fits my specific first order PDE. Does anyone have any ideas on how to do this?
This is the first part of my question. The harder part is - if we can find such a method for the PDE above, can we generalize this method for a system of 2 coupled PDE's of the form:
$$au_x+bv_y=0$$
$$cu_y+dv_x=0$$
Thanks in advance!


Q: Create conditional variables grouping by time and id I have a data frame that contains the product and destination (dest_prod) consumed by individuals (id), observed during different years (year) in the data frame df:
id <- c("1", "1", "1", "1", "2", "2", "2", "2", "3", "3", "3", "3")
year <- c("2000", "2001", "2002", "2003", "2002", "2003", "2004", "2005", "2001", "2002", "2003", "2005")
dest_prod <- c("FRA_coke", "FRA_coke", "USA_coke", "FRA_coke+USA_coke",
               "FRA_coke", "SPA_ham", "FRA_coke+SPA_ham", "GER_coke",
               "CHN_water", "CHN_oil", "CHN_water+CHN_oil+FRA_coke", "CHN_water+CHN_oil+FRA_coke")

df <- data.frame(id, year, dest_prod)

I would like to apply the following logic:

*

*Create a new variable "new_dest" if an individual consumes a prod_dest in year (t) that comes from a new destination (3 first letters of "dest_prod") than in year (t-1).

*Create a new variable "new_prod" if an individual consumes a prod_dest in year (t) that contains a new product (letters after the "_" symbol in "dest_prod") than in year (t-1).

Note!: If there is no observed year before (t) for a given individual or the last observation comes from 2 years or longer, I will assign "NA" value.
The new dataframe looks like df_mod:
new_dest <- c("NA", "0", "1", "1",
             "NA", "1", "1", "1",
             "NA", "0", "1", "NA")

new_prod <- c("NA", "0", "0", "0",
             "NA", "1", "1", "0",
             "NA", "1", "1", "NA")

df_mod <- data.frame(id, year, dest_prod, new_dest, new_prod)

I have tried to use ifelse in dplyr, but it does not work as it is impossible to capture the sense of time and group (id).
Any idea on how to create new_dest and new_prod in dplyr?

A: The first step is to parse the dest_prod column into a usable format:
library(tidyverse)

parsed <- df %>%
  mutate_at(c("id", "year"), as.integer) %>%
  separate_rows(dest_prod, sep = "[+]") %>%
  separate(dest_prod, into = c("dest", "prod"))

parsed
#> # A tibble: 18 × 4
#>       id  year dest  prod
#>    <int> <int> <chr> <chr>
#>  1     1  2000 FRA   coke
#>  2     1  2001 FRA   coke
#>  3     1  2002 USA   coke
#>  4     1  2003 FRA   coke
#>  5     1  2003 USA   coke
#>  6     2  2002 FRA   coke
#>  7     2  2003 SPA   ham
#>  8     2  2004 FRA   coke
#>  9     2  2004 SPA   ham
#> 10     2  2005 GER   coke
#> 11     3  2001 CHN   water
#> 12     3  2002 CHN   oil
#> 13     3  2003 CHN   water
#> 14     3  2003 CHN   oil
#> 15     3  2003 FRA   coke
#> 16     3  2005 CHN   water
#> 17     3  2005 CHN   oil
#> 18     3  2005 FRA   coke

Then:
parsed %>%
  # Add previous year's data in a list column
  nest_join(
    mutate(., year = year + 1L),
    name = "previous",
    by = c("id", "year")
  ) %>%
  # Check if any dest/prod appeared in previous year
  rowwise() %>%
  mutate(
    new_dest = !dest %in% previous$dest,
    new_prod = !prod %in% previous$prod,
  ) %>%
  # Set to missing if previous year was not observed
  mutate(
    across(c(new_dest, new_prod), replace, !nrow(previous), NA)
  ) %>%
  # Aggregate indicators on year level
  group_by(id, year) %>%
  summarise(
    new_dest = any(new_dest),
    new_prod = any(new_prod),
  )
#> # A tibble: 12 × 4
#> # Groups:   id [3]
#>       id  year new_dest new_prod
#>    <int> <int> <lgl>    <lgl>
#>  1     1  2000 NA       NA
#>  2     1  2001 FALSE    FALSE
#>  3     1  2002 TRUE     FALSE
#>  4     1  2003 TRUE     FALSE
#>  5     2  2002 NA       NA
#>  6     2  2003 TRUE     TRUE
#>  7     2  2004 TRUE     TRUE
#>  8     2  2005 TRUE     FALSE
#>  9     3  2001 NA       NA
#> 10     3  2002 FALSE    TRUE
#> 11     3  2003 TRUE     TRUE
#> 12     3  2005 NA       NA

A: If you do want to fight the way dplyr wants to work, here's a non-pivot solution :)
library(dplyr)
library(purrr)
library(stringr)

df %>%
  mutate(year = as.numeric(year)) %>%
  left_join(., mutate(., year = year + 1), by = c('id', 'year'), suffix = c('', '_previous')) %>%
  rowwise() %>%
  mutate(dests = str_extract_all(dest_prod, '\\w{3}_'),
         prods = str_extract_all(dest_prod, '_\\w+'),
         new_dest = max(map_int(dests, \(x) !str_detect(dest_prod_previous, x))),
         new_prod = max(map_int(prods, \(x) !str_detect(dest_prod_previous, x)))) %>%
  select(-c(dests, prods, dest_prod_previous)) %>%
  ungroup()

#> # A tibble: 12 × 5
#>    id     year dest_prod                  new_dest new_prod
#>    <chr> <dbl> <chr>                         <int>    <int>
#>  1 1      2000 FRA_coke                         NA       NA
#>  2 1      2001 FRA_coke                          0        0
#>  3 1      2002 USA_coke                          1        0
#>  4 1      2003 FRA_coke+USA_coke                 1        0
#>  5 2      2002 FRA_coke                         NA       NA
#>  6 2      2003 SPA_ham                           1        1
#>  7 2      2004 FRA_coke+SPA_ham                  1        1
#>  8 2      2005 GER_coke                          1        0
#>  9 3      2001 CHN_water                        NA       NA
#> 10 3      2002 CHN_oil                           0        1
#> 11 3      2003 CHN_water+CHN_oil+FRA_coke        1        1
#> 12 3      2005 CHN_water+CHN_oil+FRA_coke       NA       NA


Q: Passar o html da página via GET Ajax Olá,
estou tentando baixar um arquivo excel passando o html da página, porém ao tentar enviar o html, ele está passando como null.
Ajax
function exportarExcel() {
    var html = $("body").html();
    $.ajax({
        url: location.href = '@Url.Action("ExportExcel")',
        type: 'get',
        data: {
            Html: html,
        },
    });
}

Controller
    [ValidateInput(false)]
    [HttpGet()]
    public void ExportExcel(string Html)
    {
        Classes.Export.ToExcelHtml(Response, Html);
    }

Export
        public static void ToExcelHtml(HttpResponseBase Response, string html)
    {
        Response.ContentType = "application/x-msexcel";
        Response.AddHeader("Content-Disposition", "attachment;filename = Faturamento.xls");
        Response.ContentEncoding = Encoding.UTF8;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        Response.Write(html);
        Response.End();
    }

A: Via GET não vai ser possível, mude seu javascript e a controller para trabalhar com post e utilize um FileResult para fazer o download do arquivo.
function exportarExcel()
{
var html = $("body").html();
    $.ajax({
        url: '@Url.Action("ExportExcel")',
        type: 'post',
        data: { Html: html },
        success: () => { window.location.href = '@Url.Action("Download")' }
    });
}

Controller
[ValidateInput(false)]
[HttpPost]
public void ExportExcel(string html)
{
    //Classes.Export.ToExcelHtml(Response, Html);

    byte[] fileBytes = Encoding.UTF8.GetBytes(html);
    string fileName = "Faturamento.xls";
    TempData["Download"] = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

[HttpGet]
public FileResult Download()
{
    return TempData["Download"] as FileResult;
}


Q: Quando eu for instanciar uma classe eu preciso realizar um 'delete' após o uso do objeto mesmo que a classe possua um destrutor? Se eu instancio uma classe e gero um objeto a partir dele obrigatoriamente eu tenho que desalocar a memória daquele objeto no final do seu uso, certo? Mas se a classe que deu origem ao meu objeto possuir um destrutor será necessário realizar um delete no objeto mesmo que a classe com seu destrutor já faça o trabalho de desalocação de memória?

A: Depende.
Se alocar no stack então não precisa, está é uma memória automática e o compilador gera código próprio que desalocará o que for preciso.
Se a alocação for no heap precisa saber se a classe faz isso por você, se ela fizer, não é necessário fazer algo a mais.
Se você escreveu a classe então precisa analisar se não é o caso de incluir dentro dela o gerenciamento da memória. O destrutor pode indicar que faça a liberação da memória, mas isto não é garantido, precisa ver a documentação. Se ela faz então você não deve liberar a memória manualmente.
Ainda se for no heap pode usar um ponteiro inteligente, aí ele se encarrega de desalocar pra você. É o mais adequado sempre que a classe deixar para o programador cuidar do gerenciamento de memória.
Se nada disso for feito, sim, precisa desalocar a memória sob pena de provocar um vazamento de memória. Não é fácil fazer certo em muitos casos, e mesmo nos triviais é fácil cometer algum deslize.


Q: MYSQL:filter query based on user input Maybe this is a simple question but i am struggled to find the answer.
I am trying to implement a filter feature based on category,subject and medium fields value from the table art.
that means if user select only category the result will be the query
SELECT * FROM ART WHERE category=val
if user select category and subject it should be  SELECT * FROM ART WHERE category=val AND subject=val
and so on
But i don't how i dynamically build this query one approach is write all possible combinations query and  execute based on conditions but i don't think its a good approach

A: $sql=" SELECT * FROM ART where 1=1   ";

if(!empty($category) {
    $sql.=" and category= $value";
}

if(!empty($subject) {
  $sql.=" and subject= $value";
}

if(!empty($medium) {
   $sql.=" and medium= $value";
}

where 1=1 is just to keep the syntax correct else you need to have some login to add where accordingly as you can't add where in all three checks (will make incorrect sql string).
Read about sql injection. Use parameter binding to add parameter, this is just for you to get an idea, this will work but is vulnerable to sql injection

A: Try all the filters in the where condition with OR not AND as shown below
SELECT * FROM ART WHERE category=val OR subject=val OR medium=val;


Q: Decrpyting using pkcs#11 tool I'm trying too encrypt and decrypt using pkcs#11-tool
echo 'Hello word !' | openssl pkeyutl -encrypt -pubin \
                                                   -inkey pub.pem \
                                                   -pkeyopt rsa_padding_mode:oaep \
                                                   -pkeyopt rsa_oaep_md:sha512 \
                                                   -pkeyopt rsa_mgf1_md:sha512 \
                                                   -out encrypted.data

This work find but trying to decrypt it fail
pkcs11-tool --module  /usr/local/lib/softhsm/libsofthsm2.so --decrypt \
                                                   --mechanism RSA-PKCS-OAEP \
                                                   --input-file encrypted.data \
                                                   --label keyp \
                                                   --hash-algorithm SHA512 --pin Jojo

I'm having this error :
Using slot 0 with a present token (0x607f2e7f)
Using decrypt algorithm RSA-PKCS-OAEP
OAEP parameters: hashAlg=SHA512, mgf=MGF1-SHA512, source_type=0, source_ptr=(nil), source_len=0
error: PKCS11 function C_DecryptInit failed: rv = CKR_ARGUMENTS_BAD (0x7)
Aborting.

I'm following this tutorial : https://docs.nitrokey.com/nethsm/guides/pkcs11_with_pkcs11-tool and can't what wrong.


Q: Aligning multiple divs side by side I am trying to align multiple divs side by side.
I have searched stackoverflow and based my code on this: How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/.
I've played around with it, and ended up with this css:
    .frontpageBoxLeft, .frontpageBoxRight {
  border-radius: 5px;
  border-color: lightgrey;
  background: #ffffff;
  height: 150px;
}

.frontpageBoxLeft {
  margin-bottom:15px;
  width: 750px;
  min-height: 100px;
  position: relative;
}

.frontpageBoxRight {
  width: 320px;
  float: right;
  height: 300px;
  position: relative;
  vertical-align: top;
}

.frontpageBoxContainer {
    width: 70%;
    height: 500px;
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

and this html:

NEWS FEED

     et eksempel på en kasse1

     et eksempel på en kasse2

     et eksempel på en kasse3

     et eksempel på en anden kasse

The result is this:
div alignment
I would like to be able to put multiple divs on the left side, and multiple divs on the right side.
Right now the code works fine when iam only using one right and one left div, but with multiple divs it act like in the picture.
Best regards.

A: I guess this might help you

div{
  width: 48%;
  height: 100px;
  background-color: red;
  float: left;
  margin: 1%;
}

or this one

div{
  width: 23%;
  height: 100px;
  background-color: red;
  float: left;
  margin: 1%;
}

A:

.frontpageBoxLeft,
.frontpageBoxRight {
  border-radius: 5px;
  border-color: lightgrey;
  background: #ffffff;
  height: 150px;
}

.left-container {
  float: left;
  width: 750px;
}

.frontpageBoxLeft {
  margin-bottom: 15px;
  width: 750px;
  display: inline-block;
  min-height: 100px;
  float: right;
  position: relative;
  outline: 1px solid red;
}

.frontpageBoxRight {
  width: 540px;
  float: right;
  height: 300px;
  position: relative;
  vertical-align: top;
  outline: 1px solid red;
}

.frontpageBoxContainer {
  width: 1300px;
  height: 500px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

NEWS FEED

     et eksempel på en kasse1

     et eksempel på en kasse2

     et eksempel på en kasse3

     et eksempel på en anden kasse

A: Put float: left to the .frontpageBoxLeft selector will solve the problem.

A: *

*Try set the frontpageBoxContainer to position:relative

*Float the left AND the right Containers.

*set left or right Offset to the divs you want to align.


Q: Parse 6-byte IP/Port string to in_addr structure in c I'm trying to build a little bittorrent client to store data in the bittorrent dht.
Since much of the bittorrent functionality is not needed I'm trying to stay as simple as possible, since it only needs to function in a couple of limited use cases.
I'm trying to parse information about new nodes from a message, which I get from a bootstrap node. The information about each node is 26-bytes long. 20-bytes is node ID, 4 bytes IP address and 2 bytes port number. All the info is in binary.
I want to store the ip address and port number in a struct (myNode) which has got an in_addr parameter for the IP and unsinged short for the port.
typedef struct myNode {
   unsigned char id[21];
   struct in_addr ip;
   unsigned short port;
} myNode;

The parsing of the ID works fine. But the parsing of the IP and port fails. Sometimes it works, mostly it does not and never both work at the same time. I think there might be something wrong with the bitwise shift I'm doing, but I don't know what. When I printf the IP in hex after parsing I mostly get something like this:

0xffffed3a

So it seems like the first to shifts are not working. The other bits are correct. What am I doing wrong?
int get_nodes_from_find_node(char *msg, myNode *setme) {
  char *fnstr = "nodes";
  char *pos, *ptr;
  long lenNodes;
  int nrNodes, i = 0, k = 0;

  pos = strstr(msg, fnstr);           // Find nodes section.
  if(pos == NULL) { return -1; }
  pos += strlen(fnstr);

  lenNodes = strtoul(pos, &ptr, 10);  // Save the length of the nodes section in lenNodes
  nrNodes = lenNodes / 26;            // Get number of nodes, about which info is delivered.
  pos = ptr+1;                        // Set pos to first node.

  while(nrNodes > 0) {
    for(k=0;k<20;k++,pos++) {       // First 20 bytes are ID.
        setme[i].id[k] = *pos;
    }
    setme[i].id[20] = '\0';         // Make ID a Null-terminated string.

    setme[i].ip.s_addr = (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3);   // Next 4 bytes are IP in network byte order.
    pos += 4;

    setme[i].port = (*pos << 8) | *(pos+1);  // Last 2 bytes are port.
    pos += 2;

    nrNodes--;
    i++;
  }
  return 0;
}

A: Your problem is in (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3).
If any of the values in pos[0,...,3] is negative, then the entire expression is negative.


Q: BEM Convention with SASS - Problem to understand I am a beginner in front-end and I try to assimilate the notions of SASS and BEM.
I have great difficulty understanding the naming convention and how it is organized with SASS.
I wrote a product section which contains three div (column) which themselves contain child elements.
I have no idea how to organize the names well. For example the img are children of product__preview, but I'm tempted to name the class product__img .... but it looks like it's not correct? If there are several images in the product section but some of them must be different, how do we handle the names? (product__img seems to be too vague).
Do I need to add a product__preview__img class for special cases?
Can you help me correct this block so that I understand the naming correctly?
Thank you in advance!

Super Mario Odyssey

 Date:  2017

 Story:  Super Mario Odyssey[b] is a platform game developed and published by Nintendo for
            the Nintendo Switch on October 27, 2017. An entry in the Super Mario series, it follows Mario and Cappy,
            a sentient hat that allows Mario to control other characters and objects, as they journey across various
            worlds to save Princess Peach from his nemesis Bowser, who plans to forcibly marry her. In contrast to
            the linear gameplay of prior entries, the game returns to the primarily open-ended, 3D platform gameplay
            featured in Super Mario 64 and Super Mario Sunshine.[1]

 Review:

        <button class="product__btn btn-orange-tiger">Add to cart</button>
        <button class="product__btn btn-orange-tiger">Go to cart</button>
        <button class="product__btn btn-orange-tiger">Keep buying</button>

A: The structure you have now is perfectly fine and valid. Therefore, you would not want to use product__preview__img. You would be defeating the purpose of BEM if you were to create those kind of selectors as you would be creating complex/unorganised code. If you feel the name is vague, you could try product__img-preview as this still ties in with the block element selector and not a stacked block element selector.
One more thing I could suggest since you are using BEM and to utilise it fully, is to change your modifier class names for the buttons you have to product__btn product__btn--orange as it will help keep your code maintainable as you have the block element selector along side a modifier which is the orange button in this case.
.product {
  ...
  &__features {
    ...
  }
  &__btn {
     ...
     &--orange {
       ...
    }
  }
}

As you can see, the deepest nesting level is the modifiers of the block element.


Q: How to configure spring controller to use different objectMapper for the response (serialization) I configured my own ObjectMapper for my SpringBoot application, Let say the object mapper is something like below (simplified):
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

Since the ObjectMapper is a singleton, all my REST Controller use that same ObjectMapper.
But, there is some controller that I want to ignore the null value, but I want to keep the rest of my controller to send the null value response.
Is there a way to configure it? So the best result is I can configure something like this:

*

*Controller A,B,C -> ObjectMapper X (ignore null value)

*Controller D -> ObjectMapper Y (ignore empty value)

*Default (all other controller) -> ObjectMapper Z (return null value)

Requirement Note:

*

*I can't change the POJO since it's autogenerated, and I don't want to update the codegen lib or the mustache template for this.

*Specific content negotiation is not an option

A: In addition to your ObjectMapper annotated with @Primary
you can configure more ObjectMappers qualified with bean names of your choice.
@Bean
@Primary
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}

@Bean("mySpecialObjectMapper")
public ObjectMapper anotherObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper()
            /*  do some other configuration */;
    return objectMapper;
}

Then you can refer to them in your controllers like this:

*

*Just giving @Autowired will inject the primary ObjectMapper.

*Giving @Autowired together with @Qualifier("anyName") will inject
the ObjectMapper configured with @Bean("anyName")
@Autowired
private ObjectMapper objectMapper;

@Autowired
@Qualifier("mySpecialObjectMapper")
private ObjectMapper otherObjectMapper;

A: Maybe you just need to use @JsonInclude(JsonInclude.Include.NON_NULL). Try to fix it in the response model level.


Q: how to hide blinking cursor in input text? I want to make something which would look like a select input but is actually not, here are the steps.
I made an <input type="text">.
I added a background-image, which will show a "select arrow", giving the impression that it's a select box.
I added a default value to this input.
There will be a hidden div which will SlideDown() right under this input when I click on it.
I tried the read only thing so that the value cannot be changed, but the blinking cursor will show up.
If I use disabled, the blinking cursor will not show up, but the .click() or .focus function in jQuery will not work. The drop down menu will not SlideDown().
How can I make it clickable while not showing the blinking cursor?
Here's the code

        Secret Question

        <input type="text" class="inputselect" id="secretquestion" name="secretquestion" value="Choose a Secret Question" tabindex=10 />

            test

CSS
.selectoptions
{
    display: none;
    background-color: white;
    color: rgb(46,97,158);
    width: 250px;
    margin:auto;
    border-style: solid;
    border-width:1px;
    border-color: rgb(46,97,158);
    font-size: 14px;
    text-align: center;
}

.inputselect {
    color: white;
    cursor: pointer;
    background-image: url('inputselect.png');
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left:10px;
    padding-right:-10px;
    width:240px;
    border-style: solid;
    border-color: rgb(46,97,158);
    border-width: 1px;
}
.inputselect:hover {
    outline:none;
    color:aqua;
    cursor: pointer;
    background-image: url('inputselecthover.png');
}
.inputselect:focus {
    outline:none;
    color:aqua;
    cursor: pointer;
    background-image: url('inputselecthover.png');
}

A: I think this is a perfect solution: make the input wide enough, align right to screen right, thus make cursor and content locate at the outside of the screen, while it's still clickable

A: The color of the cursor matches the color of the text.
<input type="text" style="color: transparent">

If you actually want to show text in the input box (my, some people are needy), you can use a text shadow.


Q: A curve from a known family of curves for data normalisation Background:
I have been working with a system which so far required precise and manual calibration of the input variable $x$ to work and I now want to auto tune it. So I am looking for a normalizing $f$ which when operated on $x$ can be directly fed to the system. With my experience on the system, I have some guidelines that $f$ must adhere to for the system to work properly. I am from electrical background and am aware of only limited number of curves such log, sigmoid, tanh or gamma curves but want to know if any other curve better serves my purpose.
Details:
The input to the environment is a variable $x \in (800,10000)$. I want have a normalising function $f: (800,10000) \rightarrow (10,60)$, such that input to my system is $f(x)$ rather than $x$. Please note that this does not mean that 10000 should map to 60. It just means that value should be within this limit. For example if the input range (800,10000) is mapped between (20,30) that is perfectly fine.
I now list 3 guidelines which must be exhibited by $f$. Guidline A) Function must be increasing and continuous like $log(x)$. It should not be piece-wise defined. Guidline B) The function should be a squashing function such that a large change in $x$ should not cause much change in $f(x)$. Basically the variation in $f(x)$ should be much less than the variation caused in $x$. For example if $f(1000)=10$ then $10 < f(3000) < 11$ (output values are just for illustration sake and actual behavior may vary). Guidline C) Squashing should NOT be such that to kill perturbations in $x$, $f(x)$ value is very low. For eaxample $f(800)=2.3$ and $f(2000) = 2.8$ is not acceptable due to low values. However, $f(800)=12.3$ and $f(2000) = 12.9$ is good.
Some solutions:

*

*$log_{2}(x)$ follows A) and C) but does not strictly follow B). Increasing $x$ from $1000$ to $2500$, $log_{2}(x)$ shows little large variation.

*$log_{10}(x)$ strictly follows A) and B) but the output values are low around 3. They should have been at least 10. $f(x) = 10 + log_{10}(x)$ satisfies B) and C) but unfortunately the system can't admit a bias term. This because the input $x$ encapsulates the environment. So tomorrow if I shift my system to some other environment, the fixed bias term also needs to be changed which is what I do not want. The way $x$ is calculated is such that if $x$ is low, $f(x)$ should also be low and vice versa. But if I use a bias term, it dictates a minimum value which may not be required by the system. Therefore I prefer a solution that depends on fractions, power, multiplication, gamma curves, log, hyperbolic tan, hyperbola, etc functions that directly depend on input.

*$f(x) = [log_e (x^{1/2})]^2$ seems to me a much better option than above two. Another alternative is to use something like $5\times log_e[log_{10}(x)]$ but output value is little low.
I am from an electrical background and do not know of many normalizing curves in mathematics. If there is a continuous, smooth, increasing, non piece-wise, squashing function with output at least 10 for the given range of $x$ without admitting any bias term please let me know.
Thankyou for any solution or input in this regard,
Mohit


Q: Facebook Integration in IOS to fetch users data I had registered my application in facebook developers. I got app id and client key.
Is there any tutorials for an application to fetch users data?
Any third parties suggested ?

A: This tutorial is the best for me http://www.raywenderlich.com/44640/integrating-facebook-and-parse-tutorial-part-1

A: Why third party? What's wrong with Facebooks documentation? It's perfectly clear
https://developers.facebook.com/docs/ios/getting-started


Q: Word Collage-Cloud with Tikz I recently found this picture
And I wanted to do something like that with tikz.
Can someone do to me a MWE?


Q: wxPython: How to Show status/progress window and update the progress from another python code? I have a regular python app (not wx) , and i want to add a wxStatusWindow (Guage Class) in order to show the progress in my App.
There are many examples in web for wxGuage /Status windows but in all examples the progress is handled within the wxFrame.
How can i call the statusWIndow from my python code while the python code is running ?
I did some reading...is it running on separate thread??
I will appreciate an example...how can i do that?
alternatively..I though of just opening a wxDialog from my app and showing info about the progress (and than closing it and raising another wxDialog with new info)...but again..
I need the message to be displayed and in parallel the code in my app to continue running..and than to be able to close the message box from my python app
any Idea's?
code examples?
10x
Yodash


Q: Problem when I try to move socket creation code to another activity? I have an android application created by eclipse.
This application works as a client connecting to a server wirelessly across a socket connection.
I have a problem with the code of socket creation.
When I try to move the code from an activity to another in my application, then it doesn't work.
Here is the first activity, where the code works:
public class MyNewAndroidActivity extends Activity {
    protected Socket socket;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button button_connect = (Button) findViewById(R.id.button1);
        final Button button_disconnect = (Button) findViewById(R.id.button2);
        final Button b_forward = (Button) findViewById(R.id.b_forward);
        final Button b_backward = (Button) findViewById(R.id.b_backward);
        final Button b_right = (Button) findViewById(R.id.b_right);
        final Button b_left = (Button) findViewById(R.id.b_left);
        final Button b_stop = (Button) findViewById(R.id.b_stop);

        button_connect.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                try {
            // Create socket with time out
            //192.168.1.76
        // my code which I want to transfer it.
        int port = 2005;
    SocketAddress sockaddr = new  InetSocketAddress("192.168.1.15", port);

                      socket = new Socket();
                      int timeoutMs = 2000;
                      socket.connect(sockaddr, timeoutMs);

                    }

            catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                catch (SocketException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

when I convert it to method in another activity then it doesn't work:
public class IBMEyes extends Activity implements SensorListener{
    protected static Socket socket;
    final String tag = "MyProject";
    String state ="off";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        setContentView(R.layout.main);

       Button b_connect = (Button) findViewById(R.id.button1);
        b_connect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

        SocketConnect();
}
        });

// here is my code that I've transferred it.
    public void SocketConnect() {
        // TODO Auto-generated method stub
        try {

       int port = 2005;
    SocketAddress sockaddr = new  InetSocketAddress("192.168.1.15", port);

              socket = new Socket();
              int timeoutMs = 2000;
              socket.connect(sockaddr, timeoutMs);

            } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }

    }


Q: How to fix "unhashable type: 'list'" error I am trying to run a function to get column name corresponding to 2 in data frame
Input Dataframe:
df1
A|B|C|D

1|0|2|4

2|9|1|3

Output DataFrame:
A|B|C|D|new|

1|0|2|4|C|

2|9|1|3|A|

I have made the function but for some reason I am getting TypeError: ("unhashable type: 'list'", 'occurred at index 0')
def colname(x):
    b = (df1.loc[x]==2)
    return b.idxmax()

df1["new"]=df1.apply(colname,axis=1)


Q: JSF : convertNumber MonetaryAmount not working in dataTable I wanted to display MonetaryAmounts inside a dataTable. Curiously it doesn't work : the currencyCode appears to be empty (but not null).
Note : it works outside a dataTable for a single MonetaryAmount.
Tested with wildfly 25.0.1 (Mojarra 2.3.14.SP04) and Payara5
The bean :
@Named("dtBasicView")
@ViewScoped
public class BasicView implements Serializable {

    private List<MonetaryAmount> amounts;

    @PostConstruct
    public void init() {
        amounts = new ArrayList<>();
        CurrencyUnit unit = Monetary.getCurrency("EUR");
        MonetaryAmount amount = Monetary.getDefaultAmountFactory().setCurrency(unit).setNumber(200).create();
        amounts.add(amount);
    }

    public List<MonetaryAmount> getAmounts() {
        return amounts;
    }
}

Facelet :
<h:dataTable var="item" value="#{dtBasicView.amounts}" >
    <h:column>
       <f:facet name="header">Amount</f:facet>
       <h:outputText value="#{item.number}">
            <f:convertNumber currencyCode="#{item.currency.currencyCode}" type="currency" />
       </h:outputText>
    </h:column>
</h:dataTable>

It blows in java.util.Currency because the currencyCode is empty :
if (currencyCode.length() != 3) {
   throw new IllegalArgumentException();
}

Here is the error.
17:17:58,946 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-11) Error Rendering View[/ui/data/datatable/basic.xhtml]: javax.faces.convert.ConverterException: j_idt303:j_idt305:0:j_idt307: Could not convert '200' to a string.
        at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:686)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:491)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:509)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:330)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:143)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.column.Column.renderChildren(Column.java:90)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeCell(DataTableRenderer.java:1356)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRow(DataTableRenderer.java:1272)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRows(DataTableRenderer.java:1179)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1119)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1072)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:401)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:331)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.render(DataTableRenderer.java:106)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:97)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
        at javax.faces.api@3.0.0.SP04//javax.faces.render.Renderer.encodeChildren(Renderer.java:152)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:566)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1647)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
        at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
        at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
        at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
        at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
        at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
        at javax.faces.api@3.0.0.SP04//javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:88)
        at javax.faces.api@3.0.0.SP04//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
        at javax.faces.api@3.0.0.SP04//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
        at deployment.primefaces-showcase-11.0.0.war//org.primefaces.showcase.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:41)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
        at org.wildfly.security.elytron-web.undertow-server@1.10.0.Final//org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler.lambda$handleRequest$1(ElytronRunAsHandler.java:68)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.FlexibleIdentityAssociation.runAsFunctionEx(FlexibleIdentityAssociation.java:103)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.Scoped.runAsFunctionEx(Scoped.java:161)
        at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.Scoped.runAs(Scoped.java:73)
        at org.wildfly.security.elytron-web.undertow-server@1.10.0.Final//org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler.handleRequest(ElytronRunAsHandler.java:67)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.core@2.2.12.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
        at io.undertow.core@2.2.12.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
        at org.wildfly.security.elytron-web.undertow-server-servlet@1.10.0.Final//org.wildfly.elytron.web.undertow.server.servlet.CleanUpHandler.handleRequest(CleanUpHandler.java:38)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
        at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:280)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:79)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:134)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:131)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:260)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:79)
        at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:100)
        at io.undertow.core@2.2.12.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
        at io.undertow.core@2.2.12.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:852)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
        at org.jboss.xnio@3.8.4.Final//org.xnio.XnioWorker$WorkerThreadFactory$1$1.run(XnioWorker.java:1280)
        at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.configureCurrency(NumberConverter.java:775)
        at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:674)
        ... 86 more
Caused by: java.lang.IllegalArgumentException
        at java.base/java.util.Currency.getInstance(Currency.java:315)
        at java.base/java.util.Currency.getInstance(Currency.java:296)
        ... 92 more

Error with Payara5
[2022-11-30T18:18:45.713+0100] [Payara 5.2021.3] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=83 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1669828725713] [levelValue: 900] [[
  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.IllegalArgumentException
        at java.base/java.util.Currency.getInstance(Currency.java:315)
        at java.base/java.util.Currency.getInstance(Currency.java:296)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at javax.faces.convert.NumberConverter.configureCurrency(NumberConverter.java:775)
        at javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:674)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:491)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:509)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:330)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:143)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)


Q: What is the difference between Child and Element of a container? What is the difference between Child and Element of a container?
Why do the containers like Spark VGroup have different sets of methods for both Child and Elements?
Can anyone explain me the difference in the simplest way?
Thanks in advance..

A: The addChild method is used for adding a DisplayObject, which is a method from pure actionscript. So you would typically add Sprite, MovieClips etc. Widely used in action script based projects
The Flex classes like VGroup are written on top of the base actionscript classes, and therefore have an extra addElement method to be able to add an IVisualElement, which can also be an FXG for example, or other Flex based components such as UIComponent, Group etc.
However, I doubt that calling addChild on a VGroup will actually provide desired results and may result in errors.
Hope this answers your question.

A: The type IVisualElement and with it all the *Element methods from IVisualElementContainer were introduced in Flex SDK 4.0 as part of the spark layout and lifecycle features.
You are still free to build your own components based on UIComponents without having the spark features and only with the *Child methods.
All classes that extend DisplayObjectContainer of course inherit the *Child methods but in classes like Group (and SkinnableComponent) those methods have been overwritten to throw an error, as one needs to use the *Element methods to use the Spark features.
As Flex 4 supports using the MX layout as well as the Spark layout (there are options to use only one of them or both side by side when compiling) those methods could not be marked as deprecated in Group and SkinnableComponent, wich would at least trigger a compiler warning instead of a runtime error.


Q: How can I list the all Discord servers ID where my bot are in the console? | discord.js I tried on googling but all of the errors was "is not a function", that's because i'm using discord.js V12?
I can't find it on google, there is less question about this one. This was my code.
var serverArray = client.guilds.array();
for(i = 0; i < serverArray.length; i++) {
    console.log("Server ID: " + serverArray[i].id);
}

A: client.guilds.cache.forEach(guild => {
  console.log(`${guild.name} | ${guild.id}`);
})

A: let clientguilds = client.guilds.cache()
console.log(clientguilds.map(g => g.id) || "None")

This should do the trick! It's going to cache all the guilds your bot is in and then it will map the guilds as an array. We then get the id of each guild or, if it's not in any guilds "none".


Q: Can someone explain to me on runQueryOnBackgroundThread? Can someone just explain to me what is runQueryOnBackgroundThread as I already read through some sources but still not understand with it?
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint){
    FilterQueryProvider filter = getFilterQueryProvider();
    if (filter != null){
        return filter.runQuery(constraint);
    }

    Uri uri = Uri.withAppendedPath(
                ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(constraint.toString()));

    return content.query(uri, CONTACT_PROJECTION, null, null, null);
}

A: A handle of my Activity in the Adapter and the runQuery call in the filter makes a call to startManagingCursor on the Activity whenever the runQuery is called. This is not ideal because a background thread is calling startManagingCursor and also there could be a lot of cursors remaining open until the Activity is destroyed.
I added the following to my Adapter which has a handle on the Activity it is used within
@Override
public void changeCursor(Cursor newCursor) {
Cursor oldCursor = getCursor();
super.changeCursor(newCursor);
if(oldCursor != null && oldCursor != newCursor) {
    // adapter has already dealt with closing the cursor
    activity.stopManagingCursor(oldCursor);
}
activity.startManagingCursor(newCursor);
}

This makes sure that the current cursor used by the adapter is also managed by the activity. When the cursor is closed by the adapter management by the activity is removed. The last cursor held by the adapter will be closed by the activity by way of it still be managed by the activity.


Q: How to unmount webcomponent used inside react component? I am using web component inside react component. when I unmount react component, it seems web component inside react component is not being unmounted properly, because when I mount the react component again, webcomponent props update method is being called and then throws error

Uncaught TypeError: Cannot read property 'appendChild' of null

I am using skate js to create webcomponent.
How to properly unmount the web component. please help, I would always be thakful.
Please let me know if any more information is required.

A: I solved this. The Widget component was not being unmounted properly. I have to remove it forcefully form dom using
Mozilla docs removeChild
After that it works fine.


Q: How can I print/echo/get all attributes from each of the objects in this code? How can I print/echo all properties/attributes values from all Country objects in this code? I thought of using 'foreach' but I don't know the sintaxis.
The echo statement is in the last line of code.
Thanks!
    <?php

   class Country {
  public $nombre;
  public $poblacion;
  public $idioma;
  public $moneda;
  public $economia;
  public $deporte;

}

$country1 = new Country ();
$country1->nombre = 'Argentina';
$country1->poblacion = '40 millones';
$country1->idioma = 'Castellano';
$country1->moneda = 'Peso argentino';
$country1->economia = 'Agro';
$country1->deporte = 'Futbol';

$country2 = new Country ();
$country2->nombre = 'USA';
$country2->poblacion = '200 millones';
$country2->idioma = 'Ingles';
$country2->moneda = 'Dolar estadounidense';
$country2->economia = 'Multiples industrias';
$country2->deporte = 'Basket,Baseball,Futbol Americano';

$country3 = new Country ();
$country3->nombre = 'Alemania';
$country3->poblacion = '50 millones';
$country3->idioma = 'Aleman';
$country3->moneda = 'Euro';
$country3->economia = 'Multiples industrias';
$country3->deporte = 'Futbol';

$countries = [$country1,$country2,$country3];

foreach ($countries as $country)
{

  **echo $country->¿? "
";**

}

A: foreach ($countries as $country) {
    foreach ($country as $k => $v) {
        echo $k . ': ' . $v . '
'; // nombre: Argentina ...
    }
}


Q: Defining derivatives of integrals I am trying to define a derivative of a function which is itself an integral.  The function GaussInt[f_,x_] is the integral over f (a function of x) with respect to the measure $\exp(-x^2/2)/\sqrt{2\pi}$.  I prefer to use the function GaussInt rather than write out the integral to prevent mathematica from attempting to solve the integral (which it can't do, but it spends a lot of time trying).  The problem is that GaussInt doesn't satisfy the usual chain rule.  That is
D[GaussInt[f_,x_], z_]:= GaussInt[D[f,z], z]

but Mathematica uses the chain rule to decide
D[GaussInt[f_,x_], z_] := GaussInt'[f,x] D[f,z]

which usually leads to the wrong answer.
I can get around this by defining my own differentiation operator
Dd[GaussInt[a_,z_],x_] := GaussInt[Dd[a,x], z]

I then have to define all the usual rules for Dd.  Although this works its is rather inelegant.  My problem is I don't know how to robustly switch off the chain rule for differentiation when applied to my function GaussInt
.  Any ideas?

A: You could use Inactive :
Inactive[Integrate][f[x] Exp[-x^2/2]/Sqrt[2 π], x]

which leaves the integral unevaluated (and formats the output as an integral).  Then it plays nicely with derivatives:
D[%, x]


Q: jquery-ajax-php: error message not shown on other empty input fields after it's updated I’m trying to validate post data using jquery and ajax for my registration form where an error message will be shown below each input fields. I manage to get the error message initially. But when some of the empty fields were updated with an input, the error message does not shown in the remaining empty field. Would somebody please be kind to point out if is there is any problem with below script?

regsiter.php

        <form action="register-handler.php" method="POST" id="reg-form">

            Username:

            <input type="text" name="username" id="username"  autocomplete="off">

            Password:

            <input type="password" name="password" id="password" >

            Confirm Password:

            <input type="password" name="conf_pass" id="conf_pass" >

            <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
            <input type="submit" value="submit">

        </form>

register-handler.php
<?php
require_once 'core/init.php';
if(Input::exists()){
    if(Token::check(Input::get('token'))) {

        $validate = new Validate();
        $validation = $validate->check($_POST, array(
            'username' => array(
                'required' => true,
                'min' => 2,
                'max' => 20,
                'unique' => 'users'
            ),
            'password' => array(
                'required' => true,
                'min' => 6
            ),
            'conf_pass' => array(
                'required' => true,
                'matches' => 'password'
            )
        ));

        if($validation->passed()) {
            //register user
            $user = new User();

            $salt = Hash::salt(32);

            try {

                $user->create(array(
                    'username' => Input::get('username'),
                    'password' => Hash::make(Input::get('password'), $salt),
                    'salt' => $salt
                ));

                Session::flash('home', 'You have been registered and can now log in!');
                Redirect::to('index.php');

            } catch(Exception $e) {
                die($e->getMessage());
            }
        }
        else {
            //output errors
            header('Content-Type: application/json');
        echo json_encode($validation->errors());
            }
        }
    }
}
?>

validate.php
<?php
class Validate {
    private $_passed = false,
            $_errors = array()

    public function check($source, $items = array()) {
        foreach ($items as $item => $rules) {
            foreach ($rules as $rule => $rule_value) {

                $value = trim($source[$item]);
                $item = escape($item);

                if ($rule === 'required' && empty($value)) {
                    $this->addError($item, "{$item} is empty");
                } else if (!empty($value)) {
                    switch ($rule) {
                        case 'min':
                            if (strlen($value) < $rule_value) {
                                $this->addError($item, "{$item} must be a minimum of {$rule_value} characters.");
                            }
                            break;
                        case 'max':
                            if (strlen($value) > $rule_value) {
                                $this->addError($item, "{$item} must be a maximum of {$rule_value} characters.");
                            }
                            break;
                        case 'matches':
                            if ($value != $source[$rule_value]) {
                            $this->addError($item, "{$rule_value} must match {$item}");
                            }
                            break;
                    }
                }
            }

        }
        if (empty($this->_errors)) {
            $this->_passed = true;
        }
        return $this;
    }

    private function addError($key, $error) {
        $this->_errors[$key] = $error;
    }

    public function errors() {
        return $this->_errors;
    }

    public function passed() {
        return $this->_passed;
    }
}
?>


Q: ¿Como separo una columna  en otras mediante comas? tengo el siguiente problema:
Tengo un Df con datos de docentes y en una columna las áreas en las que trabajan, que son varias. Estas áreas están separadas por comas por ejemplo "Matemáticas, programación, estadística aplicada" etc.
Entonces hice el siguiente código
df %>%
  separate(Areas, into = c("linea1", "linea2", "linea3", "linea4", "linea5",
  "linea6", "linea7","linea8", "linea9", "linea10", sep = '\\,' ))

Pero esto, por ejemplo para alguien que tiene en la columna Areas
Teoría de Control Óptimo, Teoría de Juegos me lo separa de la siguiente manera
teor  | a   |de   | control    | ptimo   | teor    | a   | de   | juegos   | NA

con la división del | me refiero a que me lo divide en varias columas cuando yo solo esperaria que me lo divida en dos:
Teoría de Control Óptimo   | Teoría de Juegos | NA | NA | NA | NA |NA |NA | NA |NA |

tambien intenté el siguiente codigo
scan(text = df$Areas, sep = ",", what = "")

Pero esto me devuelve un vector y a mi me gustaría tenerlo en el df para convertirlos a factores y poder contarlos y graficarlos y cosas así
Me podrían ayudar por favor
Gracias de antemano


Q: setting low rlimit_nproc value doesn't allow even a single fork I am trying to use setrlimit to limit the number of processes a program can create. Here is my code:
struct rlimit limiter;
getrlimit( RLIMIT_NPROC, &limiter );
limiter.rlim_max = limiter.rlim_cur = 10;
setrlimit( RLIMIT_NPROC, &limiter );

int val = fork();
printf( "Error number %d\n", errno ); //gives 11
if( val == -1 ) {
    printf( "Fork failed\n" );
} else if( val ) {
    printf( "parent\n" );
} else {
    printf("child\n" );
}
return 0;

Since the value of rlim_max and rlim_cur is 10, my program should be allowed to fork 10 processes. But right now it is failing even for a single fork call. Though it works if I set the values to around 250. I don't understand why is that. I want a way to limit the number of forks to n.


Q: Silex: How to create a loop in Form The following lines of code get me a Silex Form. One text-field and one checkbox. The text-field contains the name of a team. The checkboxes should contain the username of a user, so that I can add them to the team.
$form = $app['form.factory']->createBuilder(FormType::class)
        ->add('name', TextType::class, array(
            'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 4,'max' => 64))),
            'label' => 'Team Name',
            'required' => 'required',
            'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'value' => $team->data()->name),
            'label_attr' => array('class' => 'label')
        ))
        ->add('players', CheckboxType::class, [
                'constraints' => array(new Assert\NotBlank()),
                'label' => $player->username,
                'attr' => array('class' => 'input-field', 'value' => $player->username),
                'label_attr' => array('class' => 'label')
        ])
        ->add('submit', SubmitType::class, [
            'label' => 'Edit',
            'attr' => array('class' => 'submit'),
        ])
        ->getForm();

I can get my list of users using the following lines:
$user = new User()
$user->getList();

foreach($user->data() as $player){
        ->add('players', CheckboxType::class, [
                'constraints' => array(new Assert\NotBlank()),
                'label' => $player->username,
                'attr' => array('class' => 'input-field', 'value' => $player->username),
                'label_attr' => array('class' => 'label')
        ])
    }

However, I don't know how to combine these two parts, since the $form variable is defined in one 'line' with a ';' at the end. How can I break this $form into parts so that I can loop through my users and add a checkbox for every user?

A: The form is "generated" once you execute ->getForm(); so if you want to add anyfield before generating it, you should finish by ->getForm();
So your code should probably look like:
// add you "static" fields
$formBuilder = $app['form.factory']->createBuilder(FormType::class)
    ->add('name', TextType::class, array(
        'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 4,'max' => 64))),
        'label' => 'Team Name',
        'required' => 'required',
        'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'value' => $team->data()->name),
        'label_attr' => array('class' => 'label')
    ))
    ->add('players', CheckboxType::class, [
            'constraints' => array(new Assert\NotBlank()),
            'label' => $player->username,
            'attr' => array('class' => 'input-field', 'value' => $player->username),
            'label_attr' => array('class' => 'label')
    ])
    ->add('submit', SubmitType::class, [
        'label' => 'Edit',
        'attr' => array('class' => 'submit'),
    ]);

 $user = new User();
 $user->getList();

// then add your "dynamic" fields

foreach($user->data() as $player) {
    $formBuilder->add('players', CheckboxType::class, [
            'constraints' => array(new Assert\NotBlank()),
            'label' => $player->username,
            'attr' => array('class' => 'input-field', 'value' => $player->username),
            'label_attr' => array('class' => 'label')
    ]);
}

// then generate your form
$form = $formBuilder->getForm();


Q: Facebook messenger webview not allow to access camera and audio I am developing a messenger chat bot, user get a doctor consultation url via bot.
Here is the payload I have use
"message": {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "generic",
        "elements": [
          {
            "title": "Dr.ABC has initiaed the call. Click on the Call below to Join.",
            "subtitle": "NOTE: This link will expire in 30 minutes.",
            "image_url": "https://doctorconsult.com/images/doc.jpg",
            "buttons": [
              {
                "type": "web_url",
                "title": "Call",
                "url": "https://doctorconsult.com/patientconversation/665161e3-0f50-4930-aefb-404d5c3f584f",
                "webview_height_ratio": "full",
                "messenger_extensions": true,
                "webview_share_button": "HIDE"
              }
            ]
          }
        ]
      }
    }
 }

this send the web_url for doctor consultation URL ( that need access camera and audio ) when we open up URL in a browser this works, but when I open url using bot button click, it doesn't not allow camera and  audio. How do we allow to access camera and audio to "https://doctorconsult.com/" in messenger web view ?
I am getting permission issue when its loading inside messenger web view when accessing media
navigator.mediaDevices.getUserMedia(this.videoConstraints).then(stream => {
      this.localStream = stream;
      this.localVideoPlayer.srcObject = stream;
      this.localMediaReady = true;
      this.socketService.emitCallingToPatient({
        customerCode: this.conversation.customerCode,
        currentConversationCallId: this.currentConversationCallId
      });
    });

A: That's the expected behavior due to limitations applied to webviews loaded via the in-app-browser/Messenger/Facebook app.


Q: jquery refactor: traversing Here is some awesome code I'd like to make better.
select: function(event, ui)
  {
  jQuery(this).siblings('div.hidden_fields').children('.poly_id').val(ui.item.user)
}

It is part of a select in jquery UI autocomplete.

A: You could try this
jQuery('div.hidden_fields .poly_id',jQuery(this).parent()).val(...);

Remember you can always provide a context to a jQuery Selector
jQuery("someselector", context)


Q: MathGL libmgl.so.7.2.0 not found I have downloaded and compiled MathGL following the instructions on sourceforge without any errors occuring.
When I ran my first test-program:
(The <> brackets in line 1 seem so delete it but they are there in the code)
#include mgl2/mgl.h
    int main(){
    mglGraph gr;
    gr.FPlot("sin(pi*x)");
    gr.WriteFrame("test.png");
}

the compilation with g++ -lmgl went fine.
When trying to run the programm i get:
./a.out: error while loading shared libraries: libmgl.so.7.2.0: cannot open shared object file: No such file or directory
I triple checked to be sure and libmgl.so.7.2.0 is definetely in /usr/local/lib/.
I tried telling g++ this via the -L option but that didn't work either.
Any help would be greatly appreciated

A: g++ -lmgl -lpng /shitfile.cpp -o /shitfile

care friend


Q: How To Append String To Dictionary in Python within Forloop i need to append a value of string to a specific key in dictionary in python within forloop, and if the data in forloop is empty then give the value of empty string which i'm not able to get it right, here is some of the code,
top100 = {}

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    # the value in the title is list of 100 title
    # more like ['title1', 'title2', ...] and so the price [100, 230, ...]

    # how to append each pairs of title and price so i have list of dictionary

    top100['title'].append(title)
    top100['price'].append(price)

print( top100)

output:
KeyError: 'title'

but i need something more like:
top100 = [{'title': 'title1', 'price': 'price1'},
          {'title': 'title2', 'price': 'price2'}
         ]

A: The top 100 variable should be a list, then append a dictionary
top100 = []

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    top100.append({'title':title,'price':price})

print( top100)

A: You need to make top100 a list with many nested dictionaries, with the following code:
top100 = []
for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
    top100.append({'title':title,'price':price})

A: Here for the another version of result
top100 = {'title':[],'price':[]}

for product in product_list:
    title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
    price = product.xpath('div[@class="someClass"]/text()') # LIST of 100

    top100['title'].append(title)
    top100['price'].append(price)

print( top100)

This should output
{'title':[..., ..., ... ],'price':[..., ..., ...]}

A: thanks for the answer i was able to find my own solution,
top100 = []
for product in product_list:
    titles = product.xpath('a[@class="someLink"]/text()')
    prices = product.xpath('div[@class="somePrice"]/text()')

    for title, price, in zip(titles, prices):
        top100.append({'title':title, 'price':price})

output:
top100 = [{'title': 'title1', 'price': '100'},
          {'title': 'title2', 'price': '200'}]


Q: What's wrong with this Linear Algebra proof? Linear Transformation? The question and proof is as follows:
http://i41.tinypic.com/5ahvuc.jpg
I get it up until the part where $u-\beta y \in W$. If this is true, then isn't $U=W$?
Furthermore, how could a single vector, $Ty$, span a vector space $V$, unless $Ty$ has only one element?

A: $U=W$ means that the map $T$ sends every vector $u$ of $U$ in the zero-vector of $V$, meaning that $T$ is constant, always equal to $0$, but this is not the general case. To say that $U=W$ you should have that for every $u\in U$, it is $u\in W$, but you don't have this, you have that for every $u\in U$, $u-\beta y\in W$.
Moreover, there is nothing strange in a single vector family spanning a vector space, this means by definiton that every vector in the vector space can be expressed as a suitable scalar multiple of that unique vector. Do not confuse a set of vectors $S$ with the subspace $\langle S\rangle$ of vectors spanned by $S$.


Q: jQuery getting all input elements of type text where the id ends in "Source" I am trying to get all text boxes that have an id that ends in a particular string.
So far I have tried
$("input[id$='Source']").each(function() {

$("input[type=text][id$='Source']").each(function() {

and also
$("input[type=text] , [id$='Source']").each(function() {

none of these seem to work, could some one maybe point me in the right direction.
I have tried clearing my web browsers cache just to make sure it was not caching any old code.

A: This works:
<input type="text" id="mysource">
<input type="text" id="yoursource">
<input type="text" id="nope">

js (the context 'this' inside of the each function will be the matched elements):
$("input[type='text'][id$='source']").each(function() {
    console.log(this);
});

console result:
<input type="text" id="mysource">
<input type="text" id="yoursource">

A: Clean up your quotes and you should be OK -
$('input[id$="Source"]').each(function() {

$('input[type="text"][id$="Source"]').each(function() {

Here is an example fiddle - http://jsfiddle.net/C5v4H/


Q: Function overloading by function pointer there is a question about overloading functions. Look at this code:
#include<iostream>

void fv(int){}
void fc(const int){}
void fvr(int&){}
void fcr(const int&){}

void fm(void(*fun)(const int))
{
    std::cout << "Constant called" << std::endl;
}

//void fm(void(*fun)(int))
//{
//  std::cout << "non Constant called" << std::endl;
//}

void fm(void(*fun)(const int&))
{
    std::cout << "Constant ref called" << std::endl;
}

void fm(void(*fun)(int&))
{
    std::cout << "non Constant ref called" << std::endl;
}

int main()
{
    fm(&fc);
    fm(&fv);
    fm(&fvr);
    fm(&fcr);
    return 0;
}

if you uncomment void fm(void(*fun)(int)) function you find that compiler can't statically overload function by pointer on function that accept parameter by value and pointer on function that accept const value. Also, if you uncomment void(*fun)(const int) and comment void(*fun)(const int) then all compiles sucessfully. But, if we using references it compiles OK. Don't get why, could you explain me please? Does this mean that pointers to function that accept parameter by value and by const value is same types?
UPD:
Top-level const doesn't influence a function signature
There is a good explanation why top-level const should be removed.

A: Yes, top-level const will be just dropped. Error from gcc

redefinition of ‘void fm(void (*)(int))’

As you can see const is dropped.
Quote from N3376 8.3.5/5

After producing the list of parameter types, any top-level
  cv-qualifiers modifying a parameter type are deleted when forming the
  function type.

A: Yes you cannot overload functions based on the const ness of a non pointer / non-reference argument, see:
Functions with const arguments and Overloading
Which in turn implies that pointers to function that accept parameter by value and const value are same type.


Q: Staf Copy on same Machine : Error registering with STAF, RC: 10 I want to copy a file from one directory to another directory. For doing this I am using staf which gets invoked in one php script, but getting below error, even if I run staf command like below
[root@balveer ConfigManagement_phps]# /usr/local/staf/bin/staf local FS COPY FILE /prd/mdp/Config_Manager/Configuration_files/configfiles/PCEF1/pcef.conf tomachine 172.19.13.53 todirectory /prd/mdp/Config_Manager/Configuration_files/updatedconfigs/
Error registering with STAF, RC: 10

At the time of starting staf, it says staf initialized
Ping test also gives same error
[root@balveer bin]# STAF LOCAL PING PING

Error registering with STAF, RC: 10

I am running staf version 3.4.11 on RHEL 6.3

A: I did following :
$ echo "/usr/local/staf/lib" > /etc/ld.so.conf.d/staf.conf
$ ldconfig

Basically, adding STAF library path in /etc/ld.so.conf.d/staf.conf


Q: flex textflow dyniamic height In my flex application I have scenerio like this:
parent to child
Vbox->Canvas->Sprite->Textflow
In this scenerio now I need to have dynamic height of the textflow & its parents. Here the root parent is the itemrenderer of the datagrid I have.
I need the heights of rows to be adjust according the content in it.
Right now I am importing the xml to textflow, then getting the number of lines, text height. Then removing the textflow & adding it again with the measured height according to the number of lines & text height.
How can I achieve it without removing & adding it again, coz it is taking much time in updating?
Thanks in advance.

A: Right might be a little late to answer this but someone else may benefit.
On the canvas or display object housing the TextFlow and sprite add a creationComplete functon.
I don't know if this step is necessary, but it works for me. Add a label with the text thats going to go into TextFlow (with the same font and fontSize), add a creation complete listener to that as well.
Get the height and width from the newly created label e.target.width e.target.height (in the function listening to the creation of label). Set the displayObjects (in the above case Canvas) height and width to these values, then proceed to add the sprite and textflow.
Note: this was a lazy way for me, label uses measureText which would be a more efficent way of doing this.


Q: How to open multiple nodejs command prompts in windows? For a class, I am using a node js command prompt. In windows only when i search node js command prompt am I able to open the command prompt. This command prompt is basically the regular windows command prompt with edhanced features of node. For example I use the node js command prompt to do things like npm install, npm run serve, etc. I know that to open another window of regular windows command prompt, i can run start cmd.exe  but how so can I do with my node js command prompt?

A: On my machine if I run "Node Command Prompt" a 2nd time, it opens a 2nd window.

If you want to do the same thing, the shortcut that Node installs just runs:

C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat"

so you should be able to run that, assuming your node install location is Program Files\nodejs.

A: Open your environment variables config, and add these 2 directories to Path variable.
C:\Program Files\nodejs\
C:\Users\your_user_name\AppData\Roaming\npm

And then every time you open a regular cmd window, the node.js commands will be available to you.


Q: Hide price excluding tax when price is empty I have a setup. For products, I display prices with VAT (info added in the suffix). However, I must include a net price under this price (only in single-product-view). In addition, I have products that are without a price and with them using the Call For Price plugin to display a button to send a price inquiry.
I display the net price adding:
<?php echo woocommerce_price ($ product-> get_price_excluding_tax ()); ?>

added in the template /woocommerce/single-product/price.php.
The problem is that in the case of a product without a price, I still see this value without tax (net) with the amount of 0.00. This one with VAT is deleted automatically.
How could I remove this net price in products that do not have the price indicated?

A: I'd try to add a condition :
<?php if(woocommerce_price ($product-> get_price_excluding_tax ()) != '0.00') // If price is not equal to 0.00
{ echo woocommerce_price ($product-> get_price_excluding_tax ()); }
?>
Let me know if it worked !