text:
Q: Java relative path to file I am building a JSF 2.2 project in Netbeans 7.4 (Windows 7 64bit) and one of my beans need to use a properties file located to the directory "/NetBeansProjects/projectName/web/WEB-INF/file.properties" while the bean that needs it is on the "/NetBeansProjects/projectName/src/java/packageName/bean.java". If I use an absolute path everything works like a charm but when I try to use a relative path it can not find the file. I tried to use every possible variation of "../../../web/WEB-INF/file.properties" but it just doesn't work. What should I do?

A: Use ExternalContext.getResourceAsStream() to pass context-relative path
This should work:
Properties prop = new Properties();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
prop.load(externalContext.getResourceAsStream("/WEB-INF/file.properties"));


text:
Q: How select a check box on loading a page using angular I have number of check boxes in my single page

    Place of operation

                    <input type="checkbox" ng-model="placesOBJ[place.place_id]">

            {{place.place_name}}

This is working perfectly. If data is present then i want to defaultly check this check boxes
if($scope.client.client_places){
    var plcLength = $scope.client.client_places.length;
    var client_places = new Array();
    for(var i = 0; i < plcLength; i++){
        client_places[i] = $scope.client.client_places[i]['place_id'];
    }
    // console.log(client_places);
    //$scope.placesOBJ4 = client_places;
    $scope.placesOBJ = client_places;
}

client places contain an array like {1, 2}
But this is not working. if any one know about this please help me.

A: You can use a directive ng-checked and pass in an expression based on the model

A: You can use ng-checkedto achieve what you need
<input type="checkbox" ng-model="placesOBJ[place.place_id]" ng-checked="placesOBJ">

If $scope.placesOBJ is populated (not null) then the expression is true and the checkbox will be selected

A: Just have a look at this simple code It will be useful for you

          Place of operation

                          <input type="checkbox" ng-model="placesOBJ[place.id]" ng-checked="true">
                          {{place.name}}

Explanation:- You can make use of ng-init="init()" to call on page load , it will check if data is present or not. If present then set ng-show="true" else by default it will be false

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling a remote EJB hosted on WebSphere Full Profile(v7) from app. running in Liberty I have:

*

*Application A running in Liberty Profile (8.5.5.7)

*Application B running in WAS Full Profile V7, hosting EJB called MyBean.

I want to invoke MyBean's methods from application A.
I'm programmatically doing the lookup for MyBean with code as below, based on the documentation at:http://www-01.ibm.com/support/knowledgecenter/?lang=en#!/SSEQTP_8.5.5/com.ibm.websphere.wlp.doc/ae/twlp_ejb_remote.html
String corbaURL = "corbaname::wasv7Server:wasv7Port#ejb/global/B/MyBean/beans.\\MyBean!com\\.acme\\.MyBeanRemoteInterface";
Object ref = new InitialContext().lookup(corbaURL);
// .. boilerplate code for narrowing the remote object and calling the remote method.

The Liberty where the app. A is running has the ejbRemote-3.2 feature enabled.
The application B deployed in WAS7 full profile had application name B and EJB module MyBean and MyBean's deployment descriptor is:
<session id="Session_beans.MyBean">
    <ejb-name>beans.MyBean</ejb-name>
    <home>com.acme.MyBeanHome</home>
    <remote>com.acme.MyBeanRemote</remote>
    <ejb-class>com.acme.MyBean</ejb-class>
    ...
</session>

When executing the lookup in app. A (in Liberty) I got a NameNotFoundException,
and I'm wondering if the LocationService at the WAS Full Profile V7 is understanding the corba name URL being sent by Liberty since V7, afaik, doesn't support JEE6; if this is the case how can I invoke the the bean MyBean from A running in the Liberty Profile? Can I use ejbRemote-3.2 feature and just use a different corba name URL, if so what is the correct URL to use?
UPDATE
As per @bkail recommendation changed the lookup URL to:
String corbaURL = "corbaname::wasv7Server:wasv7Port#beans\\.MyBean" ;
// dumpNameSpace shows:
// (top)/nodes/napp_srmwrk1_app-FULL/servers/AppServer/beans.MyBean
// 8    Bound Java type: com.acme.MyBeanHome
// 8    Local Java type: org.omg.stub.java.rmi._Remote_Stub

After the change still getting the NameNotFoundException. The stack trace is:
16:21:35.580 [Default Executor-thread-51] ERROR qsr - NamingException
javax.naming.NameNotFoundException: null
at
com.sun.jndi.cosnaming.ExceptionMapper.mapException(ExceptionMapper.java:61) ~ [na:1.8.0_60]
at com.sun.jndi.cosnaming.CNCtx.callResolve(CNCtx.java:500) ~[na:1.8.0_60]
at com.sun.jndi.cosnaming.CNCtx.lookup(CNCtx.java:539) ~[na:1.8.0_60]
at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:205) ~[na:1.8.0_60]
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161) ~[na:na]
at javax.naming.InitialContext.lookup(InitialContext.java:417) ~[na:1.8.0_60]
at net.gbm.App.doGet(App.java:65) ~[mnr.war:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [com.ibm.ws.javaee.servlet.3.1_1.0.10.jar:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [com.ibm.ws.javaee.servlet.3.1_1.0.10.jar:na]
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1287) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:778) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:475) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1158) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:4867) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer31.osgi.webapp.WebApp31.handleRequest(WebApp31.java:523) [com.ibm.ws.webcontainer31_1.0.10.jar:na]
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.handleRequest(DynamicVirtualHost.java:297) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:997) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:262) [com.ibm.ws.webcontainer_1.1.10.jar:na]
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:955) [com.ibm.ws.transport.http_1.0.10.jar:na]
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:341) [com.ibm.ws.transport.http_1.0.10.jar:na]
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:470) [com.ibm.ws.transport.http_1.0.10.jar:na]
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:404) [com.ibm.ws.transport.http_1.0.10.jar:na]
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:284) [com.ibm.ws.transport.http_1.0.10.jar:na]
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.ready(HttpInboundLink.java:255) [com.ibm.ws.transport.http_1.0.10.jar:na]
at com.ibm.ws.tcpchannel.internal.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:174) [com.ibm.ws.channelfw_1.0.10.jar:na]
at com.ibm.ws.tcpchannel.internal.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:83) [com.ibm.ws.channelfw_1.0.10.jar:na]
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:504) [com.ibm.ws.channelfw_1.0.10.jar:na]
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:574) [com.ibm.ws.channelfw_1.0.10.jar:na]
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:929) [com.ibm.ws.channelfw_1.0.10.jar:na]
at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1018) [com.ibm.ws.channelfw_1.0.10.jar:na]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_60]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_60]
Caused by: org.omg.CosNaming.NamingContextPackage.NotFound:   IDL:omg.org/CosNaming/NamingContext/NotFound:1.0
at org.omg.CosNaming.NamingContextPackage.NotFoundHelper.read(NotFoundHelper.java:72) ~[com.ibm.ws.org.apache.yoko.corba.spec.1.5_1.0.10.jar:1.8.0_60]
at org.omg.CosNaming._NamingContextStub.resolve(_NamingContextStub.java:251) ~[com.ibm.ws.org.apache.yoko.corba.spec.1.5_1.0.10.jar:1.8.0_60]
at com.sun.jndi.cosnaming.CNCtx.callResolve(CNCtx.java:486) ~[na:1.8.0_60]
... 31 common frames omitted

Thanks,

A: The corbaname: URLs listed in the "Using enterprise JavaBeans with remote interfaces on the Liberty profile" topic are the names used to access EJBs running in the Liberty profile.  To connect to an EJB on a full profile server, you need to use the binding name from the full profile, which likely starts with ejb/... rather than ejb/global/....  See the "Default binding pattern" section of the EJB 3.0 application bindings overview topic in the Knowledge Center.
Unlike the Liberty profile, the full profile mirrors the JNDI default namespace to the CosNaming context, so you should copy the relevant JNDI name from the CNTR0167I message in SystemOut.log (the JNDI name that does not start with java:global).  Alternatively, run the PROFILE_HOME/bin/dumpNameSpace command on the full profile to dump the namespace, and you should be able to find the binding name.

A: Let me share my experience of very similar work that I did just yesterday.
Hope this helps somebody who searches the stackoverflow.
First I downloaded Wlp8.5.5.8 and tried adding features like ejbRemote3.2. It was not available for reasons I am unaware of.
Then I googled to find the wlp having ejbRemote3.2 feature
Downloaded that
Added following features to the ServerConfiguration.
How to add these features to Serverconfiguration? Please refer the following link:
Liberty Profile - Remote EJB
Praveen has made a spoon-feed, thanks to him
    <feature>javaee-7.0</feature>
    <feature>ejbRemote-3.2</feature>
    <feature>jndi-1.0</feature>
    <feature>ejbLite-3.2</feature>
    <feature>localConnector-1.0</feature>
    <feature>servlet-3.1</feature>

Added the following 6 lines of code in my servlet deployed in Liberty profile
    Properties ejbProps = new Properties();
    ejbProps.put(Context.PROVIDER_URL, ejbUrl);
    InitialContext ffmContext = new InitialContext(ejbProps);
    Object remoteObject = ffmContext.lookup(ejbName);
    MyBeanRemote myBean = PortableRemoteObject.narrow(remoteObject, MyBean.class);
    myBean.callingMethod();

And the magic worked: MyBean method got invoked/called.
Note: I had MyBean stub jar file generated and placed in my servlet deployed in wlp


text:
Q: Difference between large Rasterlayer and formal class Raster Layer in R? I currently possess two rasters with the EXACT SAME resolution and extent, and yet they show different number of rows when loaded into the global environment in R.
In addition, before these rasters were made a dataframe in R by using the asctodataframe() function in R, they were initially stacked and the PCA was calculated using the rasterPCA() function, and then, I obtained the rasters in the snapshot shown below.

However, the individual rasters were loaded as a large Rasterlayer and a formal class raster layer. What is the difference between the two? And is this difference causing a change in the number of rows when loaded into R.
Snapshot of Individual rasters:

For more info: please see Same extent and resolution of rasters, but different number of cells

library(raster)
library(RStoolbox)

###################################
##Loading the Present day variables and then creating a raster stack, followed by a PCA
##################################

bio3 <- raster("C:\\Users\\rameshv\\4_ForR\\bio3")
bio4 <- raster("C:\\Users\\rameshv\\4_ForR\\bio4")
bio5 <- raster("C:\\Users\\rameshv\\\4_ForR\\bio5")

