text:
Q: Labelfunction interferes with Combobox Item Editor My issue is that when a user clicks a datagrid cell that has a combobox editor and then immediately clicks away from the cell, the text value in that cell disappears.
I have an itemEditEnd handler on the datagrid and it shows the value of the property I use as the editorDataField just fine. But the labelFunction (which gets called after the itemEditEnd handler) on that grid column sees it as zero.
Why aren't the labelFunction and item editor playing together nicely?
Here is the DataGridColumn:
<mx:DataGridColumn
                                headerText="Field Name"
                                dataField="attribId"
                                editorDataField="attributeId"
                                labelFunction="getFieldName">

Here is the Item editor
                            <mx:itemEditor>

                                <mx:Component>

                                    <mx:ComboBox
                                        dataProvider="{this.outerDocument.lendersModel.fileAttributes}"
                                        creationComplete="{outerDocument.selectAttribute();}"
                                        labelField="fileAttribDesc"
                                        change="updateAttribute(event);"
                                        selectedIndex="-1">

                                        <mx:Script>
                                            <![CDATA[
                                                [Bindable]
                                                public var attributeId:int;
                                                private var fileDetailRecordType:String;

                                                override public function set data( value:Object ):void{
                                                    this.attributeId = value.attribId; // adding this line appears to be the fix.
                                                    var category:String = value.category;

                                                    this.filterFileAttributes( category );
                                                }

                                                /** Change handler for combobox in Record Type column.
                                                 */
                                                private function filterFileAttributes( recordType:String ):void{
                                                    this.fileDetailRecordType = recordType;

                                                    this.dataProvider.filterFunction = filterByRecordType;
                                                    this.dataProvider.refresh();
                                                }

                                                /** Filters the file attributes collection based on the record type.
                                                 */
                                                private function filterByRecordType( item:Object ):String{
                                                    return item.category.match( this.fileDetailRecordType );
                                                }

                                                private function updateAttribute( event:* ):void{
                                                    attributeId = event.currentTarget.selectedItem.attribId;
                                                    this.outerDocument.selectedAttributeId = attributeId;
                                                }

                                            ]]>
                                        </mx:Script>

                                    </mx:ComboBox>

                                </mx:Component>

                            </mx:itemEditor>

and here is the label function for the DataGridColumn.
        private function getFieldName( item:Object, dgc:DataGridColumn ):String{
            var fieldName:String = '';

            /* At this point the lendersModel.fileAttributes collection is
               filtered based on the record type. We need to remove the filter
               so we can search the entire collection, not just the filtered subset. */
            lendersModel.fileAttributes.filterFunction = refreshFilter;
            lendersModel.fileAttributes.refresh();

            for each( var attrib:FileAttributeDTO in lendersModel.fileAttributes ){
                if( attrib.attribId == item.attribId )
                    fieldName = attrib.fileAttribDesc;
            }

            return fieldName;
        }

And here is the code executed in the itemEditEndHandler for the Datagrid:
var rowCount:int = fieldsGridEmpty.selectedIndex;
                    var attribCombo:ComboBox = ComboBox( fieldsGridEmpty.itemEditorInstance );
                if( rowCount != -1 && attribCombo.selectedItem != null )
                {
                    newFieldsDp[ rowCount ].fileAttribute.dataType = attribCombo.selectedItem.dataType;
                    newFieldsDp[ rowCount ].fileAttribute.dataLength = attribCombo.selectedItem.dataLength;
                    newFieldsDp[ rowCount ].fileAttribute.fileAttribDesc = attribCombo.selectedLabel;
                    newFieldsDp[ rowCount ].dataLength = attribCombo.selectedItem.dataLength;
                    newFieldsDp[ rowCount ].attribId = attribCombo.selectedItem.attribId;
                }

Now, the item edit handler shows a valid value for 'attribId':
newFieldsDp[ rowCount ].attribId = attribCombo.selectedItem.attribId;

However, the label function gets executed after this and the value for item.attribId is 0. And that's the reason 'fieldName' is an empty String, because there's no match.

A: My fix mentioned in the comments seems to work. The underlying problem is that the editorDataField property was only set when the user interacted with the combobox.
I remedied that problem by setting it in the override public function set data() method. In this manner, as soon as a user touches it, it is set.


text:
Q: Add borders in a used cell range (including empty/blank cells) in VBA Ok so I am trying to apply borders in VBA in the column range of A:BQ, the number of rows will never be the same so this part needs to be dynamic. I have tried some versions but these versions are excluding empty cells with will be within the range. This is the code I am working with and like I mentioned, it excludes any blank cells and doesn't give those a border.
Sub Borders()

Application.ScreenUpdating = False

Dim lngLstCol As Long, lngLstRow As Long

lngLstRow = ActiveSheet.UsedRange.Rows.Count
lngLstCol = ActiveSheet.UsedRange.Columns.Count

For Each rngCell In Range(Range("B7"), Cells(lngLstRow, lngLstCol))
    If rngCell.Value > "" Then
        rngCell.Select 'Select cells
        With Selection.Borders
            .LineStyle = xlContinuous
            .Weight = xlThin
            .ColorIndex = xlAutomatic
        End With
    End If
Next

Application.ScreenUpdating = True

End Sub

A: You have a condition in the code to exclude the empty cells on this row:
If rngCell.Value > "" Then

Simply comment this row (and its corresponding End If) and you should be all set I think.

A: No need to loop if you just want to add borders to the whole range
Dim lastCell As Range
With ActiveSheet
    Set lastCell = .UsedRange.Cells(.UsedRange.Cells.Count)
    With .Range("B7", lastCell).Borders
        .LineStyle = xlContinuous
        .Weight = xlThin
        .ColorIndex = xlAutomatic
    End With
End With

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selecting text in a TextView makes NestedScrollView scroll down The structure of my layout is this:
NestedScrollView
--ConstraintLayout
----Other Widgets
----TextView with textIsSelectable true
The problem is that if I select some text in the TextView, the NestedScrollView scrolls down.