pres_stack <- stack(bio3, bio4,bio5)

pre_pca <-  rasterPCA(pres_stack, nComp = 2) #Choosing the first two axes

#Note: YOU NEED TO CALL the right element, else it will not writeRaster
writeRaster(pre_pca$map,"C:\\Users\\rameshv\\Downloads\\5_PCAforR\\PC.asc", format="ascii", bylayer=T)

#################################
##Loading the LGM variables and then creating a raster stack, followed by a PCA

lg3 <- raster("C:\\Users\\rameshv\\4_ForR\\cclgmbi3")
lg4 <- raster("C:\\Users\\rameshv\\4_ForR\\cclgmbi4")
lg5 <- raster("C:\\Users\\rameshv\\4_ForR\\cclgmbi5")

lg_stack <- stack(lg3,lg4,lg5)

lg_pca <- rasterPCA(lg_stack, nComp = 2) #Choosing the first two axes

#Note: YOU NEED TO CALL the right element, else it will not writeRaster
writeRaster(lg_pca$map,"C:\\Users\\rameshv\\5_PCAforR\\PC.asc", format="ascii", bylayer=T)

#########Now I have two rasters that are PC1 and PC2 of the variables    chosen and shall run the multivariate code provided by Hamann et al., 2015

library(SDMTools)     # install package to read and write ESRI ASCII grids
library(yaImpute)     # install package for k-nearest neighbour (kNN) search

lg1 <- asc2dataframe("C:\\Users\\rameshv\\5_PCAforR\\PC_1.asc")
lg2 <- asc2dataframe("C:\\Users\\rameshv\\5_PCAforR\\PC_2.asc")
present1  <- asc2dataframe("C:\\Users\\rameshv\\5_PCAforR\\PC_1.asc")
present2  <- asc2dataframe("C:\\Users\\rameshv\\5_PCAforR\\PC_2.asc")

> str(lg1)
 'data.frame':   44352 obs. of  3 variables:
  $ y    : num  2209806 2209806 2209806 2209806 2209806 ...
  $ x    : num  -5265209 -5260209 -5250209 -5245209 -5240209 ...
  $ var.1: num  -260 -252 -214 -198 -187 ...
   - attr(*, "filenames")=List of 2
  ..$      : chr "C:\\Users\\rameshv\\Downloads\\Climate Stability\\Data_LGM_Present\\LGM\\5_PCAforR\\PC_1.asc"
  ..$ names: chr "var.1"

  > str(present1)
   'data.frame':   44340 obs. of  3 variables:
    $ y    : num  2209806 2209806 2209806 2209806 2209806 ...
    $ x    : num  -5265209 -5260209 -5250209 -5245209 -5240209 ...
    $ var.1: num  -38.26 -32.95 -8.26 3.47 9.82 ...
    - attr(*, "filenames")=List of 2
    ..$      : chr "C:\\Users\\rameshv\\Downloads\\Climate Stability\\Data_LGM_Present\\Present\\5_PCAforR\\PC_1.asc"
    ..$ names: chr "var.1"

A: First, please look at the objects in R and not RStudio, or whatever IDE you are using. There have been continuing issues with spatial objects in RStudio and I do not consider it reliable. It would also be helpful if you provided your code so we could track how each object was created.
I took a look at the source code for the rasterPCA function and the Large RasterLayer object class is not being assigned in the function. I am wondering if the object name is coming from RStudio. I would not worry because I think that these objects are still formally RasterLayer and RasterStack objects.
The difference in number of rows, columns, values (from your previous post) could be attributed to the spatial object information not displaying correctly in the IDE or the function not assigning the values correctly. The rasterPCA function is; 1) taking a sample, 2) predicting to the raster values, 3) assigning the predicted values back to the raster. The code looks sound and when I have used it, have observed no problems. Keep in mind that the function could be producing NA values that also may effect the displayed number of values in the raster. The critical element is that the number of rows, columns and geographic extent do not change.


text:
Q: Importing Variable length text files per individual into R I would like to import a very large text file as a dataframe into R. The file is produced by the "National Institute for Health and Disability Insurance" in Belgium. It contains individual data on health professionals in Belgium.
It's a fixed width text file, and I usualy import that kind of data with "read_fwf". The problem is that the structure of the file is a bit tricky :

*

*The individual data are divided into eight "types" ("type 11", "type 12", "type 13", etc.) that are on different rows. So each individual has several rows (= different type of information).

*Each row begins with a "prefix part" of the same information about these individuals, which allows the data to be joined by individual. This "prefix part" is therefore repeated from row to row for the same individual.

*Each part (each "type"/row and the "prefix part") has its own fixed width structure. For exemple, the prefix part has 54 characters, in which the type is indicated in the 53rd and 54th characters ; type 11 has 249 characters divided into 18 variables ; type 12 has 78 characters divided into 5 variables ; type 13 has 110 characters divided into 12 variables ; etc.

*BUT, the number of "types" (and therefore the number of rows) per individual is variable. Some individuals have 3 types/row, others 4, 5, 6, 7 or 8. This means that there is a variable number of types/rows per individual.

Here's a fictive exemple of the structure, very simplified. The "prefixed part" is the 0000xxx part. The 5 first characters indicates the individual. The 2 last characters of the "prefixed part" specifies the "type" of the row. Each row contains data specific to that "type", divided into variables (the width structure of the variables is indicated in comment) :
0000111abaabacd
0000112abbbba
0000113ccaxyzzghj5
0000211acatbacz
0000212zbabba
0000311tyyyuacd
0000312xbbiop
0000411pkggbacz

#type 11 has 3 variables. Width for each : 2,3,3
#type 12 has 2 variables. Width for each : 3,3
#type 13 has 4 variables. Width for each : 3,3,1,4

So, what i'd like to do is to import into a dataframe in R each individual into one unique row, with all the variables of each type into separated columns. If the variables are missing (because there is no type/row), i'd like indicate empty data (NA) for each variable.
id     var1  var2  var3  var4  var5  var6  var7  var8  var9
00001    ab   aab   acd   abb   bba   cca   xyz     z  ghj5
00002    ac   atb   acz   zba   bba    NA    NA    NA    NA
00003    ty   yyu   acd   xbb   iop    NA    NA    NA    NA
00004    pk   ggb   acz    NA    NA    NA    NA    NA    NA

I'm a bit lost, I don't know where to start, because the structure is really not usual for me. Do you have ideas or advices ?
Thank you very much !

A: Assuming the input shown reproducibly in the Note at the end read it as 3 fields and then reshape to wide form with one column per type.  Finally separate the fields in each such column.
library(dplyr)
library(readr)
library(tidyr)

cols <- fwf_cols(id = 5, type = 2, misc = NA)

# DF <- read_fwf("myfile", cols)
DF <- read_fwf(Lines, cols)

DF %>%
  pivot_wider(names_from = "type", values_from = "misc") %>%
  separate(`11`, c("var1", "var2", "var3"), cumsum(c(2, 3, 2))) %>%
  separate(`12`, c("var4", "var5"), cumsum(c(3, 3))) %>%
  separate(`13`, c("var6", "var7", "var8", "var9"), cumsum(c(3, 3, 1, 4)))

giving:
# A tibble: 4 x 10
  id    var1  var2  var3  var4  var5  var6  var7  var8  var9
  <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 00001 ab    aab   ac    abb   bba   cca   xyz   z     ghj5
2 00002 ac    atb   ac    zba   bba   <NA>  <NA>  <NA>  <NA>
3 00003 ty    yyu   ac    xbb   iop   <NA>  <NA>  <NA>  <NA>
4 00004 pk    ggb   ac    <NA>  <NA>  <NA>  <NA>  <NA>  <NA>

Note
Lines <- "0000111abaabacd
0000112abbbba
0000113ccaxyzzghj5
0000211acatbacz
0000212zbabba
0000311tyyyuacd
0000312xbbiop
0000411pkggbacz"


text:
Q: Fetching data from API in React Native with Redux I am trying to fetch data from API in react native using redux but it is not fetching. The API is based on colors which have to fetch, all it is showing just the change button on the screen and not changing backgroundColor after clicking on it
Here is the code :
App.js

import React, {Component} from 'react';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import ReduxThunk from 'redux-thunk';
import reducers from "./reducers";
import BoxCon from './container/box-container';

class App extends Component {
  render() {
    const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
    return (

      <Provider store={store}>
        <BoxCon />
        </Provider>

    );
  }
}

export default App;

container/box-container.js

import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {connect} from "react-redux";
import * as actionCreators from "../action/index.js"
import Box from '../component/box.js';
//import { actionCreators } from 'redux';

class BoxCon extends Component{
    render(){
        return(
            <Box handleClick={this.props.loadColor} color={this.props.color} />

        )
    }
}

const mapStatetoProps=(state)=>{
    return state
};

export default connect (mapStatetoProps, actionCreators)(BoxCon);

component/box.js
import React, {Component} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
export default class Box extends Component{
    render(){
        return(
            <View  style={styles.container}>
                <View style={{backgroundColor:'${this.props.color}'}}>
                <TouchableOpacity onClick={()=>{this.props.handleClick()}} style={styles.button}>
                    <Text>
                        Change Color
                    </Text>
                </TouchableOpacity>
            </View>
            </View>
        )
    }
}

reducers/index.js
const INITIAL_STATE ={
    color:"red"
}

const mainReducer=(state=INITIAL_STATE,action)=>{
    if(action.type==="CHANGE_COLOR"){
        return{
            ...state,
            color:action.color
        }
    } else{
        return{
            state
        }
    }
}

export default mainReducer;

action/index.js
import axios from "axios";

export function loadColor(){
    return(dispatch) => {
        return axios.get("http://www.colr.org/json/color/random").then((response)=>{
           dispatch(changeColor("#"+response.data.new_color));
        }) .catch((error) => {
            console.log(error);
          });
    }
}

export function changeColor(color){
    return{
        type:"CHANGE_COLOR",
        color:color
    }
}

A: This is probably because you did not specify a payload.
Change:
if(action.type==="CHANGE_COLOR"){
    return{
        ...state,
        color:action.color
    }
}

...

export function changeColor(color){
    return{
        type:"CHANGE_COLOR",
        color:color
    }
}

to
if(action.type==="CHANGE_COLOR"){
    return{
        ...state,
        color:action.payload
    }
}

...

export function changeColor(color){
    return{
        type:"CHANGE_COLOR",
        payload:color
    }
}

and I think it will work.


text:
Q: Addon SDK. Slice main.js into few units? I'm develop some extension for Mozilla FireFox using Addon SDK.
My main.js now is very huge, contains a lot of code in all kinds.
It's possible to slice them into few custom js files?
main.js - Loader
Unit1.js - Do job A
Unit2.js - Do job B
Unit3.js - Do job C
or any good advice for developing very functional extensions.

A: You can create and require() "local" modules. Also read up on the Module structure of the SDK.
Therefore, you may want to try to modularize your stuff.
lib/joba.js
function non_exported_helper() {
  // do something;
}

function JobA() {}
JobA.prototype = {
  doSomething: function() {
    non_exported_helper();
    return something_else;
  }
};
// Export JobA
// Stuff not in `exports` will not be visible to other code
// require()ing a module.
exports.JobA = JobA;

lib/main.js
var JobA = require("./joba").JobA;

var job = new JobA();
job.doSomething();

Of course, any module can use require(), but beware of circular imports.
It's up to you what to put into what module. E.g. one module could implement a single "class", while another module could implement a collection of functions, or another module could be for background requests and yet another module of all UI stuff.
Maybe looking at the SDK itself, which is organized in modules, and/or look into what other stdlibs do, like the Python stdlib, or the go stdlib, etc.


text:
Q: Error:Plugin /Preset files are not allowed to export objects,only functions/babel-preset-stage-0 I am having some problems with webpack/babel.First i install webpack,webpack-cli,webpack-dev-server,babel-loader,babel-core,babel-preset-env and it seems to be working fine.But when i install babel-polyfill and babel-preset-stage-0(because i want to be able to use async and await) i keep getting aforementioned error.I ve been struggling with this for days i would really appreciate if someone just told me which dependencies i need to install and what adjustments i need to make in my files.At this point i just want to be able to use modules and async and await for vanilla javascript apps.

// ./src/app.js
async function getUsers() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");

  const data = await response.json();

  return data;
}

getUsers().then(data => console.log(data));

//Package json file
{
  "name": "new",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server --output-public-path=/build/"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/preset-env": "^7.2.3",
    "babel-loader": "^8.0.5",
    "babel-polyfill": "^6.26.0",
    "babel-preset-stage-0": "^6.24.1",
    "webpack": "^4.28.4",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.1.14"
  }
}
//webpack.config.js
const path = require("path");

module.exports = {
  mode: "production",
  entry: {
    app: ["babel-polyfill", "./src/app.js"]
  },
  output: {
    path: path.resolve(__dirname, "build"),
    filename: "app.bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env", "stage-0"]
          }
        }
      }
    ]
  }
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script src="./build/app.bundle.js"></script>
  </body>
</html>

A: Check if you have multiple Babel installations.
In my case I had one at my project's node_modules folder and another global.
Uninstalling my global @babel at ~/node_modules solved this issue here.

A: I downloaded Brad Traversy s babel_webpack_starter pack.It solved the issue for me.


text:
Q: Can't ping computers on local network over wifi on Windows, but can with Mac I've got two routers connected via ethernet on two different floors of my house, both with the same SSID, and identical security settings.
When connecting via ethernet to either router, all computers can see each other.  E.g. basement-1 can ping secondfloor-1, and vice-versa.
When connecting via wi-fi, my Windows 10 machine, which is connected to the router on the second floor, cannot see any machines in the basement.  This problem does not exist for other devices (e.g. OS X, iPad, or Android tablets).
Some additonal informaiton based on questions so far:

*

*To test, I renamed the router on the second floor to a new SSID.  This ensured I was not actually connected to the basement router

*Network setup is as follows:

*

*Basement Router: 192.168.13.2 (stock D-Link)

*Second Floor Router: 192.168.13.8 (DDWRT)

*Windows 10 machine: 192.168.13.116 (I have tried both static and DHCP IP - no difference)

*NAS connected to basement router: 192.168.13.150

*Printer connected to basement router: 192.168.13.50

*Computer connected to basement router: 192.168.13.100

*ROKU connected to second floor router via Ethernet: 192.168.13.106

*Ping tests:

*

*Win 10 on second floor router ping basement router via wi-fi: Fail

*Win 10 on second floor router ping basement computer/printer/NAS via wi-fi: Fail

*Win 10 on second floor router ping google.com via wi-fi: Success

*Win 10 on second floor router ping basement router via ethernet: Success

*Win 10 on second floor router ping basement computer/printer/NAS via ethernet: Success

*Win 10 on second floor router ping ROKU via wi-fi: Success

*Win 10 on second floor router ping google.com via ethernet: Success

*iPad on second floor router ping basement computer: Success

*iPad on second floor router ping basement router: Success

*Computer on basement router ping Win 10 machine on second floor router via wifi: Fail

In a nutshell, it looks like the Windows 10 machine specifically cannot see anything connected to the basement router, but it can see the internet.  It can also see devices connected to the second floor router (e.g. ROKU).  Second floor items can also see basement items (iPad works okay via wifi; ROKU works via ethernet - both can access the NAS in the basement).
Output of route -4 print:
===========================================================================
Interface List
  5...54 e1 ad 71 de a7 ......Intel(R) Ethernet Connection (4) I219-V
 10...ae ed 5c b9 c0 67 ......Microsoft Wi-Fi Direct Virtual Adapter
 17...ac ed 5c b9 c0 68 ......Microsoft Wi-Fi Direct Virtual Adapter #2
 15...00 ff b0 04 2e e0 ......TAP-Windows Adapter V9
  8...ac ed 5c b9 c0 67 ......Intel(R) Dual Band Wireless-AC 8265
  9...ac ed 5c b9 c0 6b ......Bluetooth Device (Personal Area Network)
  1...........................Software Loopback Interface 1
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0     192.168.13.1   192.168.13.116     50
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    331
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    331
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    331
     192.168.13.0    255.255.255.0         On-link    192.168.13.116    306
   192.168.13.116  255.255.255.255         On-link    192.168.13.116    306
   192.168.13.255  255.255.255.255         On-link    192.168.13.116    306
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    331
        224.0.0.0        240.0.0.0         On-link    192.168.13.116    306
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    331
  255.255.255.255  255.255.255.255         On-link    192.168.13.116    306
===========================================================================
Persistent Routes:
  None

Any suggestions on what may be happening?  I'm confident the router setups are okay because everything seems to work fine with other platforms; the problem seems to be specific to the Windows 10 machine on wifi.
Thanks.
UPDATE
It looks like there is something materially wrong with both routers in my house; the issues above seem to resolve if I do a full power-down (i.e. unplug), pause 1 minute, and then re-power everything, starting with the basement router, then the second floor router, and then re-enabling WiFi on all devices.  Both routers are older models; as a next step I may try installing DD-WRT on the basement router and seeing if that fixes anything.

A: I suspect your Win 10 box's WNIC is losing its ability to receive multicasts (including broadcasts), which breaks ARP, which keeps it from being able to address packets to devices that aren't in its ARP cache.
As a simple test of this hypothesis, add a static ARP mapping, in the Win 10 box, for one of the boxes it can't ping. If that allows it to ping that box, you know ARP was broken somehow.
Many WNICs are buggy when it comes to dealing with a separate cipher for multicasts/broadcasts than for unicasts, which is the case when original WPA (TKIP) is left enabled alongside WPA2 (AES-CCMP). So if you've left original WPA enabled on either of your routers, be sure to disable it so you're in pure WPA2-(AES-CCMP)-only mode.


text:
Q: STS Spring Project: Why is that HelloWorld example not working? I am new to Spring and currently trying the following Hello World example from the book ProSpring3:
package com.tutorials.prospring3.ch2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class HelloWorldSpringDI {
        public static void main(String[] args) {
            // Initialize Spring ApplicationContext
            ApplicationContext ctx = new ClassPathXmlApplicationContext(
                    "META-INF/spring/app-context.xml");
            MessageRenderer mr = ctx.getBean("renderer", MessageRenderer.class);
            mr.render();
        }
    }

The ClassPathXmlApplicationContext instantiation is marked as the following error: "The constructor ClassPathXmlApplicationContext(String) refers to the missing type BeansException"
In addiation, when running the application the IDE displays a build path problem: "Archive for required library: 'C:/Users/Admin/.m2/repository/org/springframework/spring-beans/3.0.6.RELEASE/spring-beans-3.0.6.RELEASE.jar' in project 'ch2' cannot be read or is not a valid ZIP file"
As the spring-beans.jar (to which the BeansException class belongs) is part of my Maven Dependencies i wonder how that could happen.

Has anyone a suggestion how to solve that problem?
Thanks in advance!
Jonas

A: try to open the archive C:/Users/Admin/.m2/repository/org/springframework/spring-beans/3.0.6.RELEASE/spring-beans-3.0.6.RELEASE.jar with an application like WinZip. If that application indicates that the archive is corrupted as well, you should delete it and try again. (delete the entire C:/Users/Admin/.m2/repository/org/springframework/spring-beans/3.0.6.RELEASE directory and all its contents).
On the next build of your project, the archive will be downloaded again. If it still does not work and you are connecting to a local repository, you should contact the administrator.

A: I konw your problem have out of date, i just want to help someone who gets the same problem, as i got the same problem and finished it.It's easy,just add the org.springframework.beans.jar to your project.

A: Look like the dependency is missing from your project's classpath.
To resolve it
Right click on your project
Navigate to **Maven**
Click on **Update project**

If it does not resolve this problem then
Go to the path

C:/Users/Admin/.m2/repository/org/springframework/
  and delete the folder named as spring-beans

Now again Right click on your project
Navigate to **Maven**
Click on **Update project**

It will update/add the orphan/missing dependency of your project

A: Two causes:

*

*The issue could be with the corrupted Spring JARs .
Remove the existing Spring  dependancies
Add dependencies from :
http://mvnrepository.com/artifact/org.springframework/spring-beans/5.0.0.M5
It ll solve the issue.

2.The indirect dependancies for beans are not sufficiently added.
Add the dependancies .
Sameer Sukumaran

A: Go to :C:\Users(user_name(or)admin_name).m2\repository\org\springframework
Now, delete spring-beans and spring-expression folder.
Go to :Eclipse and then update the project by right clicking on the project maven>update project.
Eclipse will download the required files.ISSUE SOLVED :-)

A: I had the same issue when I was working with 4.2.2.RELEASE version of Spring, once I changed it to 4.2.0.RELEASE, the error dispeared. I hope this can help in your case too.