text:
Q: How to set spark.sql.files conf in pyspark I'm trying to run Hail (https://hail.is/) on a spark cluster. When I try to create a HailContext, I get an error claiming that I have to set two config parameters: spark.sql.files.openCostInBytes and spark.sql.files.maxPartitionBytes
$ pyspark --jars s3://<bucket_name>/hail-all-spark.jar --conf spark.driver.memory=4g --conf spark.executor.memory=4g
Python 2.7.13 (default, Jan 31 2018, 00:17:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Downloading s3://<bucket_name>/hail-all-spark.jar to /tmp/tmp2718520966373391304/hail/hail-all-spark.jar.
18/03/01 10:19:27 INFO S3NativeFileSystem: Opening 's3://<bucket_name>/hail-all-spark.jar' for reading
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
18/03/01 10:19:32 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
18/03/01 10:20:06 WARN ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 2.2.1
      /_/

Using Python version 2.7.13 (default, Jan 31 2018 00:17:36)
SparkSession available as 'spark'.
>>> sc.addPyFile('s3://<bucket_name>/hail-python.zip')
>>> from hail import *
>>> hc = HailContext(sc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<decorator-gen-478>", line 2, in __init__
  File "/mnt/tmp/spark-eebd27bf-b387-4717-9ae5-e94f81438aee/userFiles-fb511f51-35b3-436a-aa5d-d0d84de40851/hail-python.zip/hail/typecheck/check.py", line 245, in _typecheck
  File "/mnt/tmp/spark-eebd27bf-b387-4717-9ae5-e94f81438aee/userFiles-fb511f51-35b3-436a-aa5d-d0d84de40851/hail-python.zip/hail/context.py", line 88, in __init__
  File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
  File "/usr/lib/spark/python/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling z:is.hail.HailContext.apply.
: is.hail.utils.HailException: Found problems with SparkContext configuration:
  Invalid config parameter 'spark.sql.files.openCostInBytes': too small. Found 0, require at least 50G
  Invalid config parameter 'spark.sql.files.maxPartitionBytes': too small. Found 0, require at least 50G
    at is.hail.utils.ErrorHandling$class.fatal(ErrorHandling.scala:6)
    at is.hail.utils.package$.fatal(package.scala:27)
    at is.hail.HailContext$.checkSparkConfiguration(HailContext.scala:116)
    at is.hail.HailContext$.apply(HailContext.scala:169)
    at is.hail.HailContext.apply(HailContext.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

How should I set these parameters correctly? Using --conf spark.sql.files.openCostInBytes=60g creates an IllegalArgumentException
$ pyspark --jars s3://<bucket_name>/hail-all-spark.jar --conf spark.driver.memory=4g --conf spark.executor.memory=4g --conf spark.sql.files.openCostInBytes=60g
Python 2.7.13 (default, Jan 31 2018, 00:17:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Downloading s3://<bucket_name>/hail-all-spark.jar to /tmp/tmp4400881534115197439/hail/hail-all-spark.jar.
18/03/01 10:26:32 INFO S3NativeFileSystem: Opening 's3://<bucket_name>/hail-all-spark.jar' for reading
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
18/03/01 10:26:38 WARN Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
Traceback (most recent call last):
  File "/usr/lib/spark/python/pyspark/shell.py", line 45, in <module>
    spark = SparkSession.builder\
  File "/usr/lib/spark/python/pyspark/sql/session.py", line 183, in getOrCreate
    session._jsparkSession.sessionState().conf().setConfString(key, value)
  File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__
  File "/usr/lib/spark/python/pyspark/sql/utils.py", line 79, in deco
    raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.IllegalArgumentException: u"Error while instantiating 'org.apache.spark.sql.hive.HiveSessionStateBuilder':"

A: Solution is to set spark.sql.files.openCostInBytes and spark.sql.files.maxPartitionBytes to 60000000000 instead of 60g':
$ pyspark --conf spark.sql.files.openCostInBytes=60g --conf spark.sql.files.maxPartitionBytes=60g


text:
Q: How to make sure that every entry in an array is in a table? I have a 'tags' table for an item management system.
I want to make sure that before inserting an item that the tags that are attached to the item are in the 'tags' table.
How do i check that every item in the 'tags' array is in the 'tags' table and if it isn't in the table, insert it into the table.
Thanks
Im using mySQL 5.5

A: You can create a UNIQUE index on tag names, then use INSERT IGNORE to insert the tags:
CREATE TABLE tags (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100)
);
ALTER TABLE tags ADD UNIQUE INDEX uix_name (name);

INSERT IGNORE INTO tags(name) VALUES
('foo'),
('bar');
-- Affected rows: 2

INSERT IGNORE INTO tags(name) VALUES
('foo'),
('baz');
-- Affected rows: 1

INSERT IGNORE INTO tags(name) VALUES
('bar'),
('baz');
-- Affected rows: 0

This will insert only the missing tags in the table.


text:
Q: Centering/Sizing Image for PHAsset Posting a whole lot here lately... Anyways...
Im trying to get the gallery to show what the iPod Photos app will show as the thumbnail. Their thumbnail seems to be centered and all have equal size. For mine, They seem all good, except one image will be smaller.
Here is the code that gets called when I throw these into a table view cell:
func getAssetPhoto(asset: PHAsset, w: Double, h: Double) -> UIImage {
    let manager = PHImageManager.defaultManager()
    var option = PHImageRequestOptions()
    var photo = UIImage()
    var cropSideLength = min(asset.pixelWidth, asset.pixelHeight);
    var square = CGRect(x: 0.0, y: 0.0, width: Double(cropSideLength), height: Double(cropSideLength));

    var cropRect = CGRectApplyAffineTransform(square, CGAffineTransformMakeScale(CGFloat(1.0 / Double(asset.pixelWidth)), CGFloat(1.0 / Double(asset.pixelHeight))));
    option.synchronous = true
    option.normalizedCropRect = cropRect //CGRect(x: 0.5, y: 0.5, width: w, height: h)
    option.resizeMode = .Exact

    manager.requestImageForAsset(asset, targetSize: CGSize(width: w, height: h), contentMode: .AspectFill, options: option, resultHandler: {(result, info)->Void in
        photo = result
    })
    return photo
}

I also can't seem to get it to select the center of the image (tried changing rect to 0.5, 0.5).
Image of example at: http://tinypic.com/view.php?pic=1195tug&s=8#.VYL9PGB8Pdk
The dragon should be centered. The pikachu is smaller than the rest...


text:
Q: Creating new columns based on conditions of the existing columns I have a data.table which contains the following values
structure(list(Item = c("10040", "10040", "10110", "10190", "10190",
"12020", "12970", "7010040"), Customer = c("CLUB RETAILER - 106",
"WHOLESALER - 112", "NATIONAL RETAILER - 102", "MID WEST 1 - 120",
"WHOLESALER - 112", "WHOLESALER - 112", "WHOLESALER - 112", "DIAMLER BENZ - 108"
), DemandID = c("NetBaseForecast", "NetBaseForecast", "NetBaseForecast",
"NetBaseForecast", "NetBaseForecast", "NetBaseForecast", "NetBaseForecast",
"NetBaseForecast"), Forecasts = c(5, 158, 212, 12, 3, 3, 3, 2776
), RTF = c(1, 98, 139, 8, 0, 0, 0, 2356)), row.names = c(NA,
-8L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x00000000025c1ef0>,     sorted = c("Item", "Customer"))

I need to create 2 new columns based on the forecast and rtf columns based on 2 conditions of each row for the Forecasts and RTF columns. I am using a data.table

*

*If Forecast > RTF

*

*New_F = Forecast - RTF

*Com_F = RTF

*If Forecast < RTF

*

*New_F = 0

*Com_F = Forecast

I am currently using a for loop like this
for(i in 1:nrow(temp1NoOrders)){
  if (temp1NoOrders$Forecasts[i] >= temp1NoOrders$RTF[i]){
   temp1NoOrders$Com_F[i] <- temp1NoOrders$RTF[i]
   temp1NoOrders$New_F[i] <- temp1NoOrders$Forecasts[i] - temp1NoOrders$RTF[i]
 }
  else if (temp1NoOrders$Forecasts[i] < temp1NoOrders$RTF[i]){
   temp1NoOrders$Com_F[i] <- temp1NoOrders$Forecast[i]
   temp1NoOrders$New_F[i] <- 0
 }
}

Is there a faster way of doing this with data.table? I am assuming that if I use a 100k row dataset, this might become slower because of the loop and the if-else statements.

A: You don't need to do this line by line. Use fifelse in data.table to check for conditions.
library(data.table)

temp1NoOrders[, c("New_F","Com_F") :=
              .(fifelse(Forecasts > RTF, Forecasts - RTF, 0),
                fifelse(Forecasts > RTF, RTF, Forecasts))]

temp1NoOrders
#      Item                Customer        DemandID Forecasts  RTF New_F Com_F
#1:   10040     CLUB RETAILER - 106 NetBaseForecast         5    1     4     1
#2:   10040        WHOLESALER - 112 NetBaseForecast       158   98    60    98
#3:   10110 NATIONAL RETAILER - 102 NetBaseForecast       212  139    73   139
#4:   10190        MID WEST 1 - 120 NetBaseForecast        12    8     4     8
#5:   10190        WHOLESALER - 112 NetBaseForecast         3    0     3     0
#6:   12020        WHOLESALER - 112 NetBaseForecast         3    0     3     0
#7:   12970        WHOLESALER - 112 NetBaseForecast         3    0     3     0
#8: 7010040      DIAMLER BENZ - 108 NetBaseForecast      2776 2356   420  2356

fifelse is easy to understand but more efficient approach would be to use pmax and pmin :
temp1NoOrders[, c("New_F","Com_F") := .(pmax(Forecasts - RTF, 0),
                                        pmin(Forecasts, RTF))]


text:
Q: Cannot find my app in the Google Play on the tablet I developed and published an app.
build.gradle has
minSdkVersion 11
targetSdkVersion 22
compileSdkVersion 22

and AndroidManifest.xml has

<supports-screens
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        android:anyDensity="true"
        />

App uses features

Now, I have a tablet Asus Nexus 7 with Android 5.1. I can launch the app normally on it when debugging. In the developer console it says that Nexus 7 is supported.

However, I cannot find the app in the Google Play from the tablet. It's invisible for my tablet somehow.

A: Most probably the problem is your following line:
<uses-feature android:name="android.hardware.camera" />

the 2012 model only has a front camera and not a rear camera. This tells the play store that a camera is mandatory for the app to run. So it won't show on devices with ONLY front camera. See Android Camera: require frontal OR rear camera
By default android:required:"true". This means that only devices with atleast a rear camera will be able to see this. You can add android:required="false" tag which will tell the play store that a camera is not mandatory for it to show on app store.


text:
Q: How to get wrapping element of a string using regex
Possible Duplicate:
get wrapping element using preg_match php

I want to get the element that wraps a specified string, so example:
$string = "My String";
$code = "

My String

";

So how am i able to get

 that wraps the string by matching it using regex pattern.

A: Using the DOM Classes of PHP you are able to do so.
$html = new DomDocument();
// load in the HTML
$html->loadHTML('

My String

');
// create XPath object
$xpath = new DOMXPath($html);
// get a DOMNodeList containing every DOMNode which has the text 'My String'
$list = $xpath->evaluate("//*[text() = 'My String']");
// lets grab the first item from the list
$element = $list->item(0);

now we have the whole
-tag. But we need to remove all child nodes. Here a little function:
function remove_children($node) {
  while (($childnode = $node->firstChild) != null) {
    remove_children($childnode);
    $node->removeChild($childnode);
  }
}

let's use this function:
// remove all the child nodes (including the text 'My String')
remove_children($element);

// this will output '

'
echo $html->saveHTML($element);


text:
Q: prob in implementing kmeans++ in r I am actually tring to get db index for k=2:63. This problem occurs when I run kmeans in a loop otherwise it does not show error.
Here is my main function
for(i in 2:63) {
  print(i)
  # kmeans++ algorithm
  r_cluster_result = kmpp(r_cluster_mat,i)
  r_cluster_data = data.frame(r_cluster_result$cluster)
  db = index.DB(x=r_cluster,cl=r_cluster_result$cluster,d=NULL,centrotypes="centroids",p=2,q=1)
  db_values = c(db_values,db$DB)
}

Here is my kmeans++ function code
kmpp <- function(X, k) {
  n <- nrow(X)
  C <- numeric(k)
  C[1] <- sample(1:n, 1)

  for (i in 2:k) {
    dm <- distmat(X, X[C, ])
    pr <- apply(dm, 1, min);
    pr[C] <- 0
    C[i] <- sample(1:n, 1, prob = pr)

  }

  kmeans(X, X[C, ])
}

Error msg
Error in sample(1:n, 1, prob = pr) : NA in probability vector
In addition: Warning message:
In sqrt(XX + YY - 2 * XY) : NaNs produced

dput(X) is
dput(x)


text:
Q: get XML data from API using RJSDMX R I am trying to get the XML data imported into R.
Specifically, the World Integrated Trade Solution (WITS) to obtain bilateral trade levels between all countries.
On the WITS website, it says that the official package that connects to their API is RJSDMX, but I'm having a hard time downloading the data.
Package use example:
https://rstudio-pubs-static.s3.amazonaws.com/593878_b305636e73314eba87615097421034b3.html
WITS API documentation:
http://wits.worldbank.org/data/public/WITSAPI_UserGuide.pdf
This is my code so far:
library(RJSDMX)
org <- "WITS"

# Get trade flows using the RJSDMX package
# https://rstudio-pubs-static.s3.amazonaws.com/593878_b305636e73314eba87615097421034b3.html
flow <- getFlows("WITS")
flow$`WBG_WITS,DF_WITS_TradeStats_Trade,1.0`

#parse "WITS" dataflow
fas_dataflow <- strsplit(names(flow[3]),",")
idx <- 1
#if Case 2 found, then get the second element
ifelse(length(fas_dataflow[[1]]) > 1, idx <-2, idx <-1)
fas_dataflow <- fas_dataflow[[1]][idx]

#get list of dimensions of "Average duration of unemployment" DSD
fas_dimensions <- getDimensions(org, fas_dataflow)

#use flatten to remove first level of indices
fas_codelist <- map(.x = names(flatten(fas_dimensions)),
                    flow = fas_dataflow,
                    provider = org,
                    .f = getCodes) %>% set_names(names(flatten(fas_dimensions)))
getCodes(org, fas_dataflow, "FREQ")
getCodes(org, fas_dataflow, "REPORTER")
getCodes(org, fas_dataflow, "PARTNER")
getCodes(org, fas_dataflow, "PRODUCTCODE")
getCodes(org, fas_dataflow, "INDICATOR")
# this doesn't work
emoney_trx_id <- as_tibble(sdmxdf(getTimeSeries(org,"A.MPRT-PRTNR-SHR")))
# neither does this
emoney_trx_id <- as_tibble(sdmxdf(getTimeSeries(org,"A....MPRT-PRTNR-SHR")))
# and neither does this
emoney_trx_id <- as_tibble(sdmxdf(getTimeSeries(org,"A....MPRT-PRTNR-SHR.reported")))
# or this
emoney_trx_id <- as_tibble(sdmxdf(getTimeSeries(org,"A.MPRT-PRTNR-SHR.reported")))

Forgive me if this is an obvious question, but I have limited experience working with XML APIs.
Thank you in advance!!

A: EDIT: I was able to get the WITS bilateral trade flows directly through the URL on the API documentation page. See also Parsing XML to DATA FRAME
The resulting code looks like so:
# Set link to website
link1 <-"http://wits.worldbank.org/API/V1/SDMX/V21/datasource/tradestats-trade/reporter/all/year/2018/partner/all/indicator/MPRT-PRTNR-SHR"

# Get data from webpage
data_prices <- getURL(link1)

# Parse XML data
xmlfile <- xmlParse(data_prices)

# Get place nodes
places <- getNodeSet(xmlfile, "//Series")

# Get values for each place
values <- lapply(places, function(x){
  # Get current place id
  pid <- xmlAttrs(x)

  # Get values for each gas type for current place
  newrows <- lapply(xmlChildren(x), function(y){
    # Get type and update time values
    attrs <- xmlAttrs(y)

    # Get price value
    price <- xmlValue(y)
    names(price) <- "price"

    # Return values
    return(c(pid, attrs, price))
  })
  # Combine rows to single list
  newrows <- do.call(rbind, newrows)

  # Return rows
  return(newrows)
})

# Combine all values into a single dataframe
df <- as.data.frame(do.call(rbind, values), stringsAsFactors = FALSE)


text:
Q: How to link index.html (gcloud app deploy)? How would I link the index.html? I am deploying in Google Cloud Platform (using gcloud app deploy). This is so I can make the website with the html. I need a example with a html provided here (any of three html is fine). The index.html is where someone navigates to the root page of your website, what the person sees when clicking or going to the link of the site. My html specifically is just a "hello world" type website. And my files are located in my project (website-deploying-gc). This is the final step to create the site. Here is where the html is located (after getting into the files):
jinthemix@cloudshell:~ (website-deploying-gc)$ ls
app.yaml  IMD233  Files  README-cloudshell.txt  README.md  www
jinthemix@cloudshell:~ (website-deploying-gc)$ cd www
jinthemix@cloudshell:~/www (website-deploying-gc)$ ls
Mixs
jinthemix@cloudshell:~/www (website-deploying-gc)$ cd Mixs
jinthemix@cloudshell:~/www/Mixs (website-deploying-gc)$ ls
'Mix 1 (1)'  'Mix 2 (2)'  'Mix 3 (3)'  'Mix 4 (4)'
jinthemix@cloudshell:~/www/Mixs (website-deploying-gc)$ cd 'Mix (1)'
jinthemix@cloudshell:~/www/Mixs/Mix 1 (1) (website-deploying-gc)$ ls
'hello.html (B) (L2).html'  'hello.html (T) (L3).html'  'hello (L1).html'
jinthemix@cloudshell:~/www/Mixs/Mix 1 (1) (website-deploying-gc)$ cd
jinthemix@cloudshell:~ (website-deploying-gc)$ cd

Here is a reference link as well, that may provide more information. The site also talks about the index.html. The index.html is basically shows "hello world" to anyone viewing the website: https://cloud.google.com/appengine/docs/standard/python/getting-started/hosting-a-static-website
Any help is appreciated, thanks

A: I see the link you are using points to deploying a Python 2 application in App Engine. Take into consideration that the programming language itself (Python 2) is no longer supported by the community since at least January 1st 2020 so I'd strongly suggest you to use a similar tutorial for Python 3 (find the link here).
In order to serve static files (e.g. an index.html file that you are referring to) App Engine can handle URLs by executing application code (in the specific tutorial you are following this will consist on modifying your Flask application to serve a static file, as e.g. is described here), or by serving static files uploaded with the code and taking advantage of the handler element defined in your app.yaml file.
The comments within the app.yaml file on the tutorial I linked  for Python 3 explain this in a very understandable way:
runtime: python39

handlers:
  # This configures Google App Engine to serve the files in the app's static
  # directory.
- url: /static
  static_dir: static

  # This handler routes all requests not caught above to your main app. It is
  # required when static routes are defined, but can be omitted (along with
  # the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto

Notice that you basically define a URL and use an element such as static_dir or static_files to serve that file when a customer lands that specific URL in your application.


text:
Q: Data-structure sorted by value I am trying to store a score for a large about of players.  So I will need a map that is sorted based on the value, but because of the amount of players it's inefficient to sort it each time I retrieve it.  I would also like the ability to find a players rank in the map.  It would be very similar to the score datatype in redis.
Something like:
    ScoreMap<String, Integer> scores = new ScoreMap<String, Integer>();

    scores.put("Bill", 2);
    scores.put("Tom", 6);
    scores.put("Jim", 3);
    scores.put("Jake", 3);

    System.out.println("Rank = " + scores.getRank("Bill"));

    System.out.println();
    System.out.println("All:");
    for (Entry<String, Integer> entry : scores.entrySet()) {
        System.out.println(entry.getKey() + " => " + entry.getValue());
    }

    System.out.println();
    System.out.println("Rank Range:");
    for (Entry<String, Integer> entry : scores.entryRankRange(0, 2)) {
        System.out.println(entry.getKey() + " => " + entry.getValue());
    }

    System.out.println();
    System.out.println("Score Range:");
    for (Entry<String, Integer> entry : scores.entryScoreRange(2, 3)) {
        System.out.println(entry.getKey() + " => " + entry.getValue());
    }

This would return
    Rank = 3

    All:
    Tom => 6
    Jake => 3
    Jim => 3
    Bill => 2

    Rank Range:
    Tom => 6
    Jake => 3
    Jim => 3

    Score Range:
    Jake => 3
    Jim => 3
    Bill => 2

I know this is kinda specific and I will probably have to make a custom data-structure.  But a point in the right direction would be much appreciated.  :)

A: Simplest way to do this would be to use a Set (namely, TreeSet) and encapsulate the player information (including the score) into a specific class:
public class CompetitivePlayer implements Comparable<CompetitivePlayer>{

    private String name;
    private int score;

    public CompetitivePlayer(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    public void incrementScore() {
        score++;
    }

    @Override
    public int compareTo(CompetitivePlayer o) {
        return score - o.score;
    }
}

TreeSet assumes that entires stored in it implement the Comparable interface for determining the natural ordering of its elements.
Edit:
If you need to frequently modify the scores of players, then a Map<String, Integer>-based solution is a better fit, because there's no get in Java's Set. This thread discusses the Map-based approach in great detail.
One simplictic solution (as suggested in the mentioned thread) is a one-liner, using the Guava library:
Map<String, Integer> sortedScores = ImmutableSortedMap.copyOf(scores,
    Ordering.natural().onResultOf(Functions.forMap(scores)));

A: Use Collections.sort() and provide a custom Comparator to sort a map based on its values:
Collections.sort( map, new Comparator<Map.Entry<K, V>>()
{
    @Override
    public int compare( Map.Entry<K, V> entry1, Map.Entry<K, V> entry2)
    {
        return (entry1.getValue()).compareTo( entry2.getValue() );
    }
} );

A: Can you rewrite your name and score as a class player, then you can use TreeSet to keep the order, and override equals() and compareTo(), it seems like you want to use name as identifier, and keep players ordered by score, then you can do
@Override
public boolean equals(Object obj) {
    if(obj instanceof Player)
        return this.name.equals(((Player)obj).name);
    return false;
}
@Override
public int compareTo(Player p) {
    return p.score - this.score;
}


text:
Q: How is + as an infix operator associated with Plus? How is + associated with Plus?  Suppose I want to define a head FooBar and have it associated with a unicode character of my choice, ideally used as an infix form, i.e.
FooBar[x, y]

is equivalent
x ↗ y

as seen by the kernel.  How this kind of thing can be done?

A: Maybe I miss the point here, but
FullForm[x ↗ y]

gives UpperRightArrow[x,y]. This is described in the documentation to UpperRightArrow and since this symbol is not protected and has not built-in meaning, you can just define it the way you like:
UpperRightArrow[x_, y_] := FooBar[x, y]

and this instantly gives you

Update: As answer to Jacobs comment I want to point out, that I defined the FooBar definition so verbosely to show, that it works like a normal function definition. Of course, the most easy method is just to say
UpperRightArrow = FooBar

About your first question, I can only make an educated guess, because I don't know the implementation. The association of the infix + and the Plus happens during parsing, because what you see when you use something like FullForm[Expand[(a + b)^3]] is the parse tree after the expression was evaluated.
In the official docs, I found only in the tutorial Operators without Built-in Meanings a hint to your question:

When you enter a piece of input such as 2+2, Mathematica first recognizes the +  as an operator and constructs the expression Plus[2, 2], then uses the built-in rules for Plus to evaluate the expression and get the result .

A: I can't answer how the association is made for the built-in operators, but I can show how to add your own.  If your symbol is already an operator you can do this simply as halirutan showed.
This question may be a duplicate of How can one define an infix operator with an arbitrary unicode character? but since it admits a simpler interpretation I shall not close it as such.  Drawing from both Jens' and my own answer we can do the following.  It requires editing a low level system file, so make careful back-ups.  The format is described in the linked Q&A.
Here I will define an entirely new operator I shall call PennyOp, with a Unicode character mapping and an input alias.
Find your UnicodeCharacters.tr file in SystemFiles\FrontEnd\TextResources\ or using the path given by:
System`Dump`unicodeCharactersTR

(at least in version 10.1 one can also copy this file to the matching path in $UserBaseDirectory)
and add this line:
0x20B0      \[PennyOp]      ($penny$)    Infix       155     None        5       5

You can then use EscpennyEsc to enter the operator, which is recognized as such:

Adding Jens' MakeExpression definition:
MakeExpression[RowBox[{x_, "\[PennyOp]", y_}], StandardForm] :=
  MakeExpression[RowBox[{"PennyOp", "[", x, ",", y, "]"}], StandardForm]

Now:

You can define PennyOp as you would any other Symbol:
PennyOp[n_Integer, s_String] := "" <> Riffle[Table[s, {n}], " "]

5 \[PennyOp] "word"

"word word word word word"

Presto, custom Unicode-character operator with custom precedence and binding.  It will only work in the Front End however.

A: The Notation package is the most convenient way to define new notation(s).
<<Notation`

Define an infix notation. You can use the palette that the 'Notation` package pops up to do this.
InfixNotation[ParsedBoxWrapper["\[UpperRightArrow]"], FooBar]

Check that the infix notation maps to the correct FullForm expression.
x \[UpperRightArrow] y // FullForm


text:
Q: Offline map script I'm making a website with a ground plan on it. First I used google maps for the functions it has, but my boss told me that the site will also run on computers with no internet access.
Then I used jquery geo but it misses some stuff that I need (like markers). And it's a alpha version.
The thing I need is a script that I can download that shows my own map tiles and has markers where I can click on. The map needs to pan and zoom.
Does someone knows a library that does it?


text:
Q: UIImagePickerController dismissing when it shouldn't I am trying to create a custom camera overlay, but am having some problems. The capture view works great, but I would like to show another view where the user can edit the photo after the image is captured. The problem is that when a photo is taken, the view with the photo is automatically dismissed. How would I fix this so that I can show another view controller after the user takes a photo.
Here is how I create the picker:
self.cameraPicker = [[UIImagePickerController alloc] init];
self.cameraPicker.delegate = self;
self.cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.cameraPicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
self.cameraPicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
self.cameraPicker.showsCameraControls = NO;
self.cameraPicker.allowsEditing = YES;
self.cameraPicker.navigationBarHidden = YES;
self.cameraPicker.toolbarHidden = YES;
self.cameraPicker.videoQuality = UIImagePickerControllerQualityTypeIFrame1280x720;
self.frontFacing = NO;
self.gridShowing = NO;
self.showingFlash = NO;

// Insert the overlay
CameraOverlayView *overlay = [[CameraOverlayView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
self.cameraPicker.cameraOverlayView = overlay;
overlay.delegate = self;

[self.navigationController presentViewController:(UIViewController *)self.cameraPicker animated:YES completion:nil];

Here is how I take the photo, after this is called, the viewController is dismissed:
, which I do not want:
    [self.cameraPicker takePicture];


text:
Q: HTML "style" tag doesn't work I tried the following code in both online editor in w3schools & pen editor in codepen. Here is that code.

body {
 background-color: lavenderblush
}
.red-text {
  color: red;
}
h1 {
  font-family: Tangerine, times new roman;
  font-size: 55px;
}
p {
  font-size : 18px;
  font-family: inconsolata;
}
.thick-salmon-border {
  border-color: salmon;
  border-width: 5px;
  border-style: solid;
  border-radius: 50%;
}
.smaller-image {
  width: 120px;
  height: 120px;
}

.thick-royalblue-border {
  border-color: royalblue;
  border-width: 5px;
  border-style: solid;
  border-radius: 50%;
}
.thick-green-border {
  border-color: green;
  border-width: 5px;
  border-style: solid;
  border-radius: 50%;
}

.thick-sandybrown-border {
  border-color: sandybrown;
  border-width: 5px;
  border-style: solid;
  border-radius: 50%;
}
.thick-lightpink-border {
  border-color: lightpink;
  border-width: 5px;
  border-style: solid;
  border-radius: 50%;
}
.thick-rosybrown-border {
  border-color: rosybrown;
  border-width: 5px;
  border-style: solid;
  border-radius: 50%;
}
.box {
  border-style: solid;
  border-color: rosybrown;
  border-width: 5px;
}
 .AntiqueWhite-box {
  background-color: AntiqueWhite;
  padding: 20px;
  margin: 20px;
}
 .MistyRose-box {
  background-color: MistyRose;
  padding: 20px;
  margin: 20px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Rancho&effect=shadow-multiple">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inconsolata">

My Favorite Songs

Ed Sheeran

Shape of You

Thinking Out Loud

Galway Girl

    <form action="/submit-Ed Sheeran" id="Ed Sheeran-form">

            <input type="radio" name="reaction" checked>Like

            <input type="radio" name="reaction">Dislike

            <input type="radio" name="reaction">None of Above

            <input type="checkbox" name="electronic devices" checked>Phone

            <input type="checkbox" name="electronic devices">Laptop

            <input type="checkbox" name="electronic devices">Mp3

        <input type="text" placeholder="Ed Sheeran URL">
        <button type="submit">Submit</button>
    </form>

Adele

Rolling In the Deep

Someone Like You

Hello

            <form action="/submit-Adele" id="Adele">

                    <input type="radio" name="reaction" checked>Like

                    <input type="radio" name="reaction">Dislike

                    <input type="radio" name="reaction">None of Above

                    <input type="checkbox" name="electronic devices" checked>Phone

                    <input type="checkbox" name="electronic devices">Laptop

                    <input type="checkbox" name="electronic devices">Mp3

                <input type="text" placeholder="Adele URL">
                <button type="submit">Submit</button>
            </form>

BTW, I ran this in "Edge" browser in windows. What's wrong?
This code worked fine until yesterday, but now css doesn't work. Did something change in w3schools or codepen? Is there a type-o? Please help.

A: First : Use head taq(required):

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">

Second : Use style code like this (not required) :

Third : Put ; in end of your css code(in end of line 6) (not required):
 body {
   background-color: lavenderblush;
  }

I hope  second and third help you .
:)

A: It's working correctly on my side in codepen.
you should try to hard refresh(ctrl+F5)
OR
Clear cache and cookies then load the page
OR
Try a hardcore versioning e.g. add ?1 or any thing after ? in URL and then hit URL.
e.g.
http://<your URL>.html?1

The best practice is to use styles and scripts in  tag as it'll be loaded before the page and you'll see the design at its best. If it doesn't get solved then above solution will work if it's cache related issue.

Use Style in

A: It might be a hunch, but you said it worked until yesterday. Try clearing your
browser cache.
https://support.microsoft.com/en-us/help/10607/microsoft-edge-view-delete-browser-history
Hope this helps!

A: You mistake is a semicolon in your body tag background-color property
 body{
   background-color: lavenderblush;
  }


text:
Q: Ambiguity regarding adjective/adverb status in the sentence "I smell bad" For sentences like "I smell bad" I'm confused on the role.of the word "bad" and whether it requires a suffix. On the one hand it seems that the properly formed sentence should be "I smell badly" but on the other hand it seems to mean something entirely else.
Are these two different, well-formed sentences (bad vs badly)? Is the first (bad) just a convention of conversation and only the latter form (badly) valid but just ambiguous (do I mean that I smell of badness or that I have no talent for scent?)?

A: If you smell badly, your olfaction skills are poor.  If you smell bad, the odor you emit is distasteful.

A: In your example, bad is a complement, because the verb smell is a copula.
1,TRANSITIVE verbs:

I draw portraits.
  I write poems (I write poems badly)
  I smell sulphur, (I smell mint / sulphur faintly)
  'I smell badly or well' is the transitive or intransitive homonym.

the adverb describes the verb
2. INTRANSITIVE verbs:

I stare / I stare vacantly.
  I meditate / I meditate profoundly.

the adverb describes the verb
3.COPULAs (not long ago called copulatives) can be followed by complements which can be nouns or adjective:

I am (+adjective) aware / fully aware.
  I smell bad / I smell really bad.
  The meat smells bad / the meat smells slightly bad.

(the adverb describes the complement not the verb)

I am (+ noun) a student / I am an overage student.
  I smell a rat / I smell a figurative  rat.

(the adjective describes the complement)


text:
Q: c++ variable initialization in a class to send it using mpi I got stuck in a programming task. I want the elements of my stl vector to be placed in a
contiguous memory to send it with MPI_Send() routine.
here is an example:
class Tem
{

//...
private:
 vector<double> lenghtVector (4500);//this gives a compilation error but I need to have a fixed sized vector

};

how can I have a vector with a serial memory of should I do something else?
Thanks.
Kindest Regards.
SRec

A: The elements of a vector are stored contiguously according to C++ Standard (23.2.4/1). To resize it you could use appropriate constructor in the initializer list of Tem class.:
class Tem
{
  Tem() : lenghtVector(4500) {};
private:
 vector<double> lenghtVector;
};

A: vector will do what you want, as the data is guaranteed to be contiguous.  Use &(v[0]) to get a pointer that you can pass to MPI_Send().
If you don't need the dynamic sizing of vector, you might want to look at the Boost Array class.  The size is fixed at compile time, but it is an STL compatible container, so you get begin(), end(), size(), etc.


text:
Q: Does 'gritted' work here?
"He gritted his teeth."

I can't tell if gritted is correct because both gritted and grit don't sound right to me in this sentence.
The dictionary says that both grit and gritted are the past tense. (Nowhere does it say 'grot' btw)
In the grit vs gritted they're asking which one is correct when they both technically are and the answers for it aren't useful to me, plus I am asking how it fits in t h i s sentence because I know grit can fit into other sentences, but I wasn't sure if it would fit in mine.

A: According to Google's Ngrams, gritted is definitely more common.

Interestingly, it appears that women didn't grit their teeth in any significant numbers until the mid '70s.


text:
Q: Issue with volume calculation enter image description here
Please find the attached file, Why I can't calculate the volume for any object?
This message does appear when I use the Mac or Windows.
Regards,
  Ali

A: This error will be generated only if the mesh is not watertight, i.e. either the mesh has some boundary edges (holes) or some non-manifold edges.
Try with some different models to confirm. For example, generate a sphere in MeshLab (Filters -> Create New Mesh layer -> Sphere) and calculate volume.
PS: You can remove non-manifold edges in MeshLab and close the holes to make the model watertight.


text: Q: Get Server date from Sharepoint server 2010 as a SOAP request I am trying to get the Sharepoint date/time and local time offset as a SOAP request. Is this actually possible? What should my SOAP request look like?


text:
Q: mysql how to make a query through bash script How to make a mysql statement or query through bash script?? for example create a user and a database??
i'm trying through a bash script to run a simple mysql statement

echo "insert database name"
read $db
echo "insert username "
read varname
echo "insert password for the user "
read -s varpass

sudo mysql -u root  -e <<EOF
CREATE DATABASE $db;
CREATE USER '$varname'@'localhost' IDENTIFIED BY '$varpass';
GRANT ALL ON $db.* TO '$varname'@'localhost' IDENTIFIED BY '$varpass' WITH GRANT OPTION;
FLUSH PRIVILEGES;
EXIT;
EOF

A: You can try this.
test.sh
#!/bin/bash

echo "insert database name"
read db
echo "insert username "
read varname
echo "insert password for the user "
read -s varpass

sudo mysql -u root mysql<<EOF
CREATE DATABASE $db;
CREATE USER '$varname'@'localhost' IDENTIFIED BY '$varpass';
GRANT ALL ON $db.* TO '$varname'@'localhost' WITH GRANT OPTION;
FLUSH PRIVILEGES;
\q
EOF

Note the changes:

*

*read $db was changed to read db - the $ was removed

*Database name was added before <<EOF

*Exit was replaced with \q

What if your database had a password
You could create a file ~/.my.cnf with the following contents:
[client]
user=root
password=YourPassword123!!

Then, you can log on to mysql's mysql database using the command mysql mysql. Using that, you can change just the <<EOF line to:
mysql mysql<<EOF

Everything else can remain the same.


text:
Q: EDIFACT grammar, parsers and libraries (Java)
*

*I am wondering if we can define EDIFACT grammar in ANTLR/xText and then generate parser.

*If so, are these grammars defined already that we can leverage (open source preferably)?

*Are there any open source libraries that can read and write EDIFACT other than Smooks?

A: From a handy book on the subject... (http://books.google.co.uk/books?id=rDbRS6vEG0MC&pg=PA222&lpg=PA222&dq=EDIFACT+bnf&source=bl&ots=pfFYf4nsVv&sig=JXY5HPo7Ka02ji35fjW8R8wFBX8&hl=en&sa=X&ei=05ozT6K5NMO80QWa-ZSLAg&ved=0CGEQ6AEwCA#v=onepage&q=EDIFACT%20bnf&f=false) we have the following section...
, which appears to suggest that it's not a good idea - although depending on what you require you can certainly write one, I would personally find Antlr an easier tool to use (I'm currently writing a lab for Xtext and it's a less forgiving learning curve), but your milage may vary...

A: I tried this approach (using ANTLR) when I developed bots open source edi translator (http://bots.sourceforge.net).
This looked like a good approach, but I did not succeed.
My conclusion was that 'parsing' by ANTLR is something very different than 'parsing' an edi-file; the words/concepts sound the same but these are really different worlds.
If you are looking for 'grammars'(that is: descriptions of edifact and x12 messages) these can be found in the downloads of the sourceforge page.


text:
Q: Do I use a comma to separate "From.... to"? At about three o'clock, the professor transitioned from the topic of communication, to the topic of political correctness.
or
At about three o'clock, the professor transitioned from the topic of communication to the topic of political correctness.

A: The comma is superfluous in my opinion because it breaks up the flow of the sentence more than necessary. In this case, the "to" portion still forms part of the main clause and is a vital part of the sentence.
See this rule from Purdue University's rules of comma usage:

*Do not use commas to set off essential elements of the sentence, such as clauses beginning with that (relative clauses). That clauses after nouns are always essential. That clauses following a verb expressing mental action are always essential.

https://owl.english.purdue.edu/owl/owlprint/607/


text:
Q: When to use floc and fscale parameters in scipy? Although I have read lots of posts about fitting  distributions in python, I am still confused about usage floc and fscale parameters. For general information I mainly used this, this and this sources.
I know, that given distribution lets say f(x) becomes more general distribution when using loc and scale parameters, which can be described by formula
f(x) = f((x-loc)/scale).
In scipy, we have to choice. When fitting a distribution, using formula distr.fit(x), the initial guess of loc parameter is 0 and initial guess of fscale parameter is 1 (so that we assume that the parametrized distribution is close to nonparametrized distribution). We can also force scipy to fit 'original' distribution f(x) using distr.fit(x, floc = 0, fscale = 1).
My question is: is there any general advice when to force scipy to fit 'original distribution' besides the 'parametrized one'?
Here is the example:
# generate some data
from scipy.stats import lognorm, fisk, gamma
from statsmodels.distributions.empirical_distribution import ECDF
import numpy as np
import matplotlib.pyplot as plt

x1 = [18. for i in range(36)]
x2 = [19. for i in range(17)]
x3 = [22. for i in range(44)]
x4 = [27. for i in range(63)]
x5 = [28.2 for i in range(8)]
x6 = [32. for i in range(104)]
x7 = [32.6 for i in range(29)]
x8 = [33. for i in range(85)]
x9 = [33.4 for i in range(27)]
x10 = [34.2 for i in range(49)]
x11 = [36. for i in range(99)]
x12 = [36.2 for i in range(35)]
x13 = [37. for i in range(98)]
x14 = [38. for i in range(25)]
x15 = [38.4 for i in range(39)]
x16 = [39. for i in range(25)]
x17 = [42. for i in range(54)]

# empirical distribution function
xp = x1 + x2+x3+x4+x5+x6+x7+x8+x9+x10+x11+x12+x13+x14+x15+x16+x17
yp = ECDF(xp)

# fit lognormal distribution with parametrization
pars1 = lognorm.fit(xp)
# fit lognormal distribution with floc = 0
pars2 = lognorm.fit(xp, floc = 0)
#plot the result
X = np.linspace(min(xp), max(xp), 10000)
plt.plot(yp.x, yp.y, 'ro')
plt.plot(X, lognorm.cdf(X, pars1[0], pars1[1], pars1[2]), 'b-')
plt.plot(X, lognorm.cdf(X, pars2[0], pars2[1], pars2[2]), 'g-')
plt.show()

#fit the gamma distribution
pars1 = gamma.fit(xp)
pars2 = gamma.fit(xp, floc = 0)
#plot the result
X = np.linspace(min(xp), max(xp), 10000)
plt.plot(yp.x, yp.y, 'ro')
plt.plot(X, gamma.cdf(X, pars1[0], pars1[1], pars1[2]), 'b-')
plt.plot(X, gamma.cdf(X, pars2[0], pars2[1], pars2[2]), 'g-')
plt.show()

As you can see, the floc = 0 improved a lot the fit in lognorm case, in gamma case it didint change the fit at all.
Sorry for long demontration, here is my question again: Is there any general advice when to specify floc = 0 and fscale = 1 and when to use custome loc = 0 and scale = 1?

A: Short answer
Provide some guess-estimates for loc and scale whenever you are able. Provide floc and fscale only when you actually need this for your subsequent use of the model; that is, if an answer with, say, distribution mean different from 0 is just not acceptable to you.
For example, if you model elastic force by Hooke's law F = k*x and want to find k from experimental force F and deformation x, there is no use in fitting a general linear model k*x+b; we know that zero force produces zero deformation. Any nonzero value of b may achieve better fit but only because it follows experimental errors better, which isn't the goal. So this is a situation where we want to force a certain parameter to be zero.
Never use  floc or fscale if you just want to improve the fit; use loc and scale instead.
Explanation
Fitting a distribution to data is a multivariable optimization problem. Such problems are difficult and solvers frequently fail when the starting point is far from the optimal. If floc gives better result than unconstrained fit, that only means the unconstrained fit failed.
To improve the outcome, you should provide tentative loc and scale parameters whenever you are able to come up with something reasonable.
In your lognormal example, you compare not giving any hint to imposing the restriction floc=0.  But the best strategy is just to give a hint with loc=0:
pars1 = lognorm.fit(xp, loc=0)

The resulting blue curve is better than the green one with floc=0.

Of course it is better. loc=0 points the optimizer to a pretty good place to start, and lets it work from there. floc=0 points the optimizer to a pretty good place to start, but then tells it to stay there.


text:
Q: Forming a shell script from html and sending it back to server and executing and monitoring it I want to complete the following flow:
a. Form a shell script from input given by user and send the inputs in form of a shell script back to server.
b. Execute the shell script and once shell script execution finishes then send a mail to user.
I am using CGI for completing job a but I have got no clue how to go by for job b but want to use CGI for the same.
Any help will be appreciated.
All this is done in Linux(SUSE)
Thanks!


text:
Q: "e.preventDefault()" or "return false" get me to the top jQuery:
$("#envoyer_comm").click(function(e){
    comment_value = $("#text_commentaire").val();
    $.get("set_commentaire.php", {idP:idPhoto, commentaire:comment_value});
    param = "idP=" + idPhoto;
    $("#les_commentaires").load("load_commentaire.php", param);
    $("#text_commentaire").val("");
    e.preventDefault();
});

set_commentaire.php :
<?php
session_start();
$bdd = new PDO('mysql:host=127.0.0.1;dbname=pure', 'root', 'Starwars');
$insert_com = $bdd->prepare("INSERT INTO commentaire (idUserCom, idPhoto, commentaireValue) VALUES (?,?,?)");
echo $_GET['idP'].$_GET['commentaire'];
$insert_com->execute(array(1,$_GET['idP'], $_GET['commentaire']));
?>

load_commentaire.php:
<?php
session_start();
$bdd = new PDO('mysql:host=127.0.0.1;dbname=pure', 'root', 'Starwars');
$req_commentaire = $bdd->prepare("SELECT * FROM commentaire WHERE idPhoto = ? ORDER BY idCom ASC");
$req_commentaire->execute(array($_GET['idP']));
?>

        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css?v=1.1">

        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <title>Pure</title>

        <?php
        while($resultat = $req_commentaire->fetch()){
            $req_user = $bdd->prepare("SELECT * FROM utilisateur WHERE idUser = ?");
            $req_user->execute(array($resultat['idUserCom']));
            $userinfo = $req_user->fetch();
            echo "

".$userinfo['pseudo']."
".$resultat['commentaireValue']."

";
        }   ?>

envoyer_comm is just a button :
<button id="envoyer_comm">Envoyer</button>

I don't want my webpage to refresh after this function.
e.preventDefault();

or
return false;

do the job but it takes me to the top of my page, i want it to stay where i am
Any ideas ?


text:
Q: Creating and handling random number of queues in c I'm creating a program that needs to be able to create/handle a number of queues.
I used this code to work with 1 queue in programs. If I wanted to add more queues based on this code how exactly do I do it? And will there be a problem if each queue's size is varying depending on random number generation?
typedef int Item;
typedef struct node *link;
struct node{
    Item data;
    link next;
};

int QUEUEempty(link head){
    return head == NULL;
}

void QUEUEput(link *head, link *tail, Item data){
    if (*head == NULL){
        (*tail) = (link)malloc(sizeof(node));
        (*tail)->data = data;
        (*tail)->next = NULL;
        *head = *tail;
        return;
    }
    (*tail)->next = (link)malloc(sizeof(node));
    *tail = (*tail)->next;
    (*tail)->data = data;
    (*tail)->next = NULL;
    return;
}
Item QUEUEget(link *head){
    Item data = (*head)->data;
    link t = *head;
    *head = (*head)->next;
    free(t);
    return data;
}


text:
Q: Deploying hybrid app sample in Tizen I am trying to run a hybrid app sample in Tizen 3 with no success.
I created both native service  and web app from samples. Then I added the service into web app multi package.
I verified that wgt file contains both webapp and native service files.
When web app runs in the device it can connect to the service but command messages do not reach the service.
What I think the problem is that the service has moved into suspended state and so not responding to web app messages.
What am I missing to deploy hybrid app samples?
Is there anything special (privilege or feature) I should add to force native service to stay awake to receive commands from web app?

A: It worked after changing servie app id in web service!
Initially app.js has SERVICE_APP_ID in org.example.hybridservice format.
I changed it into xxxxxxxxxx.hybridservice where xxxxxxxxxx is web app id prefix. Same app id can be copied from tizen-manifest.xml file in .wgt file.


text:
Q: Does SUSE SLES 12 SP5 supports Oracle OpenJDK 11? I wanted to know does  SUSE SLES 12 SP5 supports oracle openjdk-11 or not?
As when i am trying to install and run it in SLES12 sp5  then i am getting the error
Error: dl failure on line 598
Error: failed Java/Sun-JRE/11.0.11/lib/server/libjvm.so, because /lib64/libm.so.6: version `GLIBC_2.27' not found (required by Java/Sun-JRE/11.0.11/lib/server/libjvm.so)

Means the current GLIBC version in my OS is 2.22 and oracle openjdk-11 requires a minimum of GLIBC version of 2.27 and higher.

So can anyone please let me know if SUSE SLES 12 SP5 supports oracle-openjdk-11 or not?

A: It stated clearly at the official SUSE website with L3 support link
Unless your might be using any unofficial repositories which are not supported by SUSE


text:
Q: LessCSS: lazy-loading of unlocked variable reversed In reference to this SO post and the docs.
If you simply define a variable twice, the 2nd definition gets lazy loaded as expected but if you do this through a mixin, it seems to be reversed, so the first unlock is applied.
.mixin(@input) {
  @width: @input;
}

.selector {
  width: @var;
}

@var: 30px;
@var: 40px;

.mixin(20px);
.mixin(30px);

.selector-2 {
  width: @width;
}

Output:
.selector {
  width: 40px;
}
.selector-2 {
  width: 20px;
}

Can someone explain this?

A: Variable in a mixin is exposed into its calling scope only if the scope does not already have such variable defined. (There's no dedicated section in the docs, but it's mentioned here).
In your example .mixin(30px) has no effect because @width is already unlocked into the scope by the previous .mixin call (i.e. .mixin(20px)).
There's discussion regarding this behaviour here, but it seems there's no way to change it without breaking many important Less design patterns.
-
Btw., another related example:
.mixin() {
    @width: 10px;
}

.mixin() {
    @width: 20px;
}

.selector {
   .mixin();
    width: @width;
}

In this case the result is 20px because both mixins are expanded simultaneously and the last @width definition wins.


text:
Q: Algorithm for data alignment of float arrays in Java I have two float arrays representing y values in a line chart. Now I want to align these two charts. Are there any existing algorithms for alignment of the two arrays?
A very simple example
a:
2.5 1.3 1.6 4.2 3.6

b:
3.3 1.4 2.5 1.3 1.6

Now after alignment it should be:
        2.5 1.3 1.6 4.2 3.6
3.3 1.4 2.5 1.3 1.6

In reality it is much more complex with each array having a size of about 30 000 and floats like -6.94709206

A: In principle, that's easy:
for (an=0;an<a.length;++an)
{
  for (bn=0;bn<b.length;++bn)
  {
    if (a[an]==b[bn])
    {
      boolean run=true;
      for (offset=1;offset<a.length-an && offset<b.length-bn;++offset)
      {
        if (a[an+offset]!=b[bn+offset])
        {
          run=false;
          break;
        }
      }
      if (run)
        ... match at a[an], etc matching b[bn], etc
    }
  }
}
... no match ...

With floats, you'd have the issue that they might not really have to be exactly equal to be considered a match if there's any possibilty of inexactness in your data. Instead of a[an]==b[bn] you might want to say abs(a[an]-b[bn])<errorMargin or some such.
Disclaimer: Code is off the top of my head and untested. No warranties expressed or implied. Your mileage may vary. Void where prohibited. If rash develops, consult your physician.

A: This is basically normal pattern matching, you should be able to use most simple algorithms suitable for character matching as well.
Worst case for simple search would typically be n*m (assuming that n and m are the length of your float sequences), maybe you can reduce the runtime using an algorithm similar to Boyer-Moore towards being linear if one of the sequences remain the same.

A: Assuming, that both arrays match at a certain part.

*

*Use binary search to find the position of the first element of a inside b

*If there doesn't exist such a position, find position of first element of b inside a

*If theres still no match, put a behind b, if first a > last b -- b behind a otherwise


text:
Q: Swift - Directory not found for option So I'm getting this warning "ld: warning: directory not found for option '-F/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.0.sdk/Developer/Library/Frameworks'"
Now I've gone to my project build settings and checked the Framework and Library search paths and they are both empty. The only way I was able to get rid of it is if I deleted "View Controller based status bar" but I need it to be gone so I have to leave it in.
Is there another way to get rid of this message?


text:
Q: What is the version of OData protocol used in Azure Mobile Services I am unable to find any information on the supported version from MSDN.

A: Pretty sure that it is v3.
This page https://azure.microsoft.com/en-gb/documentation/articles/mobile-services-html-how-to-use-client-library/ links to the v3 spec here:

For more information on OData system query options, see the OData system query options reference.

Just in case that link was out of date and they have now upgraded, I checked the documentation and it has things that aren't in v4.

A: I got a confirmed answer from Microsoft yesterday.
Answer on MSDN Azure Forum

It's mostly v3.  You can find details on the OData query specification
here:
http://www.odata.org/documentation/odata-version-3-0/url-conventions/#url5.1
Adrian Hall - Microsoft (MSFT)

Hope this helps!


text:
Q: Remove top 2 elements along with namespace using XSLT I have an input XML as shown below
<ns9:Messages xmlns:ns9="http://sap.com/xi/XI/SplitAndMerge">
    <ns9:Message1>
        <ZCOD_SERVICE_CONFIRMATION02>
            <IDOC BEGIN="1">
                <EDI_DC40 SEGMENT="1">
                    <DIRECT>2</DIRECT>
                    <MESTYP>COD_SERVICE_CONFIRMATION</MESTYP>
                </EDI_DC40>
                <E101COD_S_SRV_CONF SEGMENT="1">
                    <REFOBJKEY>0000122425</REFOBJKEY>
                    <REFDOCTYPE>L2</REFDOCTYPE>
                </E101COD_S_SRV_CONF>
            </IDOC>
        </ZCOD_SERVICE_CONFIRMATION02>
    </ns9:Message1>
</ns9:Messages>

I need the output to be as below, essentially removing the top 2 elements and the namespace. I am able to do it by applying 2 XSLT one after another, but how can I do it using one XSLT.
Please note I can not use template match on the 3rd level node (ZCOD_SERVICE_CONFIRMATION02) as this name can be anything in runtime.
<?xml version="1.0"?>
 <ZCOD_SERVICE_CONFIRMATION02>
   <IDOC BEGIN="1">
     <EDI_DC40 SEGMENT="1">
        <DIRECT>2</DIRECT>
        <MESTYP>COD_SERVICE_CONFIRMATION</MESTYP>
     </EDI_DC40>
     <E101COD_S_SRV_CONF SEGMENT="1">
        <REFOBJKEY>0000122425</REFOBJKEY>
        <REFDOCTYPE>L2</REFDOCTYPE>
    </E101COD_S_SRV_CONF>
 </IDOC>
</ZCOD_SERVICE_CONFIRMATION02>

Best regards, Abinash

A: Assuming that the name and namespace of your 2nd level node is fixed (ns9:Message1), you could apply the following XSLT:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns9="http://sap.com" version="2.0">
  <xsl:output exclude-result-prefixes="ns9" indent="yes"/>
  <xsl:template match="/">
    <xsl:copy-of copy-namespaces="no" select="//*[parent::ns9:Message1]"/>
  </xsl:template>
</xsl:stylesheet>


text:
Q: set up mailserver for multiple domains guide for beginner I am not Linux pro, and after days of trying with tutorials how to set up postfix or other e-mail server I am try to find solution here.
In your office we have HP Proliant server with Ubuntu server 12.10. I installed configured, the mysql, apache2, php5, vnc, ssh, to provide webhosting for our clients (we do not provide DNS service). I tested it on multiple domains and subdomains everything is fine.
Now I want to set up email server for our domain and for any other domain pointing to our ip adress. So if we create website for you client, we provide him and domain example.com with webhosting and also we want to provide him a email addresses like something@example.com.
I red some tutorials with postfix + mysql for vitual users but lot of config files are in other location or main file is including others. So I cant find lot of things in included files and main file that tutorials is described. (They seems to be outdated)
Can somebody provide me step by step instructions or ebook how to set up mailserver? From apt-get install to fetch messages with email client.
in short:

*

*not virtualized

*we do not provide dns service (We are using A record on domains)

*test domain is from http://dot.tk  (soft-tech-srv.tk) using Dot.TK Free DNS service

*System is Ubuntu server 12.10 amd64, with Xfcedesktop and SSH + VNC access

*MySQL, Apache2, PHP5, FTP installed and configured

*full email service is needed.
Thanks.

A: The tutorial on www.howtoforge.com works perfectly to install postfix with courier and mysql for your situation using virtual users (so you don't need to open a Linux account for every mail user).
The config files used are on the default places if you install with apt-get. It is long  but basically it installs everything using apt-get, build the mysql queries to manage virtual users and mails (6 simple queries if remember well) and configure postfix main and master config files. You also install squirrelmail as webmail software.


text:
Q: Not Recursively enumerable sets Can someone tell me how to show that $A = \{ x : {\phi}_{x}^{1}(x) \uparrow \}$ is a not recursively enumerable set?
I am really struggling.
Thank you!

A: The Halting Problem is represented by the set $\overline{A} = \{ x : {\phi}_{x}(x) \downarrow \}$. This set is known to be r.e. but not recursive. If its complement $A$ were r.e., then the Halting Problem would be recursive (a set is recursive iff both it and its complement are r.e.)


text:
Q: How do I send a variable from a JavaScript function to a text box?
Possible Duplicate:
Set the value of a input field with javascript

Okay so I am trying to get the result of my function to go back into the input box (This is part of a calculator). An example is: I enter 1 into the calculator it then does 1+2+3+4+5+6+7+8+9+10 and outputs 55 into an alert message box via the function below. I am trying to get the result to be shown back inside the box instead of an alert box.
Below I have provided the code for:
    The "L" function, The "input" Box, and the Button onClick that controls the function.
I have been at this for about a week trying to figure it out. If you need more code from the calculator I can provide it.
function Loop(input)
{
     var num = parseInt(input) + 10;
     var i=0;
     var sum=0;

    while(i < num)
        {
            sum=sum+i;
            i++;
        }
    alert(sum);

}

<input type="button" value="   L    " name="L" onClick="Loop(this.form.display.value)">

<form><input name="display"  id="input" size=25><form>

Here is the rest of the code seeing as the two answers I got below did not work (Thanks for trying to hep though!)

<title>Assignment 2</title>

Calculator

<form  name="MyName" id="form1" style="font-weight:bold" size="20">

</form>

<form>

<input name="display"  id="input" size=25>

<input type="button" value="    7    " onClick="addChar(this.form.display, '7')">
<input type="button" value="    8    " onClick="addChar(this.form.display, '8')">
<input type="button" value="    9    " onClick="addChar(this.form.display, '9')">
<input type="button" value="    /    " onClick="addChar(this.form.display, '/')">

<input type="button" value="    4    " onClick="addChar(this.form.display, '4')">
<input type="button" value="    5    " onClick="addChar(this.form.display, '5')">
<input type="button" value="    6    " onClick="addChar(this.form.display, '6')">
<input type="button" value="    *    " onClick="addChar(this.form.display, '*')">

<input type="button" value="    1    " onClick="addChar(this.form.display, '1')">
<input type="button" value="    2    " onClick="addChar(this.form.display, '2')">
<input type="button" value="    3    " onClick="addChar(this.form.display, '3')">
<input type="button" value="    -    " onClick="addChar(this.form.display, '-')">

<input type="button" value="   0     " onClick="addChar(this.form.display, '0')">
<input type="button" value="    N    " onClick="changeSign(this.form.display)">
<input type="button" value="    +    " onClick="addChar(this.form.display, '+')">
<input type="button" value="   C   " onClick="this.form.display.value = 0 ">

<input type="button" value="   L    " name="L" onClick="Loop(this.form.display.value)"
                                               title="If the L button is pressed, the digit present in the results box will be looped through and added up to the 'digit plus 10'.For example: After the calculator has been reset. The user can press the 1 button, then the L button 55 should be displayed in the calculator 1 + 10 = 11, therefore start with 1 and loop until less than 11 adding all of the numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55">
<input type="button" value="   =    " name="enter" onClick="compute(this.form)">

A: Put this in line in your JS function instead of your alert
document.getElementById("input").value=sum;

A: I am assuming you input text field is properly written with type="text".
You can assign an id to the element and then set its value using javascript.
Get the object using document.getElementbyId("<Id>")
and then set the value document.getElementbyId("<Id>").value=<value>

A: Try
document.forms[0].display.value=sum;

A: You just need to make 3 changes. Then you can use the same function on any text-input, just like you can now.
First you want to pass the element itself to the function
function Loop(input)
{

becomes
function Loop(inputElement)
{
  var input = inputElement.value;

Next, change your alert output statement into this:
inputElement.value = sum;

Finally, change your html (remove the '.value')
onClick="Loop(this.form.display)"

A: You are not retreving the input value correctly.
You can do it like this:
<input name="display" id="input1" size="25">
<form>
    <input type="button" value="   L    " name="L" onClick="Loop()">
<form>

I also replaced the while with a for, as in this case it is easier to read in my opinion.

A: <input type="button" value="   L    " name="L" onClick="Loop(this.form.display.value)">

this here reffers to <input> and it doesn't have form, your document has a form, so:
document.forms[0].display.value will give you what you need;

For your update:
http://jsfiddle.net/jNqEv/3/
function Loop(input)
{
     var num = parseInt(input) + 10;
     var i=0;
     var sum=0;

    while(i < num)
        {
            sum=sum+i;
            i++;
        }
    // NOTE: it's not a good idea to give an item `input` ID;
    document.getElementById("input").value=sum; // instead of document.getElementbyId("input").value=sum;
    // what's this for?
    // document.form[0].display.value=sum;
}


text:
Q: Play Video in Background using Avplayer In my iPhone application I want to keep play video when application enter in background mode.
I am using AVPlayer and not finding any way to play video in background. I will be very grateful if any one can help me in this.
Thanks

A: With surprise I can say that this can be achieved and I just did it.
This method supports all the possibilities:

*

*Screen locked by the user;

*Home button pressed;

*Switch to other application.

As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.
First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.
Then put in your AppDelegate.m into - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
these methods
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

and #import <AVFoundation/AVFoundation.h>
Then in your view controller that controls AVPlayer
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

and
- (void)viewWillDisappear:(BOOL)animated
{
    [mPlayer pause];
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

then respond to the
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            if([mPlayer rate] == 0){
                [mPlayer play];
            } else {
                [mPlayer pause];
            }
            break;
        case UIEventSubtypeRemoteControlPlay:
            [mPlayer play];
            break;
        case UIEventSubtypeRemoteControlPause:
            [mPlayer pause];
            break;
        default:
            break;
    }
}

Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).
When you control the reproduction of the video (I have play: and pause: methods) set
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

and
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];

and the corresponding method to be invoked that will launch a timer and resume the reproduction.
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}

A: Try this code in your applicationDidEnterBackground:
UIApplication *app = [UIApplication sharedApplication];
bgTask = 0;

backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(backgroundTask) userInfo:nil repeats:YES];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];

i found it somewhere on the stack
works for me
Also check out this tutorial which covers background modes including background audio.. http://www.raywenderlich.com/29948/backgrounding-for-ios

A: You can do this background task when application is in background :
1> audio
2> location
3> voip
4> newsstand-content
5> external-accessory
6> bluetooth-central
7> bluetooth-peripheral
see this link,
http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
http://www.rideitdown.com/2012/10/how-to-listen-youtube-videos-in.html

also this may help you:
AVPlayer play video in background

A: The above answers pause the video for a second when the app enters background, but by using the method mentioned below it keeps the video playing while app goes to background without any glitch.
If the AVPlayer's current item is displaying video on the device's display, playback of the AVPlayer is automatically paused when the app is sent to the background. There are two ways to prevent this pause:

*

*Disable the video tracks in the player item (file-based content only).

*Remove the AVPlayerLayer from its associated AVPlayer (set the AVPlayerLayer player property to nil).

REFERENCE
Playing media while in the background using AV Foundation on iOS

A: You can achive your requirement by using below sets of below code.
Swift: 4.2
Just, Create subclass of UIViewController
import UIKit
import AVFoundation

class VideoPlayer:UIViewController{
    var avPlayer: AVPlayer!
    var avPlayerLayer: AVPlayerLayer!
    var paused: Bool = false

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        view.backgroundColor = .clear
        avPlayer?.play()
        paused = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let theURL = Bundle.main.url(forResource:"VIDEO_NAME", withExtension: "VIDEO_TYPE") //VIDEO_TYPE -> MP4

        avPlayer = AVPlayer(url: theURL!)
        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        avPlayer.volume = 0
        avPlayer.actionAtItemEnd = .none

        avPlayerLayer.frame = view.layer.bounds
        view.backgroundColor = .clear
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        addPlayerNotifications()
    }

    deinit {
        removePlayerNotifations()
    }

    func addPlayerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(playerItemDidReachEnd(notification:)),
                                               name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                               object: avPlayer.currentItem)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }

    func removePlayerNotifations() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIApplication.didEnterBackgroundNotification, object: nil)
    }

    @objc func playerItemDidReachEnd(notification: Notification) {
        let p: AVPlayerItem = notification.object as! AVPlayerItem
        p.seek(to: CMTime.zero)
    }

    //App enter in forground.
    @objc func applicationWillEnterForeground(_ notification: Notification) {
        paused = false
        avPlayer?.play()
    }

    //App enter in forground.
    @objc func applicationDidEnterBackground(_ notification: Notification) {
        paused = true
        avPlayer?.pause()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        avPlayer.pause()
        paused = true
    }
}

Now, Almoast done. Just create UIViewcontroller class by using sub-class as below.
class Classname: VideoPlayer{
   override func viewDidLoad() {
        super.viewDidLoad()
    }
}

A: Set AVAudioSession category to .playback mode in viewDidLoad
let audioSession = AVAudioSession.sharedInstance()
do {
     try audioSession.setCategory(.playback, mode: .moviePlayback, options: [])
} catch {
     print("Failed to set audio session category.")
}

Add NotificationObservers
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

//App enter in forground.
@objc func applicationWillEnterForeground(_ notification: Notification) {
    // Reconnect the AVPlayer to the presentation when returning to the foreground

    // If presenting video with AVPlayerViewController
    playerViewController.player = player

    // If presenting video with AVPlayerLayer
    playerLayer.player = player
}

//App enter in foreground.
@objc func applicationDidEnterBackground(_ notification: Notification) {
    // Disconnect the AVPlayer from the presentation when entering background

    // If presenting video with AVPlayerViewController
    playerViewController.player = nil

    // If presenting video with AVPlayerLayer
    playerLayer.player = nil
}

References
Playing Audio from a Video Asset in the Background,
AVAudioSession


text:
Q: Swift filter nested array of objects I have an array of Business objects. Each Business object contains an array of key-value pairs, one element of which can be a nested array of ContentBlocks objects.
var masterArray = [
        Business(busName: "Dave's Cafe", busId: 1, website: "http://www.davescafe.com", latLong: (45.541, -45.609),
            actions: [["title": "About Us", "contentId": "123", "actionType": "content"],
                ["title": "Website", "url": "http://www.davescafe.com", "actionType": "web"]],
            contentBlocks:[
                ContentBlock(busName: "Dave's Cafe", busId: 1, contentId: "123", title: "Testola!", body: "Hello there!")
            ]),
        Business(busName:...
]

I can filter the array to return a specific Businesses matching a unique busId by using something like this:
let rtnArray = masterArray.filter{$0.busId == id}
    if rtnArray.count == 1{
        return rtnArray[0]
    } else {
        return // feedback that no matches were found
    }

Additionally, I'd like to return a specific contentBlock by filtering on the unique contentId (if necessary I can also pass the busId of the Business 'owner'). I'm really struggling to move forward so any pointers in the right direction would be great.

A: Here's a solution to what I think you're asking:
 var contentBlocks = masterArray
                         .flatMap{$0.contentBlocks}
                         .flatMap{$0}
                         .filter{$0.contentId == "123"}

Outputs a [ContentBlock] containing all ContentBlock objects that match the filter from within all Business objects.

*

*The first flatMap makes the list of Businesses into an [ContentBlock?]

*The flatMap flattens the [ContentBlock?] into a [ContentBlock]

*The [ContentBlock] is filtered

A: When you are dealing with model and want to search the nested custom object of class.
Here is class example.
public final class Model1  {
// MARK: Properties

public var firstname: String?
public var lastname: String?
public var email: String?
public var availabilities: [Availability]?
public var username: String?
}

public final class Availability {
var date: String
var day : String

init(date: String, day: String) {
    self.date = date
    self.day = day

    }
}
public final class AvailData {
var am: String?
var pm: String?

init(am: String?,pm: String?) {
    self.am = am
    self.pm = pm
   }
}

let make an array of Model1.
var arrData = [Model1]()

In my case, I want to search in availabilities array. So I put below logic and it work perfectly.
 let searchData = arrData.filter({ singleObj -> Bool in
     let result = singleObj.availabilities?.filter({ $0.date == "2019/09/17" })
     return result?.count > 0 ? true : false
 })

This swift code will return only those records which match 2019/09/17

A: Try this:
// The busId and contentId you want to find
let busId = 1
let contentId = "123"

let contentBlocks = masterArray.flatMap {
    $0.contentBlocks.filter { $0.busId == busId && $0.contentId == contentId }
}


text:
Q: QML Контейнер с автоматической компоновкой элементов по ширине/высоте Вопрос:
Есть Column Row и Grid - три основных контейнера в qt. Они компонуют своё содержимое внутри себя в столбец, строку и таблицу соответственно.
Задача: вывести в контейнере 15-20 небольших однотипных элементов, но так, чтобы они не выходили за пределы контейнера при изменении его размера. т.е. если контейнер сужается по ширине, то в нём появляется больше строк и содержимое вытягивается в колонку, а если сужается по высоте, то наоборот - содержимое вытягивается в строчку.
По сути, код я реализовал. Всё на qml, всё работает. Но разве нету в qml подобного контейнера в стандарте? Я искал достаточно долго, но найти ничего не смог.
Может кто сталкивался с подобной задачей, поделитесь опытом.


text: Q: VSCode/Snowflake: How to connect to Snowflake DB via proxy? This is an extension to this issue. I'm trying to connect to a snowflake database using VSCode, it seems like there are no options to connect via a proxy? Where can I input my proxy details?


text:
Q: Why can't I delete this directory? What is going on here?
dave@dave-desktop:/mnt/w/Source/Sign/dist$ ls -la
total 0
drwxrwxrwx 1 dave dave 512 Feb 27 08:55 .
drwxrwxrwx 1 dave dave 512 Feb 27 09:09 ..
drwxrwxrwx 1 dave dave 512 Feb 27 09:09 signage
dave@dave-desktop:/mnt/w/Source/Sign/dist$ rmdir signage
rmdir: failed to remove 'signage': Permission denied
dave@dave-desktop:/mnt/w/Source/Sign/dist$ rm -rf signage
rm: cannot remove 'signage': Permission denied
dave@dave-desktop:/mnt/w/Source/Sign/dist$ whoami
dave

This is on "Ubuntu" running on windows 10 WSL.

A: Permissions don't work as expected in mounted Windows directories in WSL.
See this example:
root@x250:/mnt/c/Temp# touch foo
root@x250:/mnt/c/Temp# ls -l foo
-rwxrwxrwx 1 ibm ibm 0 Feb 27 15:25 foo
root@x250:/mnt/c/Temp# chmod -v 644 foo
mode of 'foo' changed from 0777 (rwxrwxrwx) to 0644 (rw-r--r--)
root@x250:/mnt/c/Temp# ls -l foo
-rwxrwxrwx 1 ibm ibm 0 Feb 27 15:25 foo

Yuck!

A: I can't even delete this directory from MS-Windows.
I found it with Windows process explorer.
It was locked. lsof shows nothing, but I found it with windows process explorer. I had a cmd.exe open in that directory.

A: If the account "dave", which was used to create the directory, has root privileges, try sudo rm -r signage


text:
Q: request.query does not print the query in Fastify (querystring) I searched for ages, but it just wouldn't print the query, I've no idea what I should do. I'm also kind of new to Fastify. Also I'm sending the request to 127.0.0.1/?greeting=something.
const opts = {
  schema: {
    querystring: {
      type: 'object',
      required: ['greeting'],
      properties: {
        greeting: {type: 'string'},
      },
    },

    response: {
      200: {
        type: 'object',
        properties: {
          status: {type: 'object'}, // i've abosulutely no idea what the type should be
        },
      },
    },
  },

  handler: async (request, reply) => {
    reply.send({
      status: request.query,
    })
  }
}

Can someone please help me in resolving this ?

A: You don't see the request.query output because of the response's schema.
The response schema filters out all the fields that are not defined, so the properties field lists the status key as object without any properties.
You should change it to:
status: { type: 'object', additionalProperties: true }

or adding the greetings property.
You can read about it here: https://github.com/fastify/fast-json-stringify#additionalProperties


text:
Q: Redis index scan for not equals operator I'm trying to use Redis sorted set as my secondary index while the actual data is stored on AWS S3.
Let's say if I want to support a condition like Name!= 'uma' is there anyway to achieve that using the inbuilt pattern matching?
For example, Let's i have below as my sorted set key
ZADD mykey 0 uma:7000
ZADD mykey 0 umesh:7001
ZADD mykey 0 mahes:7002

Can I do something like ZSCAN mykey 0 match !uma?
I don't want to get all data in-memory and apply != in the application layer.
Thanks in advance

A: You could create a temporary set containing the members you don't want and then use ZDIFF:
> ZADD mykey 3 uma:7000
(integer) 1
> ZADD mykey 4 umesh:7001
(integer) 1
> ZADD mykey 5 mahes:7002
(integer) 1

Add some temp values:
> ZADD tempkey 0 uma:7000
(integer) 1

And get the difference:
> ZDIFF 2 mykey tempkey WITHSCORES
1) "umesh:7001"
2) "4"
3) "mahes:7002"
4) "5"

Oh. And be sure to clean up the temp set:
> UNLINK tempkey
(integer) 1

A: You can use Lua Script + ZSCAN to do the job. The following is a one-liner that achieves the goal.
redis-cli eval 'local res = redis.call("zscan", KEYS[1], ARGV[1]); local matches = {}; local kv = res[2]; for i=0,(#kv/2-1) do local k = kv[i * 2 + 1]; local v = kv[i * 2 + 2]; if k ~= ARGV[2] then matches[#matches + 1] = k; matches[#matches + 1] = v; end end res[2] = matches; return res' 1 mykey cursor-starting-from-0 uma

There's a similar question for SCAN. I tried to modify the one-liner in that answer, and made a comment. However, the return value for SCAN is quite different from ZSCAN, so I wrote a dedicated answer for it.


text:
Q: Easiest way to convert list to a comma separated string by a Specific Property? I have a list of Custom objects ,Actually those are entities I am storing in an IEnumerable collection. I want to convert the list  to a comma separated string, but  I want only one specific property,  How do I build a comma separated string with a specific property from a custom object list?
I know i can build a comma separated list by using a "Foreach / For (int i .... "
but I think there is a easy and a better way for this
So what would be that easy way?
This is my list
IEnumerable<BAL.Category> categories = chklCategories.CheckedItems.Cast<BAL.Category>();
            //Category object has a property called Name , I want the list from that property

A: This is very easy , Isn't it ?
string sCategories = string.Join(",", categories.Select(x => x.Name));

A: Just try with this.
By using this version of the string.Join<string> method, you can reduce copies of your collection before joining.
static string CombineList(IEnumerable categories)
{
  return string.Join<string>(",", categories.Select(x => x.Name));
}


text:
Q: Laravel - Property [name] does not exist on this collection instance I am trying to create a Collection and pass it to blade. My PHP code look like this
$collection1 = collect(['name' => 'Alex', 'id' => '1']);
$collection2 = collect(['name' => 'John', 'id' => '2']);
$collection3 = collect(['name' => 'Andy', 'id' => '3']);

$people_col = new Collection();

$people_col->push($collection1);
$people_col->push($collection2);
$people_col->push($collection3);

return view('test',[
    'people_col' => $people_col
]);

In my blade I loop through people_col to get properties of items:
 @foreach ($people_col as $people)

            {{ $people->name }}
            {{ $people->id }}

 @endforeach

However I got this error:

Property [name] does not exist on this collection instance

Any idea?
Thanks

A: You are creating a collection of collections where you should have created a collection of objects instead.
With your current implementation you should be able to get the values using array access method {{ $people['name'] }} or using get method on collection {{ $people->get('name') }}
If you created a collection of objects like below and return it instead of what you are doing now
$people_col = collect([
    (object) ['name' => 'Alex', 'id' => '1'],
    (object) ['name' => 'John', 'id' => '2'],
    (object) ['name' => 'Andy', 'id' => '3']
]);

return view('test', [
    'people_col' => $people_col
]);

Then in your view you should be able to access people object like you have done in your code.
@foreach ($people_col as $people)

        {{ $people->name }}
        {{ $people->id }}

@endforeach

A: Try to access to the property name this way: $people['name']
@foreach ($people_col as $people)

            {{ $people['name'] }}
            {{ $people['id'] }}

 @endforeach


text:
Q: Determine whether the set $\{ k \in \mathbb R^{1 \times n} : \rho(A-bk^T) < 1 \}$ is convex Suppose we have a controllable (stabilizable) pair $(A, b)$ (Definition can be found here and it is equivalent to $(b, Ab, A^2b, \dots, A^n b)$ having full rank), where $A \in \mathbb R^{n \times n}$ and $b \in \mathbb R^{n}$. I am interested in determining whether the following set
$$\{ k \in \mathbb R^{n} : \rho(A-b k^T) < 1 \}$$
where $\rho(\cdot)$ denotes the spectral radius, is convex. In control theory, this set corresponds to stabilizing feedback controllers and have many real applications.
In general, there is no reason to believe the set of stabilizing feedback controllers to be convex. As pointed in Appendix B of this paper, if $A \in \mathbb R^{3 \times 3}$ and $B \in \mathbb R^{3 \times 3}$ we can easily construct an example to show the corresponding stable feedback controller set is not convex.
But here I am considering a modest case, where $b$ is restricted to be $\mathbb R^{n}$. The reason for me to believe the set is probably to be convex is simulation result. Indeed, in all my randomly generated $(A, b)$, the set of $k$ forms a convex set for $n=2, 3, 4$ (I grid the space of $\mathbb R^{n}$ and check the eigenvalues for each point). For higher dimensions, it takes much longer to simulate. So either the set is indeed convex or I am not sampling the space fine enough.

As commented by @loup blanc, the question was initially formulated for the specific case $n=2$. Before it drew too much attention, I did more simulations to see the shape of $k$ and then I changed the formulation since I am not sure it is OK to start a new question. If this brought inconvenience, I sincerely apologize.

A: I'm not aware of any specific convexity results for the single-input $b \in \mathbb{R}^n$ case you mentioned, but for the general case of multiple inputs and $B \in \mathbb{R}^{n \times m}$, there exists a very useful convexifying change of variables that is often used for controller design. This means that the nonconvexity of the set of stabilising $K$ is not usually an issue and state feedback controllers can be designed using convex optimisation.
A discrete time linear system is stabilised by a state feedback $K$ if and only if $A + BK$ admits a quadratic Lyapunov function, so that for some symmetric matrix $P$ we have
$$
x^T P x > 0, \qquad x^T P x - x^T (A+BK)^T P (A+BK) x < 0
$$
for all $x \neq 0$. Factorising the LHS of the second inequality gives
$$
x^T P x > 0, \qquad x^T \left( P - (A+BK)^T P (A+BK) \right) x < 0
$$
for all $x \neq 0$, which is equivalent to the matrix inequalities:
$$
P \succ 0, \qquad - P + (A+BK)^T P (A+BK) \succ 0
$$
The second inequality is jointly nonconvex in $P$ and $K$, but we can make it convex by pre-and post- multiplying by $Q = P^{-1}$ (noting that $Q$ is positive definite iff $P$ is)
$$
Q \succ 0, \qquad - Q + Q (A+BK)^T Q^{-1} (A+BK) Q \succ 0
$$
then applying the Schur Complement Lemma to give
$$
\left[ \begin{array}{cc} -Q & Q (A+BK)^T \\ (A+BK)Q & -Q\end{array} \right] \succ 0
$$
and then considering a change of variables $Y = K Q$ to yield
$$
\left[ \begin{array}{cc} -Q & Q A^T+Y^T B^T \\ AQ+BY & -Q\end{array} \right] \succ 0
$$
which is a Linear Matrix Inequality (LMI) in the variables $Q$ and $Y$ and therefore define a convex set (a spectrahedron). This parameterises the whole set of stabilising state feedback controllers, in the sense that for any $Q$ and $Y$ satisfying the LMI, $K = Y Q ^{-1}$ gives a stabilising state feedback and if the LMI is infeasible then no such $K$ exists.
I suggest taking a look at the book by Boyd and co-workers on LMIs in control, which is available online at https://web.stanford.edu/~boyd/lmibook/. Chapter 7 in particular contains many results about state feedback synthesis in continuous-time for various system types (LTI, LDI, LFT), and some discrete-time results are available in Chapter 9 (for the more general case of stochastic systems).