text:
Q: Multiple users use linux pc at the same time I have a powerful linux PC. Is it possible that more than one user use that PC at the same time while I will use it physically and others will use it remotely (each person will have different user and see different screen)? Can they login remotely anytime when my PC is turned on?
For example:
Suppose there are three users named X, Y, Z in my linux PC. I am user X and using the computer physically. I want that user Y and Z can login to the PC remotely at the same time and log out. They should be allowed to login to their users at any time they want. We all will use GUI.
If this is possible, please tell me how can I do that. Thanks in advance.

A: Yes it's possible.
Look into installing a RDP or VNC server on the Linux machine, and a RDP/VNC client (for instance FreeRDP or RealVNC) on the users' computers.
RDP (Remote Desktop Protocol) and VNC (Virtual Network Computing) both are technologies that enable remote graphical use of another computer.
In addition to logging in with a graphical interface, users can also login to a terminal using SSH.

A: Install xrdp with the following command,
sudo apt install xrdp

Enable and start it
sudo systemctl enable xrdp --now
sudo systemctl start xrdp

Make sure it is running
sudo systemctl status xrdp

Now all user accounts on the Linux PC can remote desktop using the building RDP client on Windows and Remmina on Linux.
The username and password are the same as their credentials on Linux PC.


text:
Q: iOS - App crashing, but not generating crash report My iOS Application Extension is crashing sporadically in ways that I'm unable to replicate or even begin to figure out how to replicate. When I go into XCode and go to Window->Devices->View Device Logs it's not showing any crashes for my application. I have no way to debug what's going on without these crash logs.
Is there a reason that they might not be generating?
I've tested across three devices:

*

*iPhone 6S running iOS 11.1

*iPhone 7 running iOS 10

*iPhone 7 running iOS 11

I'm getting the same result on all of them. The extension will randomly crash during the day, and when I notice that it has crashed and plug it in to recover crash logs, there is nothing there.
I'm positive that it is a crash and that the extension isn't just closing. Right before this started happening I was getting several common crashes that I had reports for, but then this started happening and I"m no longer able to verify which of my crashes are still happening at all.
Are there common reasons that this might be happening?

A: I think you are supposed to check your scheme. edit scheme -> info - build configuration -> debug, just as the below image


text:
Q: En un servidor apache2 no funciona la autenticación auth_digest., me sigue dejando acceder a la página sin pedirme autenticación El modulo auth_digest está en mods-enabled y la consola me dice que está habilitado. He probado en la directiva Directory las rutas con comillas y sin comillas, o con provider file y sin el, y me sigue dejando entrar en la ruta especificada. Por supuesto, reinicio Apache después de cada cambio.
Uso Apache/2.4.41 en Ubuntu
El archivo digest está bien creado también, con la directiva htdigest
Adjunto código del archivo conf de mi sitio
Está igual que en todos los tutoriales pero no va, incluso reiniciando mi máquina virtual.
<Directory /www/dnoticias/public/private>
    Order deny,allow
    AuthType Digest
    AuthName "diegolgroup"
    AuthDigestProvider file
    AuthUserFile /etc/apache2/claves/claves_digest.txt
    Require valid-user
</Directory>


text:
Q: Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException no message in crud in laravel i got an error when i trying to update a record, please some one help me !!
Form:
    {{Form::open(array('action'=>['MyController@update',$record->id]))}}

Name<input type="text" value="{{$record->name}}" class="form-control" name="name">

Email<input type="text" value="{{$record->email}}" class="form-control" name="email">

Phone<input type="text" value="{{$record->phone}}" class="form-control" name="phone">

<input type="submit" class="btn btn-primary">
<input type="reset" class="btn btn-danger">

{{Form::close()}}

Route:
Route::resource("my","MyController");

Controller:
public function update(Request $request,$id){
    $record=Record::find($id);
    $record->name=$request->name;
    $record->email=$request->email;
    $record->phone=$request->phone;
    if($record->save()){
        return redirect("my")->with("success","Record Successfully Updated");
    }else{
        return redirect("my")->with("error","Something went wrong");
    }
}

A: 1.First of all it is a post method add method in the form header and you are using resource in the routes so you need to specify the patch method in your form
2.You have to pass csrf_token for post method on the top of the form you can do @csrf Like this
<form method="POST">
    @csrf
    @method("METHOD")
</form>

You are pssing id from your form so In controller you can do simple like this
3.Check the routes/web.php if u have done post
public function update(Request $request,Record $record){
    $record->name=$request->name;
    $record->email=$request->email;
    $record->phone=$request->phone;
    $record->save();

    return redirect()->to('/url');
}

Also make sure you have pass the id to the routes
Hope this helps
Good luck

A: For update request,Your method should be PUT; so
<form method="POST">
  @csrf
  @method('PUT')

</form>

or
{{ Form::open(array('url' => '/', 'method' => 'PUT')) }}
    .... wathever code here
{{ Form::close() }}

Note: Since HTML forms only support POST and GET, PUT and DELETE
  methods will be spoofed by automatically adding a _method hidden field
  to your form.

Read this doc


text:
Q: Looking for examples of ffmpeg and concat with list.txt and fade in-out I've been researching how to do an ffmpeg-concat with play list and fade in/out. I haven't seen an example of this combination. my current command is as follows: I'd like to fade in and out of each video clip, and there are 35-60 video clips in the .txt list. ffmpeg build is from 2016, so it doesn't have gltransition.
ffcommand = {"-f", "concat", "-safe", "0", "-i", renderDirPath + "concatscript.txt", "-i", musicDirPath, "-map", "0:v", "-map", "1:a", "-vf", "scale=640x480", renderDirPath + "finalrender.mp4"}


text:
Q: Lag when plotting data from arrays in real time using matplotlib I'm having a little bit of trouble ploting data of the size of two arrays or lists Arr_Particles and Arr_Particles2. I currently draw the figure to plot on when i intitiate my program then plot on it later using a function which is called every so often using a loop. The problem im having is that i have an animation of particles moving and colliding oin a pygame window and in order to plot points on the figure i have to pause the plotting which halts the animation of particles as it runs in a loop with graph() . I'm wondering if there is any way around this ?
code below:
code for creating arrays and figures:
Arr = []
Arr2 = []

fig = plt.figure()
ax = fig.add_subplot(111)
Ln, = ax.plot(Arr)
Ln1, = ax.plot(Arr2)
ax.set_xlim([0,100])
ax.set_ylim([0,40])
plt.ion()
plt.show()

The code called to plot is:
def Graph(Arr, Arr2, Arr_Particles, Arr_Particles2):

 #sets the variable Particle1No = the length of Arr_Particles
    Particle1No = len(Arr_Particles)
    #sets the variable Particle2No = the length of Arr_Particles2
    Particle2No = len(Arr_Particles2)

    #this appends the data from Particle1No to Arr
    Arr.append(Particle1No)
    #this sets ln y data as the data from Arr
    Ln.set_ydata(Arr)
    #this sets ln x data as len of Arr
    Ln.set_xdata(range(len(Arr)))

    #this appends the data from Particle2No to Arr2
    Arr2.append(Particle2No)
    #this sets ln y data as the data from Arr2
    Ln1.set_ydata(Arr2)
    #this sets ln x data as len of Arr2
    Ln1.set_xdata(range(len(Arr2)))

    #pauses plotting ( seems can be 0 or very close) ? it doesnt plot if this is removed either.
    plt.pause(0.1)

Any help would be Very much appreciated.


text:
Q: Sharepoint 2007 Image Gallery - Is there a better one available that I'm not seeing? The default image gallery for Sharepoint 2007 requires you to click the thumbnail of each picture you want to view and then after you see the picture, you have to navigate back to the thumbnails before you can continue to the next picture.
Is there a way to make this process easier so users can simply click next or use the arrow keys on their keyboard to quickly move forward and back between images in a gallery?
Thanks in advance!

A: If you look under the Actions menu, you'll see a "View Slide Show" option. That's what you get out of the box.
If you're looking for something a little more "modern", consider adding a jQuery-driven "lightbox". You see these all over the Web these days, and you and your users will be very familiar with them. You can use my SPServices library to drive the slideshow by reading the list items using GetListItems.


text:
Q: Upload multiple images to firebase storage i build a chat application using firebase and i want to send multiple image to firebase storage.
using this library
compile 'com.github.darsh2:MultipleImageSelect:3474549'
At the top
private StorageReference storageRef;
private FirebaseApp app;
private FirebaseStorage storage;

onCreate()Method
app = FirebaseApp.getInstance();
storage =FirebaseStorage.getInstance(app);

button click action
   Gallary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(ChatActivity.this, AlbumSelectActivity.class);
                intent.putExtra(Constants.INTENT_EXTRA_LIMIT, 10);
                startActivityForResult(intent, Constants.REQUEST_CODE);
                pwindo1.dismiss();
            }
        });

Activity result
    if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
        Uri uri = Uri.parse(String.valueOf(images));
        storageRef = storage.getReference("photos");
        final StorageReference photoRef = storageRef.child(uri.getLastPathSegment());
        photoRef.putFile(uri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Uri downloadUrl = taskSnapshot.getDownloadUrl();
                        String content = downloadUrl.toString();
                        if (content.length() > 0) {
                            editWriteMessage.setText("");
                            Message newMessage = new Message();
                            newMessage.text = content;
                            newMessage.idSender = StaticConfig.UID;
                            newMessage.idReceiver = roomId;
                            newMessage.timestamp = System.currentTimeMillis();
                            FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
                        }
                    }
                });

    }

A: Variables

*

*private static final int PICK_IMAGE = 1;

*Button chooserBtn, uploaderBtn;

*TextView alert;

*private Uri ImageUri;

*ArrayList ImageList = new ArrayList();

*private int upload_count = 0;

*private ProgressDialog progressDialog;

*ArrayList urlStrings;

onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    uploaderBtn = findViewById(R.id.uploader);
    chooserBtn = findViewById(R.id.chooser);
    alert = findViewById(R.id.alert);

    progressDialog = new ProgressDialog(MainActivity.this);
    progressDialog.setMessage("Uploading Images please Wait.........!!!!!!");
    chooserBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(intent, PICK_IMAGE);

        }
    });

Uploader Button
    uploaderBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            urlStrings = new ArrayList<>();
            progressDialog.show();
            alert.setText("If Loading Takes to long press button again");
            StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");

            for (upload_count = 0; upload_count < ImageList.size(); upload_count++) {

                Uri IndividualImage = ImageList.get(upload_count);
                final StorageReference ImageName = ImageFolder.child("Images" + IndividualImage.getLastPathSegment());

                ImageName.putFile(IndividualImage).addOnSuccessListener(
                        new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                ImageName.getDownloadUrl().addOnSuccessListener(
                                        new OnSuccessListener<Uri>() {
                                            @Override
                                            public void onSuccess(Uri uri) {
                                                urlStrings.add(String.valueOf(uri));

                                                if (urlStrings.size() == ImageList.size()){
                                                    storeLink(urlStrings);
                                                }

                                            }
                                        }
                                );
                            }
                        }
                );

            }

        }
    });

}

This Line of will help us to store Links of All Images under One Node
                                                if (urlStrings.size() == ImageList.size()){
                                                    storeLink(urlStrings);
                                                }

Store Links To Firebase Realtime Database
private void storeLink(ArrayList<String> urlStrings) {

    HashMap<String, String> hashMap = new HashMap<>();

    for (int i = 0; i <urlStrings.size() ; i++) {
        hashMap.put("ImgLink"+i, urlStrings.get(i));

    }
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("User");

    databaseReference.push().setValue(hashMap)
            .addOnCompleteListener(
                    new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(MainActivity.this, "Successfully Uplosded", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
            ).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
    progressDialog.dismiss();
    alert.setText("Uploaded Successfully");
    uploaderBtn.setVisibility(View.GONE);

    ImageList.clear();
}

onActivityResult()
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE) {
        if (resultCode == RESULT_OK) {

            if (data.getClipData() != null) {

                int countClipData = data.getClipData().getItemCount();
                int currentImageSlect = 0;

                while (currentImageSlect < countClipData) {

                    ImageUri = data.getClipData().getItemAt(currentImageSlect).getUri();
                    ImageList.add(ImageUri);
                    currentImageSlect = currentImageSlect + 1;
                }

                alert.setVisibility(View.VISIBLE);
                alert.setText("You have selected" + ImageList.size() + "Images");
                chooserBtn.setVisibility(View.GONE);

            } else {
                Toast.makeText(this, "Please Select Multiple Images", Toast.LENGTH_SHORT).show();
            }

        }
    }
}

}

A: It is working fine.
 if (requestCode == Constants.REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<Image> images = data.getParcelableArrayListExtra(Constants.INTENT_EXTRA_IMAGES);
        Uri[] uri=new Uri[images.size()];
        for (int i =0 ; i < images.size(); i++) {
            uri[i] = Uri.parse("file://"+images.get(i).path);
            storageRef = storage.getReference("photos");
            final StorageReference ref = storageRef.child(uri[i].getLastPathSegment());
            ref.putFile(uri[i])
                    .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            String content = downloadUrl.toString();
                            if (content.length() > 0) {
                                editWriteMessage.setText("");
                                Message newMessage = new Message();
                                newMessage.text = content;
                                newMessage.idSender = StaticConfig.UID;
                                newMessage.idReceiver = roomId;
                                newMessage.timestamp = System.currentTimeMillis();
                                FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
                            }
                        }
                    });

        }

    }

A: This utility class I create it to upload multiple images to firebase storage using kotlin with help of coroutine. if you have any enhancement please tell me.
you need to add these dependencies firstly.
implementation 'com.google.firebase:firebase-storage-ktx:19.1.1'
//Firebase adds support to Coroutines through the kotlinx-coroutines-play-serviceslibrary
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.3.1"
for more info check link, github link
object FirebaseUtils {

    suspend fun uploadPhotos(photosUri: ArrayList<File>): List<PhotoUrl> {
        val storageRef = Firebase.storage.reference
        val photosUrls = ArrayList<PhotoUrl>()
        val uploadedPhotosUriLink = withContext(CoroutineScope(Dispatchers.IO).coroutineContext) {
            (photosUri.indices).map { index ->
                async(Dispatchers.IO) {
                    uploadPhoto(storageRef, photosUri[index])
                }
            }
        }.awaitAll()

        uploadedPhotosUriLink.forEach { photoUriLink -> photosUrls.add(PhotoUrl(photoUriLink.toString())) }
        return photosUrls
    }

    private suspend fun uploadPhoto(storageRef: StorageReference, photoFile: File): Uri {
        val fileName = UUID.randomUUID().toString()
        val fileUri = Uri.fromFile(photoFile)

        return storageRef.child(fileName)
            .putFile(fileUri)
            .await()
            .storage
            .downloadUrl
            .await()
    }
}

A: For return list imageUrls with same order of images selected from gallery
don't use for loop for every uri
after you get ArrayList<Uri> imageUriList and you want now upload it to firebase storage then return the list of url for every image in same order your selected it, so i use recursion on below method until upload all uri
 private void uploadImages(@NonNull ArrayList<String> imagesUrl,ArrayList<Uri> imageUriList) {

        StorageReference storageReference = FirebaseStorage.getInstance().getReference("Products").child(UUID.randomUUID().toString());

        Uri uri = imageUriList.get(imagesUrl.size());

        storageReference
                .putFile(uri).addOnSuccessListener(taskSnapshot ->
                storageReference.getDownloadUrl().addOnCompleteListener(task -> {
                    String url = Objects.requireNonNull(task.getResult()).toString();

                    imagesUrl.add(url);

                    //if same size so all image is uploaded, then sent list of url to to some method
                    if(imagesUrl .size()  == imageUriList.size()){
                        allImageUploadedNow(imagesUrl);
                    }else {
                        uploadImages(imagesUrl);
                    }

                }))
                .addOnFailureListener(e -> {
                    Log.e("OnFailureImageListener", Objects.requireNonNull(e.getMessage()));

                   //some image is fails to upload

                });

    }

so now after get imageUriList value from OnActivityResult we can call method by this;
uploadImages(new ArrayList<>(),uriFilesList);

and when finish to upload all image you can handle it inside
 private void allImageUploadedNow(ArrayList<String> imagesUrl){

  //handle imagesUrl
}

A: In my case of uploading multiple images into firebase I have used forEach(). forEach() method had helped me to upload images successfully into firebase

    import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
    const Product =()=>{
    const [file, setFile] =useState([])
    Object.values(file).forEach(val => {
    const storage = getStorage();
    const storageRef = ref(storage, 'images/val.name');

    const uploadTask = uploadBytesResumable(storageRef, val);
    uploadTask.on('state_changed',
      (snapshot) => {
         number of bytes to be uploaded
        const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
          case 'paused':
            console.log('Upload is paused');
            break;
          case 'running':
            console.log('Upload is running');
            break;
        }
      },
      (error) => {
      },
      () => {
        getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
          console.log('File available at', downloadURL);
        });
      }
    );
    })
    return (
    <button onClick={(e) => setFile(e.target.files)}/>
    )
    }


text:
Q: MySQL how to safely randomize the output of this query? I have a SELECT query that I am expecting millions of results from. I need to randomize these results in MySQL. Doing it in my script after the query obviously uses too much RAM. Can someone please rework this query so that the results are all random without using order by rand()? I have seen some examples and tried to use them but they don't work for me since they all seem to depend on returning the whole table rather than using a WHERE clause. Here is my query:
SELECT * FROM pool
WHERE gender = 'f'
AND (`location` = 'united states' OR `location` = 'us' OR `location` = 'usa');

A: If you can use other language, for example php you can use its rand() function to generate ids and add the to the query like
$ids = range($mini, $maxid);
shuffle($ids);
array_slice($ids, 0, $quantity);

Or something similar in any language you are using.
If you need to do this in pure mysql query then here are some alternaties: http://www.electrictoolbox.com/msyql-alternative-order-by-rand/

A: If you have 10 million lines with id's, are they in a contiguous range?

*

*Get the lowest id from the range you want via a quick select.

*Get the largest id as well.

*generate random numbers in this range using php

*once you have your numbers "SELECT * FROM table1 WHERE id IN (the numbers you generated)" or something like that


text:
Q: Support for Loadinf procedure i would need some assistance with this loadinf function
const
  Section = 'Setup';

  procedure LoadInf(const FileName: String; var WantToSuppressMsgBoxes: Boolean);
var
  S: String;
begin
  //saved infs
  InitLang := GetIniString(Section, 'Lang', InitLang, FileName);
  InitDir := GetIniString(Section, 'Dir', InitDir, FileName);
  InitProgramGroup := GetIniString(Section, 'Group', InitProgramGroup, FileName);
  InitNoIcons := GetIniBool(Section, 'NoIcons', InitNoIcons, FileName);
  InitSetupType := GetIniString(Section, 'SetupType', InitSetupType, FileName);
  S := GetIniString(Section, 'Components', '$', FileName);
  if S <> '$' then begin
    InitComponentsSpecified := True;
    SetStringsFromCommaString(InitComponents, SlashesToBackslashes(S));
  end;
  S := GetIniString(Section, 'Tasks', '$', FileName);
  if S <> '$' then begin
    InitDeselectAllTasks := True;
    SetStringsFromCommaString(InitTasks, SlashesToBackslashes(S));
  end;
end;

I'm having issues with the
SetStringsFromCommaString(InitComponents, SlashesToBackslashes(S));
Is there any way to do that function in inno ?
The SetStringsFromCommaString can be found here , but couldn't make it to compile
Best Regards,  BeGiN.


text:
Q: How to insert and extract image or object from cxRichEdit I'm using DevExpress cxRichEdit for Notebook project.
I need to be able to insert an image selected from open dialog into richedit (now I can do that only by pasting from clipboard), and, if needed, get this image back to original file with original extension.
Please advise.


text:
Q: Sorting a filtered list I have a list of reports that are being shown to the user. I have a-tags that allow the list to be sorted in different ways (last posted, highest upvotes etc.), and I also have separate a-tags that filter down the list according to a particular report variable (report status is open, closed etc.).
I am trying to figure a way out to allow the filter to remain in place when the a-tag to sort the list is pressed, and vice-versa.
What I have tried was setting up a model with the statusId (id set to filter the list) and sortString (string containing "highest_award" or "last_update", used to sort the list in HomeController), but my thinking was completely off.
Is there a clean way to go about this?
Index.cshtml
//List of sorting options -- *These are links that allow the user to sort the list as appropriate*

Highest Awarded

Last Updated

...

//Filtering options set to status.Id -- *These are buttons that allow the user to filter the list as appropriate according to a set statusId for each article*
@foreach (ReportStatus status in Model.Statuses)
{

    @status.StatusName

}

...

//Report contents as viewed by used
@{
foreach (ReportViewModel report in Model.Reports.ReportViewModels)
{
    ...some "report" details
}

HomeController.cs (with no mention towards filtering the list)
        public IActionResult Index(string sortString/*, int statusId*/)
        {
            Console.Write(sortString + " " + statusId + "\n");

            var reports = from r in _myRepository.GetAllReports()
                          select r;

            ViewData["AwardSort"] = String.IsNullOrEmpty(sortString) ? "highest_award" : "";
            ViewData["UpdateSort"] = String.IsNullOrEmpty(sortString) ? "last_update" : "";

            //reports = reports.Where(r => r.StatusId == statusId); -- Need to set this and keep set

            switch (sortString)
            {
                case "last_update":
                    reports = reports.OrderBy(r => r.DateOfUpdate);
                    break;
                case "highest_award":
                    reports = reports.OrderBy(r => r.NumberOfStars);
                    break;
            }

            HallOfFameViewModel hofViewModel = new HallOfFameViewModel(_myRepository.GetTopUsers(5));
            ReportListViewModel reportsViewModel = new ReportListViewModel(
                reports.ToList(),
                _myRepository.GetUserById(_userManager.GetUserId(User))
            );

            var model = new HomePageViewModel(hofViewModel, reportsViewModel, _myRepository.GetReportStatuses());
            return View(model);
        }

//-------------------------------------------
//The filtered list would be taken here, need to somehow add currently selected sort option as well as be able to set the sorting criteria

[ResponseCache(Duration = 2)]
        [Route("Home/Index/{id}")]
        public IActionResult Index(int statusId)
        {
            var reports = from r in _nemesysRepository.GetAllReports()
                          select r;

            HallOfFameViewModel hofViewModel = new HallOfFameViewModel(_nemesysRepository.GetTopUsers(10));
            ReportListViewModel reportsViewModel = new ReportListViewModel(
                _nemesysRepository.GetAllReportsWithStatus(statusId).ToList(),
                _nemesysRepository.GetUserById(_userManager.GetUserId(User))
            );

            var model = new HomePageViewModel(hofViewModel, reportsViewModel, _nemesysRepository.GetReportStatuses());
            return View(model);
        }

Thank you in advance.

A: my friend,
You should also add a 'CurrentFilterName' for each filter tag you have.
Ex: ViewData["AwardSort"] should couple with ViewData["CurrentAwardSort"]
So when the page reloads when a filter is clicked you send the values to this 'FilterName'
and on input value, you put 'CurrentFilteNameValue'.
Hopefully, this solves your issue. Wish you the best :)

A: Change your code like below:
public IActionResult Index(string sortString,int statusId)
{
    if (statusId!=0)
    {
        reports = test.Reports.ReportViewModels.Where(a => a.Id == statusId);
        var data = HttpContext.Session.GetString("Filter");
        if(data!=null)
        {
            sortString = data;
        }
    }
    else
    {
        ViewData["AwardSort"] = String.IsNullOrEmpty(sortString) ? "highest_award" : "";
        ViewData["UpdateSort"] = String.IsNullOrEmpty(sortString) ? "last_update" : "";
        if(sortString!=null)
        {
            HttpContext.Session.SetString("Filter", sortString);
        }
    }
    switch (sortString)
    {
        case "last_update":
            reports = reports.OrderBy(r => r.DateOfUpdate);
            break;
        case "highest_award":
            reports = reports.OrderBy(r => r.NumberOfStars);
            break;
    }
    //....

    return View(model);
}

Here is my whole working demo:
Model:
public class Test
{
    public Report Reports { get; set; }
    public List<ReportStatus> Statuses { get; set; }
}
public class ReportStatus
{
    public int Id { get; set; }
    public string StatusName { get; set; }
}
public class Report
{
    public IEnumerable<ReportViewModel> ReportViewModels { get; set; }
}
public class ReportViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime DateOfUpdate { get; set; }
    public int NumberOfStars { get; set; }
}

View:
@model Test

Highest Awarded

Last Updated

@foreach (ReportStatus status in Model.Statuses)
{

        @status.StatusName

}

        @foreach (ReportViewModel report in Model.Reports.ReportViewModels)
        {

                    @Html.DisplayFor(model => report.DateOfUpdate)

                    @Html.DisplayFor(model => report.NumberOfStars)

        }

Controller:
public class HomeController : Controller
{
    Test test = new Test()
    {
        Reports = new Report()
        {
            ReportViewModels = new List<ReportViewModel>()
            {
                new ReportViewModel(){ Id=1, DateOfUpdate=new DateTime(2018,2,12),NumberOfStars=34},
                new ReportViewModel(){Id=1,DateOfUpdate=new DateTime(2019,3,23),NumberOfStars=23},
                new ReportViewModel(){Id=2,DateOfUpdate=new DateTime(2014,5,13),NumberOfStars=25},
                new ReportViewModel(){Id=2,DateOfUpdate=new DateTime(2015,2,24),NumberOfStars=29}
            }
        },
        Statuses= new List<ReportStatus>()
        {
            new ReportStatus(){Id=1,StatusName="aa"},
            new ReportStatus(){Id=2,StatusName="bb"}
        }
    };
    public IActionResult Index(string sortString,int statusId)
    {
        var reports = test.Reports.ReportViewModels;

        if (statusId!=0)
        {
            reports = test.Reports.ReportViewModels.Where(a => a.Id == statusId);
            var data = HttpContext.Session.GetString("Filter");
            if(data!=null)
            {
                sortString = data;
            }
        }
        else
        {
            ViewData["AwardSort"] = String.IsNullOrEmpty(sortString) ? "highest_award" : "";
            ViewData["UpdateSort"] = String.IsNullOrEmpty(sortString) ? "last_update" : "";
            if(sortString!=null)
            {
                HttpContext.Session.SetString("Filter", sortString);
            }
        }
        switch (sortString)
        {
            case "last_update":
                reports = reports.OrderBy(r => r.DateOfUpdate);
                break;
            case "highest_award":
                reports = reports.OrderBy(r => r.NumberOfStars);
                break;
        }
        test.Reports.ReportViewModels = reports;

        return View(test);
    }
}

Be sure register Session:
public void ConfigureServices(IServiceCollection services)
{
    services.AddSession();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSession();
}

Reference:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0#configure-session-state


text:
Q: What is the appropriate number of Gunicorn workers for each Amazon Instance Type? I'm currently trying to figure out what the appropriate number of workers is for each Amazon Instance Type. I used to run one Gunicorn worker, however that proved to be quite slow.
Many developers are currently using this formula to gauge how many workers would be suitable:
NUM_WORKERS=3  #recommended formula here is 1 + 2 * NUM_CORES

The problem I'm having is that Amazon isn't quite clear as to the number of cores each instance is running. For example, an M1 Small Instance has 1 EC2 Compute Unit (1 virtual core with 1 EC2 Compute Unit)
What does that essentially mean? That it has one core? or that it has two cores?

A: The Amazon EC2 m1.small instance type definitely has one virtual core only; from a threading/worker perspective you can ignore the EC2 Compute Unit (ECU) specification entirely and take the listed number of (virtual) cores on the Amazon EC2 Instance Types page literally, multiplying by the number of listed CPUs, where applicable (only relevant for cluster instances).
If you want to avoid doing the math and/or have programmatic access to that information, you might want to have a look at the missingcloud project - the aws.json dataset features a cores field within the instance_types collection, e.g.:
"instance_types" : {
        "m1.small" : {
            "compute_units" : 1,
            "cores" : 1,
            "gpus" : 0,
            "ramMB" : 1700,
            "storageGB" : [10, 160],
            "i/o" : "moderate",
            "ebs_optimized_iopsMbps" : 0,
            "arch" : [32,64]},
        ...
}

A: I know this is a old question. But I think I have a better answer to this question. Gunicorn docs suggests that 2n+1 [gunicorn -w <2n+1> myapp:wsgi] is a good guess for number of workers (Yes, n = number of cores). I came up with a tiny shell script to apply this formula. All you need to do is this:
gunicorn -w $(( 2 * `cat /proc/cpuinfo | grep 'core id' | wc -l` + 1 )) myapp:wsgi

Where the command
cat /proc/cpuinfo | grep 'core id' | wc -l

will return the total number of actual CPU cores (n). So
$(( 2 * `cat /proc/cpuinfo | grep 'core id' | wc -l` + 1 ))

equates to 2n+1 formula.
This will apply 2n+1 formula to all the linux-based machines. You dont need to know the number of workers for each type of instance or anything like that.
Reference: http://dhilipsiva.com/2015/10/22/appropriate-number-of-gunicorn-workers.html

A: An easy way to see how many cpu's are detected is to run top and press "1" to show the number of cpu's. You will see cpu0, cpu1, cpu2 etc.

A: Building on epicbrew's work, here's how to launch 2N+1 Gunicorn workers, where N = number of CPU cores:
gunicorn --workers=$((2 * $(getconf _NPROCESSORS_ONLN) + 1)) wsgi:application

This works on both Linux and macOS!  More detail on the John Tells All blog.


text:
Q: JwtSecurityTokenHandler ValidateToken: "Signature validation failed. No security keys were provided to validate the signature" I am experiencing strange behavior when I run the code below.
If it runs through a test everything works correctly and the passed token got validated.
But when it run from an Azure FunctionApp it throw this exception: "Signature validation failed. No security keys were provided to validate the signature" despite validationParameters contains IssuerSigningKeys.
In both cases the result of GetPublicKeysAsync was the same.
public async Task<ClaimsPrincipal> GetClaimsPrincipalFromTokenAsync(string accessToken)
{
    TokenValidationParameters validationParameters = await CreateTokenValidationParametersAsync();

    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    ClaimsPrincipal principal = tokenHandler.ValidateToken(accessToken, validationParameters, out SecurityToken oAuthSecurityToken);
    return principal;
}

public static async Task<TokenValidationParameters> CreateTokenValidationParametersAsync()
{
    var keys = await GetPublicKeysAsync();
    List<SecurityKey> securityKeys = new List<SecurityKey>();
    foreach (JWTPublicKey publicKey in keys)
        securityKeys.Add(GenerateJWTSecurityKey(publicKey.key));

     TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
     {
         ValidIssuer = "XXX",
         ValidAudience = "YYY",

         ValidateIssuer = true,
         ValidateAudience = true,
         ValidateLifetime = true,
         ValidateIssuerSigningKey = true,
         IssuerSigningKeys = securityKeys,
     };
     return tokenValidationParameters;
}

private static SecurityKey GenerateJWTSecurityKey(string publicKey)
{
    var rsa = new RSACryptoServiceProvider(2048);
    rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out _);

    return new RsaSecurityKey(rsa);
}

Would anyone have any guidance on what to check for? Thank you.

A: Glad that paolo-crociati issue got resolved with the help of this SO thread posting the suggestion provided in comments as an answer to help the other community members who faces related issues.
Below is the sample code for RSA signature for the specified data.
public override bool VerifySignature (byte[] rgbHash, byte[] rgbSignature);

and here is the sample example which demonstrates how to use the verify signature method by which paolo have implemented work around for custom token.
using System;
using System.Security.Cryptography;

class RSASample
{

    static void Main()
    {
        try
        {
            //Create a new instance of RSA.
            using (RSA rsa = RSA.Create())
            {
                //The hash to sign.
                byte[] hash;
                using (SHA256 sha256 = SHA256.Create())
                {
                    byte[] data = new byte[] { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };
                    hash = sha256.ComputeHash(data);
                }

                //Create an RSASignatureFormatter object and pass it the
                //RSA instance to transfer the key information.
                RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);

                //Set the hash algorithm to SHA256.
                RSAFormatter.SetHashAlgorithm("SHA256");

                //Create a signature for HashValue and return it.
                byte[] signedHash = RSAFormatter.CreateSignature(hash);
                //Create an RSAPKCS1SignatureDeformatter object and pass it the
                //RSA instance to transfer the key information.
                RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                RSADeformatter.SetHashAlgorithm("SHA256");
                //Verify the hash and display the results to the console.
                if (RSADeformatter.VerifySignature(hash, signedHash))
                {
                    Console.WriteLine("The signature was verified.");
                }
                else
                {
                    Console.WriteLine("The signature was not verified.");
                }
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

For complete information check the Verify Signature document.


text:
Q: How to extract only specific numeric values from a range of data in MS Excel? I have a range of data say a1:a100 in which there exist mixed up numeric and alphabetic values.
I want that only the numeric values which are greater than 1 and lesser then 10000000 (i.e. falling between 1 to 10000000) from the range a1:a100 should be extracted and should be inserted into column b.
I am attaching the snapshot of excel sheet.

I tried to use this array formula in b1 but this is not working as i want-
 =IFERROR(INDEX(A5:A100, SMALL( IF(A1:A100>0, ROW()-0, ""), ROW()-0) ), "")

A: If it is ok for you to use VBA:
Press Alt + F11, double click ThisWorkbook and paste the following code:
Sub values()

Dim c As Range
i = 1

For Each c In ActiveSheet.Range("A1:A100")
    If IsNumeric(c) And c >= 1 And c <= 10000000 Then
        Cells(i, 2).Value = c
        i = i + 1
    End If
Next c

End Sub

Go back to the sheet with your numbers, press Alt + F8 and run the macro.
I did not test this so create a backup first.


text:
Q: Is it ok to use MongoDB when we have no idea about the availabe keys? We are scraping a huge products website.
So, we will get and persist so many products, and almost each product has a different set of features/details.
Naturally, we consider using a NoSQL database (MongoDB) for this job. We will make a collection "products", and a document for each product where each key/value pair map to detail_name/detail_description of the product.
Since products are quite different, we have almost no idea what are the product details/features. In other words, we have no knowledge of the available keys.
According to this link MongoDB case insensitive key search, It is a "gap" for MongoDB (that we do not have some idea of the available keys).
Is this true? If yes, what are the alternatives?

A: Your key problem isn't that much of an issue for MongoDB provided you can live with a slightly different schema and big indexes :
Normally you would do something like :
{
    productId :..
    details : {
        detailName1 : detailValue1,
        detailName2 : detailValue2;
    }
}

But if you do this you can index the details field :
{
    productId :..
    details : [
        {field : detailName1, value : detailValue1},
        {field : detailName2, value : detailValue2}
    ]
}

Do note that this will result in a very big index. Not necessarily a problem but something to be aware of. The index will then be {details.field:1, details.value:1} (or just {details:1} if you're not adding additional fields per detail).

A: Once you've scraped all of the data you could examine it to determine if there is a field/set of fields in the documents that you could add an index to in order to improve performance.


text:
Q: Providing JS or iframe like analytics and statcounter to other webpage to run remotely my PHP + JS script How to not copy my source code to other servers and provide them with a JS or iframe like the analytics and statcounter provide us?
I wrote a PHP script with JS that in it's basic description goes like this:
When someone visits my website, gets a cookie with a value of a unique identification and at the same time using AJAX I make some checks and I save that same value to mysql accordingly. After this, if he visits again my site, (in most of the cases) a cookie is not created again.
In depth:
The cookie value is created with JS and I want to keep it that way for future enhancements.
My code (index.php, add-to-mysql.php) has JS and PHP.
I want to use this script in my additional domains, and some of them are in different server. But I don't want to put all my source files to there accounts.
The ideal for me is to provide them with a JS code, like the google analytics or statcounter give us (or alternative similar ways), an iframe... solutions like these.
When a visitor gets into their page, my mySQL in a remote server (my server) will be updated and a cookie will created on their site. Transferring data from and to.
Is this something possible to be made? If yes, how can I start studying for this? Can you provide me with some guidelines?
Thank you.
this is a block of code, the ajax function that posts the random number to the add-to-mysql.php file where i make some actions
$.ajax({
    type: 'POST',
    url: 'add-to-mysql.php',
    data: { one: hash }, //an antikatastiso to hash me to a ke kano to md5 meso php sto ajax vgenei to idio
    success: function(data) {
        alert("success! X: " + data);
    }
});

A: It seems to me you have three options here.
1. Use JSONP
JSONP allows you to do cross domain ajax calls so that you can just call in to your home server from your other domains without being obstructed.
This is probably the easiest route to go I'm thinking.
See here for a quick write up on how JSONP works:
https://stackoverflow.com/a/2067584/867294
jQuery supports jsonp so it's not to difficult to get started with:
http://learn.jquery.com/ajax/working-with-jsonp/
JSONP works by dynamically adding a script to the document that then calls a callback.
The contents of ths javascript file need to be generated by the server, your PHP file add-to-mysql.php will have to echo out something like this:
<?= htmlspecialchars($_GET["callback"]) =>('someData you want to return');

You can access the one: parameter that was passed in from jQuery trough the $_GET array as well, as this is just a GET request.
From the client side you can call this route like so:
Note that this will always be a GET request, all parameters will go trough the URL.
The 'callback' parameter is the connecting factor here, it makes sure the PHP side knows what JavaScript function to generate.
$.ajax({
    jsonp: 'callback',
    dataType: "jsonp",
    url: 'http://my-server.com/add-to-mysql.php',
    data: { one: hash }, //an antikatastiso to hash me to a ke kano to md5 meso php sto ajax vgenei to idio
    success: function(data) {
        alert("success! X: " + data);
    }
});

2. Use CORS
CORS will allow you to make ajax calls to a different domain then the one where your JS is running. This does however require you to send special http headers from the serving html page, so this does require you to modify the servers.
See here for a qucik intro on CORS:
http://www.html5rocks.com/en/tutorials/cors/
In short, the headers you will need to set from the serving html page are:
Access-Control-Allow-Origin: http://domain.com
Access-Control-Expose-Headers: list,of,headers

3. Posting to an iFrame
Posting trough a hidden iFrame is also an option.
For this you need to set the target of a form to the name of the iframe, the advantages here is that you can use POST as well. You can submit and populate the form trough jQuery as well.
$('#one_input').val('someHash');
$('#myForm').submit();

You can just put everything in a hidden div if you don't want to show it on the page:

    <form id="myForm" action="http://my-server.com/add-to-mysql.php" method="post" target="my_iframe">
       <input type="input" id="one_input" value="" />
    </form>

You could also just set the url of the iframe with your parameter if you don't need any feedback.
var hash = 'stuff';
document.getElementId('one_input').src="http://my-server.com/add-to-mysql.php?one=" + hash;

Extra
you could also use the iframe with Window.postMessage
Building on the previous example:
$('#my_iframe')[0].contentWindow.postMessage('hash', 'my-server.com');

But this requires you to have already a page loaded in your iframe that will then receive the message trough JavaScript, so I don't think this is what you are looking for.

A: Google Analytics provide an script that doesn't post data, it loads an script asynchronously (this is very important to avoid messing with load times of the original website), then it sends all of their info requesting for a .gif image. Your code should do a request to an url ending in .gif, with all the data in GET form. Do your magic and return a gif with size 1px*1px and no content.
Just request something like this
yourdomain.com/a.gif?cookie=1234aqfajsdlq....&uid=qekjlajdfa

Put all your data in there
I recommend obfuscating it a bit, but that should help you avoid cors, iframes or jsop
EDIT

This was taken from GA. See that it creates a tag, with the async attribute to avoid load time issues (remember sync scripts stop the page rendering). Then it creates and array where it pushes all the info it needs in tuples. It defines ga in the window as a function that pushes all its arguments to a q.
The you can create an script that takes all of the data you need, with js, cookies, domain, etc. and send to the server.
For example, you want the domain that the user is visiting:
//You won't have jquery, but you get the idea
//Create a tag
var i = $('').prop('src', 'yourdomain.com/a.gif?domain' + window.location.origin).css('display', 'none');
$('body').append(i);

In some point you will have to set a cookie. I thing cookies can't not be cross domain, so you should set them in your requests not in js.
On the server side you check the cookie, if there is none, you created, and there you can track many things.
Afterwards, your script can check for cors support, and use ajax without this. I don't recommend JSONP, is very error prone, and is actually kind of a hack

A: In order to avoid the cross-domain problematic you can include an iframe at the other sites, that loads from your site. It creates its own scope (domain) and you can freely use ajax from inside communicating with your site.
However, if you set cookies there, it will be associated to the iframes source domain (your domain). This might or might not be a problem. Note, that this can be used to identify users across all the other domains including this same iframe (from your domain).


text:
Q: Spark window function and taking first and last values per column per partition (aggregation over window) Imagine I have a huge dataset which I partitionBy('id'). Assume that id is unique to a person, so there could be n number of rows per id and the goal is to reduce it to one.
Basically, aggregating to make id distinct.
w = Window().partitionBy(id).rowsBetween(-sys.maxsize, sys.maxsize)

test1 = {
    key: F.first(key, True).over(w).alias(key)
    for key in some_dict.keys()
    if (some_dict[key] == 'test1')
}
test2 = {
    key: F.last(key, True).over(w).alias(k)
    for k in some_dict.keys()
    if (some_dict[k] == 'test2')
}

Assume that I have some_dict with values either as test1 or test2 and based on the value, I either take the first or last as shown above.
How do I actually call aggregate and reduce this?
 cols = {**test1, **test2}
 cols = list(cols.value())
 df.select(*cols).groupBy('id').agg(*cols) # Doesnt work

The above clearly doesn't work. Any ideas?
Goal here is : I have 5 unique IDs and 25 rows with each ID having 5 rows. I want to reduce it to 5 rows from 25.

A: Let assume you dataframe name df  which contains duplicate use below method
from pyspark.sql.functions import row_number
from pyspark.sql.window import Window
window = Window.partitionBy(df['id']).orderBy(df['id'])

final = df.withColumn("row_id", row_number.over(window)).filter("row_id = 1")
final.show(10,False)

change the order by condition in case there is specific criteria so that particular record will be on top of partition


text:
Q: Object-based Classification in Orfeo ToolBox I have a multispectral camera with 5 bands (r, g, b, red edge, NIR) and I would like to classify plants object based with Orfeo ToolBox. I am flying with the drone close to the plants and have an image resolution of about 0.01 m per pixel. I guess I have to do a segmentation first, then an object based classification. What steps and models in OTB do I have to follow?

A: There are four steps to perform an object-based classification in OTB:
1) Image segmentation
otbcli_Segmentation
note that there is also an external module with the Baatz and Schape criterion : http://tully.ups-tlse.fr/lassallep/grm/tree/master
2) Feature extraction in order to compute object-based variables for the classification
otbcli_ZonalStatistics
3) training the classifier to build a model based on training samples
otbcli_TrainVectorClassifier
4) Applying a model to the feature
otbcli_VectorClassifier

A: Here is a detailed description of single steps: Object-based classification (Tutorial)


text:
Q: Prevent Inserting same combination of Component and template : In a page when we will click the component Presentation tab we can see the component and template listed there.On clicking of Insert button just below that, it will open another window "Insert component presentation" there also we will have Insert and close button.So now what i need to do While inserting i need to check whether the combination of selected Component and Template is already present there on page or not. If yes then it should prevent inserting the same with a  popup like "this combination is already present, select other componet".
Any idea how can i proceed. How can i trigger a Javascript on the Insert button?
EDIT:
When i am subscrbing it to Page i am getting erro.My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using Tridion.ContentManager.Extensibility.Events;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.ContentManagement;
using System.IO;
using System.Windows.Forms;

namespace MyEventHandlers
{
[TcmExtension("MyEventHandlerExtension")]

public class MyEventHandler : TcmExtension
{
    public MyEventHandler()
{
  Subscribe();
}

public void Subscribe()
{
    EventSystem.Subscribe<Page, SaveEventArgs>(SaveBtnInitiated, EventPhases.Initiated);

}

private void SaveBtnInitiated(Page subject, SaveEventArgs args, EventPhases phase)
{

    try
    {
        List<string> allcplist = new List<string>();
        List<string> allcplist = new List<string>();
        foreach (ComponentPresentation cp in subject.ComponentPresentations)
        {
            allcplist.Add(cp.Component.Id + "," + cp.ComponentTemplate.Id);
        }
        List<string> uniquecplist = allcplist.Distinct().ToList();
        if (allcplist.Count != uniquecplist.Count)
        {
            subject.Checkin(false);
            throw new Exception("Page has duplicate component presentation");

    }
    catch(Exception)
    {

    }
}

A: You can implement this in an event handler that is subscribed to the Page Save event and the Initiated phase. When there is a duplicate Component Presentation you can cancel the Save by throwing an exception. The message will be shown in the Message Center in the TCM Explorer.

A: Why are you subscribing to the Component? I think it should be the Page. Then you can walk through the ComponentPresentations property.
Code to go through the Component Presentations and throw an exception when duplicate presentations are found:
foreach (var cpA in subject.ComponentPresentations)
{
    if (subject.ComponentPresentations.Where(cpB => ComponentPresentationsAreEqual(cpA, cpB)).ToList().Count() > 2)
    {
        throw new DuplicateComponentPresentationsEmbeddedOnPageException();
    }
}

And the function to include cpB in the list when it is equal to cpA:
function ComponentPresentationsAreEqual(ComponentPresentation cpA, ComponentPresentation cpB)
{
    return cpA.Component.Id == cpB.Component.Id && cpA.ComponentTemplate.Id == cpB.ComponentTemplate.Id;
}

A: I got my Result with this code Thanks to  @Arjen Stobbe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using Tridion.ContentManager.Extensibility.Events;
using Tridion.ContentManager.Extensibility;
using Tridion.ContentManager.ContentManagement;
using System.IO;
using System.Windows.Forms;

namespace MyEventHandlers
{
[TcmExtension("MyEventHandlerExtension")]

public class MyEventHandler : TcmExtension
{
    public MyEventHandler()
{
  Subscribe();
}

public void Subscribe()
{
    EventSystem.Subscribe<Page, SaveEventArgs>(SaveBtnInitiated, EventPhases.Initiated);

}

private void SaveBtnInitiated(Page subject, SaveEventArgs args, EventPhases phase)
{

    try
    {
        List<string> allcplist = new List<string>();
        List<string> allcplist = new List<string>();
        foreach (ComponentPresentation cp in subject.ComponentPresentations)
        {
            allcplist.Add(cp.Component.Id + "," + cp.ComponentTemplate.Id);
        }
        List<string> uniquecplist = allcplist.Distinct().ToList();
        if (allcplist.Count != uniquecplist.Count)
        {
            subject.Save(false);
            throw new Exception("Page has duplicate component presentation");

    }
    catch(Exception)
    {

    }
}

But i am not deleting the duplicate CP present on the page. Do i need to add,
for each()

inside
if (allcplist.Count != uniquecplist.Count)
{
}


text:
Q: is there a code formatting tool or keyboard short cut to automatically remove the trailing spaces within a quote especially in CSS styling? I want to be able to automatically remove the space after and before the quotes in the inline styling. Especially for large codebase. is there a tool like Prettier or ESLint or VScode extension that can do this?
spacing

A: You can enable whitespace trimming at file save time from this plugin in VScode: plugin


text:
Q: Why does get_term() require taxonomy? Are term_ids not unique? A related WPSE question asks how to get the term by specifying ID only, without specifying taxonomy. My question is more philosophical. Generally, stuff in WP core is there for a reason. I'm trying to understand why term_id can't be the primary key for the term - why do we need the taxonomy as well? Can a single term record be a member of multiple taxonomies? That's certainly not currently supported in the API. Is there a use case where this might be desirable?
Or is the required $taxonomy parameter in get_term() a vestigial tail from an earlier incarnation of the database structure?

A: I've logged a ticket against this with trac: http://core.trac.wordpress.org/ticket/20536
However, it turns out that for the time being it IS necessary, as WordPress currently (since 2.x) has a bug that DOES associate two terms with the same name to the same term_id! So it IS possible (though incorrect) for a single term to be associated with more than one taxonomy. See this bug: http://core.trac.wordpress.org/ticket/5809
It's pretty wide-reaching so implementing the fix will need to be unit-tested very thoroughly. I'll try to remember to update this question if there are any developments.

A:
why do we need the taxonomy as well? Can a single term record be a member of multiple taxonomies?

No. Terms have slugs to support term archives. And having the slugs two times brings up a lot of minetraps or "wontfix"es in some permalink scenarios.

Is there a use case where this might be desirable?

Yes: Imagine that you have terms for e.g. size and have three taxonomies named length, width  and height (you could also think about colors). But that's not supported for the reasons written above.

Generally, stuff in WP core is there for a reason. I'm trying to understand why term_id can't be the primary key for the term - why do we need the taxonomy as well?

From looking at the table and running an EXPLAIN, term_id is the primary key. I guess on larger systems it might be faster to only query taxonomy specific terms using a (slow) join than querying all, sorting them and filtering what you need.


text:
Q: Visual Studio Enterprise 2019, "Profile" unit test causes error: file contains no data buffers After right-clicking a unit test in Test Explorer in Visual studio 2019, and selecting "Profile", the following happens:

*

*All associated projects all built and instrumented, as evidenced by output by Test logging to the Output window, like ** Instrumented C:\Users\Me\Source\Repos\MyRepo\<ProjectPath>\Project.UnitTests\bin\x64\Debug\net472\MyProject.dll **

*The unit test runs and passes

*A new tab with a name of "[UnitTestName][Date][Time].VSP" appears with "Preparing to open report..." in the middle

*An error occurs, "File contains no data buffers"

I've made sure all the projects have this in their csproj file:
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <DebugType>full</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>

Also made sure symbol servers are set up.  Any ideas what else to try to get profiling of unit tests working in VS2019?

A: Through trial and error, discovered there are two things that need to be set to get the Profile option to work (using Visual Studio 2019 and NUnit 3 adapter):

*

*You need the project under test and any of its dependencies switched
to target "Any CPU", under Project > Properties > Build tab >
General section > Platform Target dropdown.

*From the Visual Studio bar, Test > Processor Architecture for AnyCPU Projects - change it to x64.

Profiling should then work.  If you don't do the second step, you'll get Test output errors like:
Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again.
and/or
No test matches the given testcase filter 'MyTestName'


text:
Q: Map super/windows key to KDE Menu? I want to use the Super/Windows key to open the KDE Menu at the bottom left. I really do not want to use Alt+F1 as I am switching from Windows to Kubuntu and I want to retain this functionality. Also, I cannot use ksuperkey as that does not support 16.10 (the version that I use)

A: The feature you describe has been implemented in KDE Plasma 5.8, and is available "out-of-the-box" in that version. Unfortunately, Kubuntu 16.10 contains Plasma 5.7, so it does not have that feature. You will most likely have to wait until Kubuntu 17.04 to get that feature in the official Ubuntu packages.
If you are more adventurous, you can try the Kubuntu Backports PPA, which very recently (6 days ago at the time of writing) added KDE Plasma 5.8.4 packages. However, if you are just beginning under Linux, this may be a lot of things to learn at once, and there is a risk you screw up your install. Here is the announce (with minimal instructions) about that: http://www.kubuntu.org/news/kubuntu-and-linux-mint-doing-plasma-5-8-testing/