text:
Q: Change background colour dynamically I am using RangeSeekBar to set some values for 3 conditions (i.e. Green=OK,Amber=Warning, Red=evacuate)... I am using xml drawable to set the backgroung like this
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#27F70C"
        android:centerColor="#FFBF00"
        android:endColor="#FC0505"
        android:angle="0" />

    <corners android:radius="0px" />

    <stroke
        android:width="2dp"
        android:color="#70555555" />

    <stroke
            android:width="0dp"
            android:color="#70555555" />
</shape>

which results like this

Now I want to change the background colour according to the seekbar values so that If I change the range it should change the background colour something like this

I know I can change the gradient programmatically but how to narrow down start color and increase end colour ?
Anyone has a solution for this ?
Thanks

A: Try creating three Views underneath the RangeSeekBar, and updating the widths of each as the sliders are moved.
Very roughly, this might look like:
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content">
     <View
         android:id="@+id/green"
         android:layout_width="100dp"
         android:layout_height="match_parent"
         android:background="#00FF00"/>
     <View
         android:id="@+id/orange"
         android:layout_toRightOf="@id/green"
         android:layout_width="100dp"
         android:layout_height="match_parent"
         android:background="#FFFF00"/>
     <View
         android:id="@+id/red"
         android:layout_toRightOf="@id/orange"
         android:layout_width="100dp"
         android:layout_height="match_parent"
         android:background="#FF0000"/>
     <RangeSeekBar android:layout_width="300dp" android:layout_height="wrap_content">
</RelativeLayout>

In this example, you would update the widths of the three colour views so that they add up to 300dp, as the sliders are moved.
You can either use solid colours for the backgrounds of the three views, which would look like your second image, or create three gradients (green to green-yellow, yellow-orange, orange-red).

A: The LinearGradient has an optional parameter called positions - these positions tell how long the different sections of colors will be.
@miroslavign posted a function here  which seems to set gradient background for a view by code (not XML) -  I haven't tried it, but it looks promising. Simply change it to your colors and set the gradient positions according to the Seekbar.
Copy pasted here for people who don't like following links:
private void FillCustomGradient(View v) {
    final View view = v;
    Drawable[] layers = new Drawable[1];

    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(
                    0,
                    0,
                    0,
                    view.getHeight(),
                    new int[] {
                             getResources().getColor(R.color.color1), // please input your color from resource for color-4
                             getResources().getColor(R.color.color2),
                             getResources().getColor(R.color.color3),
                             getResources().getColor(R.color.color4)},
                    new float[] { 0, 0.49f, 0.50f, 1 },  // positions
                    Shader.TileMode.CLAMP);
            return lg;
        }
    };
    PaintDrawable p = new PaintDrawable();
    p.setShape(new RectShape());
    p.setShaderFactory(sf);
    p.setCornerRadii(new float[] { 5, 5, 5, 5, 0, 0, 0, 0 });
    layers[0] = (Drawable) p;

    LayerDrawable composite = new LayerDrawable(layers);
    view.setBackgroundDrawable(composite);
}

A: This is how I did it, in case anyone looking for a complete solution...
Thanks to @Dave Morrissey for the help :)
XML code will be
<RelativeLayout
    android:id="@+id/layout4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center">

    <LinearLayout
        android:id="@+id/colorsLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <View
            android:id="@+id/bgGreen"
            android:layout_width="100dp"
            android:layout_height="25dp"
            android:background="#27F70C"/>
        <View
            android:id="@+id/bgAmber"
            android:layout_width="100dp"
            android:layout_height="25dp"
            android:background="#FFBF00"/>
        <View
            android:id="@+id/bgRed"
            android:layout_width="100dp"
            android:layout_height="25dp"
            android:background="#FC0505"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/seekBarLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </LinearLayout>

</RelativeLayout>

Java code will be like
LinearLayout ll = (LinearLayout)findViewById(R.id.colorsLayout);
View viewGreen = (View)findViewById(R.id.bgGreen);
View viewAmber = (View)findViewById(R.id.bgAmber);
View viewRed = (View)findViewById(R.id.bgRed);

int sbMaxVal = 4999;
//Create RangeSeekBar as Integer range between 0 and sbMaxVal
seekBar = new RangeSeekBar(0, sbMaxVal, this);
seekBar.setNotifyWhileDragging(true);

//Add RangeSeekBar to Pre-defined layout
ViewGroup layout = (ViewGroup) findViewById(R.id.seekBarLayout);
layout.addView(seekBar);

//Set the onRangeChangeListener for the seekBar
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
    @Override
    public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {

        int width = ll.getWidth();
        int minVal = (int) Math.floor((Integer.parseInt(amberValue)*width)/sbMaxVal);
        int maxVal = (int) Math.floor((Integer.parseInt(redValue)*width)/sbMaxVal);

        int wg = minVal;
        int wy = maxVal-minVal;
        int wr = ll.getWidth()-wg-wy;

        //Change the length of background views green,amber,red
        LinearLayout.LayoutParams paramsGreen = (LinearLayout.LayoutParams)
        viewGreen.getLayoutParams();
        paramsGreen.width = wg;
        viewGreen.setLayoutParams(paramsGreen);

        LinearLayout.LayoutParams paramsAmber = (LinearLayout.LayoutParams)
        viewAmber.getLayoutParams();
        paramsAmber.width = wy;
        viewAmber.setLayoutParams(paramsAmber);

        LinearLayout.LayoutParams paramsRed = (LinearLayout.LayoutParams)
        viewRed.getLayoutParams();
        paramsRed.width = wr ;
        viewRed.setLayoutParams(paramsRed);
    }
});


text:
Q: iPad application strange behavior I am working on a simple video player base application in which I have eight buttons, on click of that buttons video plays and when video playing complete the button image changed. if user close the video then button image will not change.
This small app is working perfect with me and when I send it to client it behave strange, like some buttons works and some of them can't.
How do I resolve it!

A: I had the same issue with iPad. All buttons worked fine on simulator, but on the iPad they worked randomly.
I figured out that the gesture recognizer is very precise on TouchUpInside event. If you tap and move your finger even a millimeter the touch event is being canceled, as it thinks it's a swipe.
I solved it with a little hack, by removing addTarget:action:forControlEvents: and writing my own method with gestureRecognizer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add time picker in HTML5 which have HH:MM format with selected Dates? I searched everywhere but I'm not satisfied by the answer. At last I'm posting here to get the answer.
I have two datepicker and time picker textbox which displays 12:00 format with AM & PM.
Here I want to calculate the TOTAL time which includes number of days and given time.
I want to add those time and display it in another text box. I need it in HH:MM format. I don't want seconds as my time picker textbox shows only HH:MM which is enough for me.
I tried many methods to add but i'm not getting the exact time value.
Below is my HTML code
<input type="date" id="opening_date">
<input type="date" id="closing_date">
<input type="time" class="time" id="garage_out_time">
<input type="time" class="time" id="garage_in_time">
<input type="text" id="total_hours">

Below is my script code
$(document).ready(function () {
function ConvertDateFormat(d, t) {
    var dt = d.val().split('/');
    return dt[0] + '/' + dt[1] + '/' + dt[2] + ' ' + t.val();
}
$(".time").change(function () {
    var start = new Date(ConvertDateFormat($('#opening_date'), $('#garage_out_time')));
    var end = new Date(ConvertDateFormat($('#closing_date'), $('#garage_in_time')));
    console.log(start, end);
    var diff = new Date(end - start);
    var days = Math.floor(diff / 1000 / 60 / 60 / 24);
    var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60);

    var total = (days * 24) + hours;

    var startTime = document.getElementById("garage_out_time").value;
    var endTime = document.getElementById("garage_in_time").value;
    var s = startTime.split(':');
    var e = endTime.split(':');
    var endtime = parseInt(e[1], 10);
    var starttime = parseInt(s[1], 10);
    var min = endtime + starttime;
    var minutes = min ;
    var minhours = Math.floor(minutes / 60);
    minutes = minutes % 60;

    total = total + minhours;
    if(minutes > 9){
    $("#total_hours").val(total+":"+ minutes);
    } else {
        $("#total_hours").val(total+":0"+ minutes);
    }
});
});

Above code is working for some extent BUT for example when I select 8:12 AM to 8:12 PM , the result I'm getting is 12:32 where answer should be 12:00.

A: I think you are over-complicating things somewhat. Your ConvertDateFormat() function already gives you what you need, so why are you parsing the time again? Try the code below (with thanks to this this answer)
var start = new Date(ConvertDateFormat($('#opening_date'), $('#garage_out_time')));
var end = new Date(ConvertDateFormat($('#closing_date'), $('#garage_in_time')));
console.log(start, end);
var diff = new Date(end - start);
var mins = Math.floor( diff /    60000 %   60 );
var hours = Math.floor( diff /  3600000 %   24 );
var days = Math.floor( diff / 86400000        );
console.log('days='+days+' hrs='+hours+' mins='+mins);
var totalHours = (days * 24) + hours;
var minsStr = (mins < 10) ? '0' + mins : mins;
$('#total_hours').val(totalHours + ':' + minsStr);


text:
Q: Bootstrap row elements with variable height I'm currently developing a website using Twitter Bootstrap.
My case:
A single .row element containing several elements .col-XX-XX with variable height (product images with variable image ratio)
The number of columns in my design vary from viewport size to viewport-size, which disables me just seperate the elements by use of creating several .row wrappers.
Each element having variable height, due to the element's individual image. Large blank areas (marked with red) with no elements can appear if a large element is appearing as first in the actual row it is appearing.

My only solution yet is to set a predefined height of the elements in the list, to ensure that no "jumping" can happen when the next element (on a new row) is displayed.
I've also tried to use a javascript, finding the max value of the elements, and then set all elements to this height, however this is a bad solution hence large varity of image heights will also create large blank areas.
Does anyone have a nice solution to this problem?

A: With help from Joseph Casey, I found a solution.
CSS: flexbox
By using the styles explained in this link: http://osvaldas.info/flexbox-based-responsive-equal-height-blocks-with-javascript-fallback
I used the following styles:
CSS
.row{
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;

    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
}
.row .item{
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
}

Which achieved that the elements aligns nicely.
The styles is supported by the most newer browsers. I found a list of the browser support of flexbox here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
A little note: In Google Chrome 43, the first row of elements moves the last element down on the next row (last column on first row is empty), but on all following rows, all columns is filled nicely. I haven't found any solution to this yet.


text:
Q: SchemaSpy - Error message while generating the report I am using SchemaSpy (5.0.0) to generate a report of our Informix database.
While running it I get the following error during the last step of 'Gathering schema details':
java.sql.SQLException: The cursor has been previously released and is unavailable.
    at com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:408)
    at com.informix.jdbc.IfxSqli.addException(IfxSqli.java:3187)
    at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3467)
    at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java:2378)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2303)
    at com.informix.jdbc.IfxSqli.executeFetch(IfxSqli.java:2037)
    at com.informix.jdbc.IfxSqli.getaRow(IfxSqli.java:4077)
    at com.informix.jdbc.IfxResultSet.next(IfxResultSet.java:494)
    at com.informix.jdbc.IfxDatabaseMetaData.getImportedKeys(IfxDatabaseMetaData.java:5524)
    at net.sourceforge.schemaspy.model.Table.connectForeignKeys(Table.java:106)
    at net.sourceforge.schemaspy.model.Database.connectTables(Database.java:984)
    at net.sourceforge.schemaspy.model.Database.<init>(Database.java:83)
    at net.sourceforge.schemaspy.SchemaAnalyzer.analyze(SchemaAnalyzer.java:211)
    at net.sourceforge.schemaspy.Main.main(Main.java:42)
Caused by: java.sql.SQLException
    at com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:408)
    at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3472)

I am using the Informix JDBC driver in version 4.1.0 (also tried 4.10.8.1). Strangely this driver also needs the BSON library.
Any idea what's the problem?

A: Agree 100% with Jonathan. This should be reported to IBM Technical Support. IBM releases  about 3 or  Fixpacks a year, and I see no reason for Informix 12.10 user to be penalized. It would be great to open a service request. I love schemaSpy!
Eric

A: For future reference I could solve the problem by replacing the above driver 4.X with an older version. Seems that driver is buggy or SchemaSpy is not compatible with the newer 4.X drivers. The driver which worked was the latest 3.X driver (3.70.JC8 to be exact).

A: Looking at the stack the server is failing to do a select and returns an error to the client when it tries to retrieve the list of primary keys:
java.sql.SQLException: The cursor has been previously released and is unavailable.
    at com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:408)
    at com.informix.jdbc.IfxSqli.addException(IfxSqli.java:3187)
    at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3467)    <--- means error ;)
    at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java:2378)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2303)
    at com.informix.jdbc.IfxSqli.executeFetch(IfxSqli.java:2037)
    at com.informix.jdbc.IfxSqli.getaRow(IfxSqli.java:4077)
    at com.informix.jdbc.IfxResultSet.next(IfxResultSet.java:494)
    at com.informix.jdbc.IfxDatabaseMetaData.getImportedKeys(IfxDatabaseMetaData.java:5524)

I did a quick test with 4.10.JC8 in one of my servers against the stores_demo database and it completed without a glich:
d:\JJTMP>java -jar \jjtmp\schemaSpy_5.0.0.jar -t informix -db stores7 -s informix -u informix -p password -o \jjtmp -host 420ito:9088 -server ids1210 -dp \infx\jdbc410jc8x\lib\ifxjdbc.jar
Using database properties:
  [\jjtmp\schemaSpy_5.0.0.jar]/net/sourceforge/schemaspy/dbTypes/informix.properties
Gathering schema details....................................................................(4sec)
Writing/graphing summary..............(7sec)
Writing/diagramming details.................................................................(6sec)
Wrote relationship details of 65 tables/views to directory '\jjtmp' in 19 seconds.
View the results by opening \jjtmp\index.html

d:\JJTMP>

If you get a SQLI trace you should be able to see why that particular SQL is failing.
Add the SQLIDEBUG property to the connection string in the schemaSpy command line to generate one.
Something like this:
d:\JJTMP>java -jar \jjtmp\schemaSpy_5.0.0.jar -t informix -db stores7 -s informix -u informix -p password -o \jjtmp -host 420ito:9088 -server ids1210 -dp \infx\jdbc410jc8x1\lib\ifxjdbc.jar -connprops SQLIDEBUG\=trace
Using database properties:
  [\jjtmp\schemaSpy_5.0.0.jar]/net/sourceforge/schemaspy/dbTypes/informix.properties
Gathering schema details....................................................................(4sec)
Writing/graphing summary..............(7sec)
Writing/diagramming details.................................................................(6sec)
Wrote relationship details of 65 tables/views to directory '\jjtmp' in 18 seconds.
View the results by opening \jjtmp\index.html

d:\JJTMP>dir trace*
 Volume in drive D is Data750
 Volume Serial Number is F0B7-2E46

 Directory of d:\JJTMP

17/08/2017  11:10         2,008,706 trace1502964639886.0
               1 File(s)      2,008,706 bytes
               0 Dir(s)  284,868,997,120 bytes free

Then you can decode the trace file using the sqliprint/sqliprt CSDK tool (it should be on the engine bin directory)
d:\JJTMP>sqliprt -notimestamp trace1502964639886.0 > trace.txt

d:\JJTMP>

But as everyone said, it may be a good idea to open a ticked with tech support. It could be specific to your database/schema (wonder if it fails against other databases) but even so getImportedKeys() shouldn't fail with that error no whatever the application does.

A: I just answered this similar question here https://stackoverflow.com/a/55458418/8334122.  The copy of that answer is below.
I had to get some help tracking down this as it's a timing issue + bug in the driver.
The problem here is with some versions of the Informix JDBC driver. Quick fix is to upgrade to the latest 4.50.1 driver. It's out on maven.
<!-- https://mvnrepository.com/artifact/com.ibm.informix/jdbc -->
<dependency>
    <groupId>com.ibm.informix</groupId>
    <artifactId>jdbc</artifactId>
    <version>4.50.1</version>
</dependency>

In detail. The 4.10.X drivers introduced a statement cleaner thread that runs every 15 seconds and looks for resources that need to be closed as they have no more references and could be garbage collected. The problem, then compounds as a couple JDBC metdata calls incorrectly failed to close resources causing this cleaner thread to close resources in the middle of the work sometimes. Hence some people see it often, some never. You can work around it with 4.10.JC12 where we added a connection flag to disable the cleaner thread (IFMXCONNECTION_CLEANER_THREADS=0). Or the best option is to upgrade to the newest 4.50.1 driver which has this issue properly fixed


text:
Q: Regex for parsing a shell command like strings I am trying to parse strings that look like shell commands. The general structure of these command is the following:
command value -arg1name arg1val -arg2name arg2val ... -argMname argMval

Here is an example,
abc cmdh1521 -x 123 -y sadg -zzz 563sd

I am using the Python re module to parse, search and group strings so that I get an output like this,
(command, value, ((-arg1name, arg1val), (arg2name, arg2val), ... (argMname, argMval))

I tried the following set of commands, but my output is not what I want it to be.
import re
cmd = "abc cmdh1521 -x 123 -y sadg -zzz 563sd"
_parser = r"^([a-z]+)\s{1}(\S*)((\s+\-[a-z]+\s{1}\S+)*)"
out = re.search(_parser, cmd)
print out.groups()

Here is the output I get
('abc', 'cmdh1521', ' -x 123 -y sadg -zzz 563sd', ' -zzz 563sd')

What am I doing wrong?
I can easily implement a non-regex solution, but I would like to know if there is a regex that can give me the kind of parsing I want?

A: Then again split according to the space exists before -
>>> s = ('abc', 'cmdh1521', ' -x 123 -y sadg -zzz 563sd', ' -zzz 563sd')
>>> h = []
>>> for i in s:
    if '-' not in i:
        h.append(i)
    else:
        for j in re.split(r'\s+(?=-)', i):
            if j:
                h.append(j)

>>> h
['abc', 'cmdh1521', '-x 123', '-y sadg', '-zzz 563sd', '-zzz 563sd']
>>>

or
>>> cmd = "abc cmdh1521 -x 123 -y sadg -zzz 563sd"
>>> import re
>>> re.findall(r'^(\S+)\s+(\S+)|(-\S+\s+\S+)', cmd)
[('abc', 'cmdh1521', ''), ('', '', '-x 123'), ('', '', '-y sadg'), ('', '', '-zzz 563sd')]
>>> [j for i in z for j in i if j ]
['abc', 'cmdh1521', '-x 123', '-y sadg', '-zzz 563sd']
>>>

A: In this case you will have to use positive lookbehind regex as shown below:
(?<=-)(\w+) ([\w\d]+)

Description and example is at:
Demo


text:
Q: DateString and localization, $Language ignored I have a DateString calculated in English.
Now I would like to change the output according to localization. I have read that localization is possible for Menu, Messages and Cells. A simple $Language = "French" before calling DateString is ignored.
Since this should be a basic feature for localization, I am wondering if my keywords for Google and SX are just plain wrong? Or is this feature not present?

A: Ok, There seems to be some agreement, that the function is not natively implemented in MM. Thus, I will try to answer my question with a workaround. My answer is based on a java question over at SX
In[1]:= Needs["JLink`"]
        InstallJava[];
        LoadJavaClass["java.text.DateFormat"];
        LoadJavaClass["java.util.Date"];
        LoadJavaClass["java.util.Locale"];
In[2]:= date = JavaNew["java.util.Date"];

In[3]:= df = DateFormat`getDateInstance[DateFormat`LONG, Locale`GERMANY];
        df@format[date]

Out[3]= "19. März 2013"

In[4]:= df = DateFormat`getDateInstance[DateFormat`LONG, Locale`FRANCE];
        df@format[date]
Out[4]= "19 mars 2013"

In[5]:= df = DateFormat`getDateInstance[DateFormat`LONG, Locale`ITALY];
        df@format[date]
Out[5]= "19 marzo 2013"

Maybe someone can come up with a better solution. Since then, I stay with my opinion that this feature is basic and should be implemented in MM before any (ugly) tachometer or so onis added to the UI - At least I don't want a Labview like MM...


text:
Q: bs_embed_popover with shinydashboard I'm having problems using the popover from bsplus with shinydashboard since the text is not shown, and it is behind the title panel.
library(shiny)
library(bsplus)
library(htmltools)
library(shinydashboard)

# UI
ui <-
  dashboardPage(
    dashboardHeader(title = "Title"),
    dashboardSidebar(
      use_bs_popover(),
        selectInput(
          inputId = "letter",
          label = "Label with popover help",
          choices = c("a", "b", "c")
        ) %>%
        shinyInput_label_embed(
          shiny_iconlink() %>%
            bs_embed_popover(
              title = "Letter", content = "Choose a favorite", placement ="right"
            )
        )
    ),
    dashboardBody(
    )
)

# Server
server <- shinyServer(function(input, output) {
})

# Run the applicationenter image description here
shinyApp(ui = ui, server = server)

A: For some reason, the text is displayed in white (you can try to highlight the text content, it will reveal itself). So it's not hidden, and you can fix that using CSS:
.popover-title {color:black;}
.popover-content {color:black;}

The second problem is related to the fact that the popover is showing under the navbar, because of each element's z-index. The problem is that the popover is nested in the sidebar which has a z-index with a numeric value, so even though the popover has a z-index greater than the z-index of the header, it will remain under the header. To make it work, you just need to set the z-index of the sidebar to auto:
.main-sidebar {z-index:auto}

All in all, you could use the following lines to make your shiny app working as desired:
dashboardBody(tags$style(HTML('.popover-title {color:black;}
                               .popover-content {color:black;}
                               .main-sidebar {z-index:auto;}'))
)

A: I have tried the same with out shinydashboard,using fluidpage() and it's working perfectly okay.
I have tried the same with ShinyBS library using bsPopover and bsButton function.
It might solve your purpose.
Here is code.
library(shiny)
library(bsplus)
library(htmltools)
library(shinyBS)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    selectInput(
      inputId = "letter",
      label = "Label with popover help",
      choices = c("a", "b", "c")
    )%>%shinyInput_label_embed(
      shiny_iconlink() %>%
        bs_embed_popover(title = "Number", content = "Demo Description", placement ="left")
    ),
    use_bs_popover(),
    selectInput(
      inputId = "letter",
      label = h5("Label with popover help ",
                 tags$style(type = "text/css", "#q1 {float: right;}"),
                 bsButton("q1", label = "", icon = icon("question"), style = "info", size = "extra-small")),
      choices = c("a", "b", "c")),
    bsPopover(id = "q1", title = "Demo data",
              content = paste0("Demo Description "
              ),
              placement = "right",
              trigger = "focus",
              options = list(container = "body")
    )
      ),
    dashboardBody()
  )

  server <- shinyServer(function(input, output) {

  })

  shinyApp(ui = ui, server = server)

Output is:

Please check if it solves your purpose.


text:
Q: Redux reducers: map or not map on editing I´m trying to figure out if I shouyld map or not in my reducer.
Here´s the context.
I have a redux state composed by...
friends [{}, {}]
pets [{}, {}]
users [{}, {}]

3 of them are array of objects based on GET responses (local API)
Here´s an example of one object of the friends array.
{
  id: '982347646324',
  name: 'Peter',
  lastName: 'Doe',
  age: 40
}

So... Now let´s say that I want to edit this entry.
My current reducer case would be...
...
      case EDIT_FRIEND:
      return state.map(el => {
        if (el.id === action.payload.data.id) {
          return {
            ...el,
            name: action.payload.data.name,
            lastName: action.payload.data.lastName,
            age: action.payload.data.age
          }
        }
        return el
      });
...

      default:
      return state;

Since I´m new and in the learning process, I should ask:
Is this the right way to do it...?
It works, yes, but I want to learn and do it properly.
Should I do it in other way...?
Should I map or not...? Any help will be really helpful.
Thnanks a lot

A: There are a few ways to do it, the map method which you use is one such and it is perfectly fine to use it. The other solution is using spread syntax and updating the desired object like
...
  case EDIT_FRIEND: {
      const index = state.findIndex(obj => obj.id === action.payload.data.id);
      return [
         ...state.slice(0, index),
         {
            ...state[index],
            name: action.payload.data.name,
            lastName: action.payload.data.lastName,
            age: action.payload.data.age
          }
          ...state.slice(index + 1)
      ]
 }
 ...

 default:
   return state;

You can opt to go for any of the solution that you find comfortable from the above two. What you must keep in mind is that you are not directly mutating the store state.

A: Things you should not do in a reducer

*

*make it impure

*mutate the state

Since you are using map method, it will return a new array everytime and doesn't mutate your earlier array. So, it is totally fine to use map.


text:
Q: Domain names added in windows hosts file is not accessible from android emulator/device I am testing facebook app from android mobile/emulator. For this I added a domain like,
127.0.0.1       mysite.web

in the \etc\hosts file.
But when i enter this url, http://mysite.web:8080/fb_post_log.html in the webview, it is not loading and DDMS log says that,
"Reason : The URL could not be found."
How to access local domains from android webview or browser without using IP address. I cannot give IP address in facebook domain name fields.
Thanks in advance,
JRH


text:
Q: Fortran 90: How to correctly read an integer among other real I have created a Fortran 90 code to filter and convert the text output of another program in a csv form. The file contains a table with columns of various types (character, real, integer). There is a column that generally contains decimal values (probability values). BUΤ, in some rows, where the value should be decimal "1.000", the value is actually integer "1".
I use "F5.3" specifier to read this column and I have the same format statement for every row of the table. So, when the code finds "1", it reads ".001", because it does not find a decimal point.
What ways could I use to correctly (and generally) read integers among other decimals?
Could I specify "unformatted" input only for a number of "spaces"?

A: You could try using list-directed input: use a * instead of a format specifier.   This would be for the entire read, not selected items.   Or you could read the lines into a string test their contents to decide how to read them.   If the sub-string has a decimal point: read (string(M:N), '(F5.3)') value.   If it doesn't, use a different format, e.g., perhaps read as as F5.0.
P.S.  "unformatted" is reading binary data without conversion ... it is a direct copy of the data from the file to the data item.   "listed-directed" is the Fortran term for reading & converting data without using a format specification.

A: The data edit descriptor fw.d for floating point format specification is  for input normally used with zero d (it cannot be ommited). Nonzero d is used in the rare case when the floating point data is stored as scaled integers, or you do some unit conversion from the integer values.

A: well here's someting new to me: f90 allows a mix of comma and space delimiters for a simple list directed read:
read(unit,*)v1,v2,v3,v4

with input
1.222  2 , 3.14 , 4

yields
1.222000  2.000000 3.140000 4.000000


text: Q: Converting Parse to AWS I have read the posts creating the Parse environment on a MondoDB instance on AWS, but I am more interested in converting my parse storage to native AWS.  Does anyone have any examples of doing this.  I am trying to figure out if you can use S3 or do you have to use the noSql DB to mimic the "Class", "Column" structure of Parse.  My App uses the Class name as the customer and the columns are the customer specific data files, the columns are all text files and image files.  Thanks


text:
Q: perpendicular distance to center of square from line in terms of slope I am trying to find the relationship between the vertical distance (V) from the center of the square to the line to the perpendicular distance (P) from the center of the square to the line in terms of slope.
I know the answer.
The vertical distances are related to the perdendicular distances by a factor of    such that p=cv where dx=x2-x1 and dy = y2-y1
However I do not know how to find this relationship...can someone step through the math that arrives at this?
In the image I have increased the size of the square.  In my problem I am trying to find this relationship for each square in the grid that the line cuts through.  Then I can find P at any square on the grid.  I believe the relationship should be the same in either case.

A: First, note that the square has nothing to do with it -- you never talk about the square in any way other than referring to its center, so it's easier to just talk about points.
The relationship arises because the triangle you drew has the same angles as a triangle demonstrating the slope of the line. If you draw a triangle underneath the line with one horizontal side of length $\Delta x$ and one vertical side of length $\Delta y$, that triangle has the same angles, since it has a right angle and the two angles between the vertical lines and the given line are the same.
That means that the ratios of corresponding sides must be the same. The side corresponding to $P$ has length $\Delta x$, and the side corresponding to $V$ is the hypotenuse, which by Pythagoras has length $\sqrt{\Delta x^2 + \Delta y^2}$.


text:
Q: Iterating through two Lists and checking the item value of the first list to the item values of the second list with a lambda expression So in the program I'm trying to run I receive two lists, one with objects that contain an id in string format (looks something like "bb_b1203322") and one list with the id's(which in this place is only named "b1203322" for reasons unknown) and a description of the actually id's meaning.
var forms = await _tRepository.GetAllFormsAsync(lastUpdate);
var formDefinitions = await _deRepository.GetAllFormDefintionsAsync();

foreach (var form in forms)
{
    foreach (var def in formDefinitions)
    {
        if (form.SetupFormName.Contains(def.BLKID))
            form.SetupFormName = def.DESCR;
    }
}
return forms;

Now this piece of code does exactly what I want it to, but I'd rather have it as a lambda expression because ... reasons :)
Now I've tried several different things but with my current knowledge of lambda expressions I can't get it to work.

A: This code uses a bit of LINQ to find the definition:
foreach(var form in forms)
{
    var def = formDefinitions.FirstOrDefault(x => form.SetupFormName.Contains(x.DESCR));
    if(def != null)
        form.SetupFormName = def.DESCR
}

As you can see, it's not really saving all that much code.
Please note:
As Jon correctly comments, the behavior of this code is a bit different from your original one. This code uses the first occurrence if there are multiple and your code uses the last occurrence.
If this is actually a use case for your code, replace FirstOrDefault with LastOrDefault.
Extending the code above, you can do something like this:
foreach(var tuple in forms.Select(x => new { Form = x,
                                             Definition =
                                               formDefinitions.FirstOrDefault(y =>
                                                   x.SetupFormName.Contains(y.DESCR)) })
                          .Where(x => x.Definition != null))
{
    tuple.Form.SetupFormName = tuple.Definition.DESCR;
}

But as you can see, this gets messy real quick.

A: Try this code. Note that you can use it if formDefinitions with suitable DESCR always exists.
forms.ForEach(f => f.SetupFormName = formDefinitions.FirstOrDefault(fd =>
    f.SetupFormName.Contains(fd.DESCR)).DESCR);


text:
Q: Are random seeds "spent" in some way? I expected this code to give me the same number each time:
set.seed(1)
sample(rep(1:100), size = 1)

However, it doesn't. Here's is how it behaves: it gives me the same number if I run the two lines directly after each other, however, if I then run the second line once again, it gives me something different. Does that mean the seed is "spent" after running sample() once?
I need to produce code that includes random sampling, but which is reproducible. How can I make sure the same, random number is produced each time?

A: This isn't exactly how things really work, but it helps for understanding.
Imagine that we're drawing numbers between 0 and 9 by looking them up in a pre-generated book of random numbers. A really long book with lots and lots of random draws made by some bored undergraduate intern with a fair 10-sided die. What R normally does is look at the number following whatever the previous random number was in the book. So if the book starts 4, 5, 2, 8, 3, 4, 4, 1, 7, 0, 4, ... the first random number will be 4, then 5 etc.
The results will be as random as the book is---no matter where in the book we start. Typically, you don't know what you're going to get because you have no idea where in the book R is currently at, maybe page 103, maybe page 10003. Setting the seed tells R to start at a specific place. So set.seed(1) says "start on page 1", so you now can count on that "4" being first, and then followed by a 5, and so forth.

A: It's not that the seed is spent; rather, setting the seed produces a fixed sequence of pseudo-random values that you'll be sampling from. Once you've sampled one value from the sequence, the next value you sample will be the subsequent value in the sequence. However, if you reset the seed, then you will start back at the beginning of the sequence when you sample again.


text:
Q: SQL Server Express inserts doesn't work anymore In my C# application, I do the following:
using (SqlConnection connection = new SqlConnection(connectionstr))
{
    connection.Open();
    SqlCommand com1 = new SqlCommand("insert into Anfangstierbestand(bestand, jahr, loginid) VALUES (" + bestand + ", " + jahr + ", " + loginid + ");", connection);
    SqlCommand com2 = new SqlCommand("select * from Anfangstierbestand;", connection);

    com1.Connection = connection;
    int ferksum = 0;

    com1.ExecuteNonQuery();
    connection.Close();

    connection.Open();
    SqlDataReader read = com2.ExecuteReader();

    while (read.Read())
    {
        ferksum += Convert.ToInt32(read[2]);
    }

    // MessageBox.Show("Fehler beim Erstellen des Tierbestandes", "Fehler"); }
    MessageBox.Show(ferksum.ToString());
}

It's a simple insert to a database. I added com2 to check, if the insert works.
Unfortunately, the the value of com2 tells me, that it works, but when I go to the Server Explorer and press Execute SQL, there are no new values.
I don´t know the reason. The code above is just an example, since a few days, no insert works anymore(before, the same code works).
Does anybody know what the reason can be?
EDIT:
C#:
string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;";

EDIT2:
Server Explorer:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\user\Desktop\Farmer´s Calc\Programmierung\WPF\Finanz_WPF\Finanz_WPF\Datenbank\FarmersCalc.mdf";Integrated Security=True;User Instance=True

EDIT3:
Here are the columns:
id int,
jahr int,
anzahl int,
loginid int

EDIT4:
Is it possible that it´s a problem that I opened my project with expression blend? Normally, I work with VS 2010...
EDIT5:
Even because I can not answer my question(<100 reputations) I write it here:
Shame on me. Some of you were right, it was the wrong database-file. But I´m still wondering, why this happened, because I did not change anything since a few days and before this, it worked!
Thanks to all for helping!

A: You're using user instances, why? Isn't it possible that the instance you're connecting to in Server Explorer is not the same as the instance where your app is inserting data? What happens when you select data from within the app, does it reflect your insert(s)? It seems to me based on your connection strings that these are two completely different MDF files - they have the same name but they are in different locations.

A: Is the issue implicit transactions? Do you need to issue a commit of the SQL Insert? If com2 tells you that it's there then it may only see it since it's in the context of the current SQL transaction.
You should share your connection string for both Server Explorer and your SqlConnection (connectionstr). Ensure that you setup your Server Explorer connection with User Instance=true;.

A: As a diagnostic,
 connection.Open();
 int n = com1.ExecuteNonQuery();
 // log or show 'n' , the nr of rows affected

Edit, after seeing the connectionstrings:
local db files in |DataDirectory|\ are very prone to be overwritten by the next run or build command.
Make sure you set them to 'copy never' or 'copy if newer' in the VS Solution explorer.

A: Perhaps somewhere in the callstack above this code, someone has added a TransactionScope.
This would cause the connections to enroll automatically in the transaction, and the connections could see the data inserted via that not-yet-committed transaction.  When the scope is exitted without calling scope.Complete, the transaction gets rolled back and no data is saved.


text:
Q: convert from 'to_julian_date()' to 'np.datetime64' consider array below
dt = DatetimeIndex(['2016-01-01', '2016-01-01', '2016-01-21', '2016-01-21'], dtype='datetime64[ns]', name=u'date', freq=None)

i convert the above to_julian_date()dtype
j = dt.to_julian_date()
Float64Index([2457388.5, 2457388.5, 2457408.5, 2457408.5], dtype='float64')

how can I convert jback to dt
I tried
dt = pd.to_datetime(j, errors = 'coerce')

it converts j back to datetime object, but the values are not the same, here is the output
DatetimeIndex(['1970-01-01 00:00:00.002457388',
           '1970-01-01 00:00:00.002457388',
           '1970-01-01 00:00:00.002457408',
           '1970-01-01 00:00:00.002457408'],
          dtype='datetime64[ns]', freq=None)

A: Julian dates are number of days from a long time ago.  A time prior to the pandas Timestamp epoch.  We refer to the beginning of when a system of tracking time begins tracking time.  For Timestamp that is '1970-01-01'.  What I do is get the Timestamp epoch with pd.to_datetime(0, unit='s').  That is the first possible pandas.Timestamp.  Then I assign the number of days of that Timestamp from the beginning of the Julian Date by running to_julian_date() on that Timestamp.  Now that I have the number of days from the beginning of the Julian start date to the Timestamp epoch, I subtract that from each of the Julian dates in j and that becomes the number of days from the Timestamp epoch (or '1970-01-01').  I can then use pd.to_datetime(j - epoch, unit='D') to give me the Timestamps where each of my values represent the number of days from the Timestamp epoch.
I hope that is clear ;-)
first find the julian_date for the pd.Timestamp epoch
epoch = pd.to_datetime(0, unit='s').to_julian_date()

then conversion is done with pd.to_datetime using the parameter unit='D'
pd.to_datetime(j - epoch, unit='D')

DatetimeIndex(['2016-01-01', '2016-01-01', '2016-01-21', '2016-01-21'], dtype='datetime64[ns]', freq=None)


text:
Q: How does AirDrop retain "Developer Verification" information? And, can this be done with other methods? I am trying to share an app. AirDrop successfully completed this task. However, when e-mail is used, the error regarding an unknown developer prevents the app from running. Why is AirDrop successful and e-mail not?
Is there something I can do to share the app and retain the developer information?

A: Apps are actually containers, if the container doesn't contain a verified developer certificate then you will see that message pop-up when you try to open the app.
If you right click and select open it will still let you open the app, irregardless if it is from a verified developer or not.


text:
Q: Error detected while processing InsertEnter Autocommands: E117: Unknown function: jedi#remove_usages I'm trying to setup vim-jedi on neovim.
Whenever I open a python file and switch to Insert mode I get the following error:
Error detected while processing InsertEnter Autocommands for "<buffer=1>":
E117: Unknown function: jedi#remove_usages

I'm really new to (neo)vim so I'd really appreciate if could help me resolve this issue, thanks!
Below, I'm providing the information I think is relevant. Please let me know if you require me to provide anything else.
My setup
First I installed vim-jedi from pacman then I set my init.vim file to the following.
" My .nvimrc(init.vim) file
"

:set number relativenumber
:set termguicolors

" Plugins
call plug#begin()
    " Solarized theme
    let g:neosolarized_contrast = "normal"
    set background=dark
    Plug 'iCyMind/NeoSolarized'

    " Python Completions via jedi
    Plug 'davidhalter/jedi-vim', { 'for':  'python' }

call plug#end()

" Select Solarized as my theme.
colorscheme NeoSolarized

Afterwards I

*

*Ran :PlugInstall

*Restarted nvim

*Ran :PlugUpdate

*Restarted nvim and opened my file with nvim db.py.

The file I opened contains the following:
"""Database management functions"""

import tasks3.tasks3.db as db

def init(db_path: str):
    engine = db.create_engine(db_path)
    Base.metadata.create_all(bind=engine)

def purge(db_path: str):
    engine = db.create_engine(db_path)
    session = db.orm.sessionmaker(bind=engine)

def drop(db_path: str):
    pass

To the best of my knowledge I don't have any additional scripts for nvim.
Additional Note (not sure if this is related)
In the context of the above purge function if type session. I get the following message:
-- Omni completion (^O^N^P) Pattern not found


text:
Q: Argument of type 'number' is not assignable to parameter of type Custom Request I am getting the following error but am not sure why.
Argument of type 'number' is not assignable to parameter of type 'CustomRequest'

this.accountNumber = 4048358124;
//When I pass account number as a parameter below I get the error
this.myService.myMethod(this.accountNumber).subscribe((resp)=>{
      console.log("CustomRequest response: "+resp);
})

export interface CustomRequest{
  accountNumber: number
}

myMethod(request: CustomRequest):
  Observable<CustomResponse> {
  return this.myProxyService.GetAVAFPreValidateLoanAdjustment(request);
}

I don't know why it is saying that type number is not the same type as CustomRequest as they are both numbers. Any ideas?

A: The problem is that there is a mismatch in the data passed in the function.

this.myService.myMethod({accountNumber:this.accountNumber}).subscribe((resp)=>{
      console.log("CustomRequest response: "+resp);
})

Function myMethod was expecting the param to be of type CustomRequest but you were just sending the number because of which the type check error was happening. The above code should fix your issue.


text:
Q: How to read tab sepereated values in PHP using fscanf Recently I was practicing problems in Hackearth and I was unable to scan tab-separated values.
Ex(Inputs): 12 3 6 1
The input is treated as a file, it seems, because fscanf is used to read it.
I was trying to scan it using while loop like this:
$arr = [];
$i = 0;
while($i < 4){
 fscanf(STDIN, "%s\t", $a);
 $arr[] = $a;
 $i++;
}

But when I am printing $arr like:
print_r($arr);

It shows like this:
Array
(
    [0] => 12
    [1] => 12
    [2] => 12
    [3] => 12
)

I checked this problem but unable to solve my problem.
How can I scan all the numbers using a loop and put it in an array?

A: According to the documentation:

Each call to fscanf() reads one line from the file.

So you can't call fscanf() in a loop to read each number from the same line. The second iteration tries to read the next line, but there isn't one.
You can use fgets() to read a whole line, then use explode() to split it into an array at the delimiters:
$line = fgets(STDIN);
$line = rtrim($line); // remove the newline
$arr = explode("\t", $line);

Or use fgetcsv() to do this in one step:
$arr = fgetcsv(STDIN, 0, "\t");


text:
Q: Thread, Asynctask or intentService for my app? I need your opinion for my app. I'm developing an app which communicates with a radio via bluetooth. App is divided into 3 (swipe) tabs :

*

*In the first I put a connection option and a "connect" button to connect my device to a radio.

*In the second there is a map which shows my position (radio can send a GPS string, I decode it with my algorithm and I obtain latitude and longitude).

*In the third there is a similar bluetooth chat option with which I can send/receive simple text message to the radio.
This app must stay in background and connected to the radio and it must show (similar to an SMS) in the notification area an icon which says "message received". So I want your opinion to develop the app: I have to use a thread/asynctask for connection, a thread/asynctask for the map and a intentservice for the messages or what do you think should be done? This is my first app in background, last month I implemented a part of my app with asynctask.
Thank you for your help.

A: AsyncTask should be used when you have to perform a short-lived operation on a separate thread and post the final result on the main / UI thread, which is not the case with your app I believe.
Service should be used to perform long-running tasks which take place in the background and continue working irrespective of whether there is an Activity in the foreground or not. Service, though, still runs on the main thread, which means that if you do a lot of heavy computations on this Service, it will slow down your UI (when the UI is present).
Which brings us to IntentService, which performs a long-running operation on a separate thread and works in the background irrespective of whether an Activity is present or not.
So IntentService is probably the best bet in a situation where you want a smooth UI but you also have work going on in the background independent of the UI components of the app (AsyncTask cannot do this). However, your work is cut out for you, as you will still have to synchronize / bind the IntentService with the Activity when you want to transmit data.


text:
Q: PHP PayPal simple API, one time payment I have this code to setup recurring payments on PayPal
$p->add_field('cmd','_xclick-subscriptions');
$p->add_field('business','payments@pitchmystuff.com');
$p->add_field('item_name', 'Remove Album Release');
$p->add_field('return', $this_script.'?action=success&idAlbum='.$idAlbum.'&package='.$package);
$p->add_field('cancel_return', $this_script.'?action=cancel&idAlbum='.$idAlbum);
$p->add_field('notify_url', 'http://pitchmystuff.com/modules/yobilab/digidist/PayPal/paypal_remove.php');
$p->add_field('no_note','1');
$p->add_field('currency_code','USD');
$p->add_field('a3', "$paymentAmount");
$p->add_field('t3', "Y");
$p->add_field('p3', "1");
$p->add_field('src', "1");
$p->add_field('sra', "1");

How do I change it to work with ONE TIME payments and NOT recurring?
Thanks

A: Change $p->add_field('cmd','_xclick-subscriptions'); to $p->add_field('cmd','_xclick'); to enable one time payments.

A: Note: I haven't used the subscription / recurring payments API before, so bear that in mind when reading my answer as there may be a way to do this with the API you are using that I don't know about.
For one time payments you might try using the adaptive payments API or the express checkout API instead, docs for express checkout API are here:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECGettingStarted
And docs for adaptive payments API:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_APIntro
(another note - paypal has been moving everything to x.com but managed to somehow lose alot of their docs, so they are kinda spread over two sites. Also, x.com is bad.)
Hope this helps
EDIT: at a guess, your 'cmd' param needs changed. Not sure what you should change it TO, however.

A: Set p3 to 0 (p3 - number of time periods between each recurrence)


text:
Q: Select and crop face image from photo image (ios) I'm trying to get cropped image from photo. I have the following code that crop image that was got from ios face detection sdk:
- (UIImage *)scaleAndRotateImage:(CIFeature *)ciFeature image:(UIImage *)image {
    static int kMaxResolution = 640;

    CGImageRef imgRef = image.CGImage;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
        } else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }

    CGFloat scaleRatio = bounds.size.width / width;

    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {
        case UIImageOrientationUp:
            transform = CGAffineTransformIdentity;
            break;
                default:
            [NSException raise:NSInternalInconsistencyException
                        format:@"Invalid image orientation"];
    }

    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    } else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    CGContextConcatCTM(context, transform);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return returnImage;
}

But how can I crop only face from the image (Like face image in box) because for now it changes original resolution of image?

A: If you want to crop your image with more conveniently and more user-defined, I recommend you to use the RSKImageCropper, its github location is here:https://github.com/ruslanskorb/RSKImageCropper
Because you want to crop the face's position, so the system's default method is not satisfy your requirement, you can learn from here:https://developer.apple.com/library/content/documentation/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/PickinganItemfromthePhotoLibrary.html#//apple_ref/doc/uid/TP40010408-SW1
The Core Graphic's crop image method:CGImageCreateWithImageInRect, is not easy to confirm the rect you want, because you for get the position of the face you should do a lot of work, the RSKImageCropper may be your convenient choise.


text:
Q: What is more prefered way of updating data in child components hooks or redux? i am new to JS.
And I wondered what is more prefered way for updating data in children components.
Is that better to use hooks or redux?
Let say i have a parent component with 3 child components.
<Parent>
  <ChildA/>
  <ChildB/>
  <ChildC/>
</Parent>

And i have a need to update something in ChildA and ChildB and pass it to ChildC
What would the best way to do it ?
Shall i use hooks like this?
[childAValue, setChildAValue] = useState([])
[childBValue, setChildBValue] = useState([])

  <ChildA onChildChanged={(e) => {
    setChildAValue(e)
    }}
  />
  <ChildB onChildChanged={(e) => {
    setChildBValue(e)
    }}
  />
  <ChildC childAValue={childAValue} setChildBValue={setChildBValue} />

Or it's better to use redux ?
Because with using hooks i may have a lot of rerendering if there are 3-4 components or more.
But on the other hand Redux will be just overloaded if i will use it for every possible component
Which way do you prefer more and why?
This question also refears to modals also when you need to pass value from modals to suibling component/s.

A: here you have multiple child components, you need to pass down functions to change them in all of them, redux can be used here and it will remove the hassle pass down props to each of the components. Redux is industry standard and is being used in large web projects, where you need to manage a global state to be present and accessible in all of the components/modules, for example Authentication state,
for your question simply passing down as props also works so there is no need to complicate things further.


text:
Q: How do fix Safari extensions on Safari 12? Since installing Safari 12, I've been unable to get my extensions working. In particular I have no functioning ad blocker, and the primary extension I use, Pocket, (rally the only reason I use Safari at all) doesn't seem to work. In order to prevent Safari from showing repeated warnings each time I launch it, I've cleared out my extensions and emptied ~/Library/Safari/Extensions/.
How do I get and ad blocker and Pocket working with Safari 12?

A: The latest Safari update (12.0, Sept 17, 2018) turns off some and and stops supporting other extensions.
I don't see Pocket on Apple's new list of supported Safari Extensions (https://itunes.apple.com/us/story/id1377753262). That might be why Pocket now recommends that Mac users just use their Mac app: https://help.getpocket.com/article/1042-using-pocket-for-safari
Pocket may update their extension such that Apple starts supporting it again. Until then, there might be a javascript bookmark(let) for saving items to Pocket (https://support.apple.com/en-us/HT4550) or a Pocket email address to which you can send items to your account (https://getpocket.com/add/).
Update: Some unsupported extensions work again in Safari 12. E.g.,

*

*The "Zotero Connector" extension for Safari (https://www.zotero.org/download/) now works for me even though—as I write this—it does not show up in Safari's list of supported extensions in the Mac App Store (https://itunes.apple.com/us/story/id1377753262).

A: I loaded Pocket from here and it seems to work with Safari. I use the ad blocker "Ka-Block!" and it appears to be working... So load Pocket and use Ka-Block and they work together on my machine.


text:
Q: Shell command not found in python script I source a dotcshrc file in my python script with :os.system('/bin/csh dotcshrc') and it works,but when I want to use the command I have just put into the env by the source command,like os.system('ikvalidate mycase '),linux complaints:command not found.
But when I do it all by hand,everything go well.
Where is problem?

A: If you have a command in linux like ls and you want to use it in your python code do like this:
import os
ls = lambda : os.system('ls')
# This effectively turns that command into a python function.
ls() # skadoosh!

Output is :
FileManip.py                          Oscar
MySafety                              PROJECT DOCS
GooSpace                              Pg Admin
l1_2014                               PlatformMavenRepo
l1_2015                               R
l1_201617                             R64
l2_2014                               Resources

A: os.system runs each command in its own isolated environment. If you are sourcing something in an os.system call, subsequent calls will not see that because they are starting with a fresh shell environment. If you have dependencies like the above, you might be able to combine it into one call:
os.system('/bin/csh "dotcshrc; ikvalidate mycase"')


text:
Q: mongodb $nin operator doesn't work I am fiddling a bit with mongodb.
I have 2 collections with documents sharing same ids and I want to get all documents ids from colB not in colA.
Ids are simple integers
First I fetch all IDs from colA in an array and then use it with the $nin operator in a second query.
But the $nin operator returns no data.
Is the array provided to the $nin operator too large? The query returns no error.
(On a production environment I would probably check the consistency in an other way)
Take a look at my troubleshoot mongoshell script.
Output
MongoDB shell version: 3.2.5
connecting to: test
MATCHES
2032
MATCHES DETAILS
2004
MATCHES DETAILS not found using manual check
28
MATCHES DETAILS not found using find $nin
0
MATCHES DETAILS found using find $in
2004

Script
var rito = new Mongo("localhost").getDB("riotData");
var allMatchesIds = rito.matches.find({}, {_id: true}).map(a => a._id );

var allMatchesDetailIds = rito.matchDetail.find({}, {_id: true}).map(a => a._id );

var matchesNotFound = [];
for (var i = 0; i < allMatchesIds.length ; i++ ) {
    var found = false;
    for (var j = 0; j < allMatchesDetailIds.length ; j++ ) {
        if(allMatchesIds[i] === allMatchesDetailIds[j])
            found = true;
    }
    if(!found)
        matchesNotFound.push(allMatchesIds[i])
}

var matchesNotFoundMongo = rito.matchDetail.find({_id: {$nin: allMatchesIds}},{_id: true}).count();
var matchesFound = rito.matchDetail.find({_id: {$in: allMatchesIds}},{_id: true}).count();

print("MATCHES");
printjson(allMatchesIds.length);
print("MATCHES DETAILS");
printjson(allMatchesDetailIds.length);
print("MATCHES DETAILS not found using manual check");
printjson(matchesNotFound.length);

print("MATCHES DETAILS not found using find $nin");
printjson(matchesNotFoundMongo);
print("MATCHES DETAILS found using find $in");

printjson(matchesFound);


text:
Q: In Python, is a list synonymous with an array? I've used JavaScript before where we use arrays. I'm following a textbook that teaches Python. I'm now learning about lists. They sound exactly like arrays. Is list simply the Python word for array, or does Python have arrays and lists which are different things?

A: Yes, lists are the data structure in Python.
Sidenote: Numpy (a python library) has arrays
But, as pointed out in the comments Python does, in-fact, have an array module. Which is a list of all the same data types

A: you can check:
type([]) == type(list())

Which returns True.
Just make sure with a friend that [] is a list...

A: Python's lists can be treated as arrays, but they are not arrays. They are the closest thing to Javascript arrays, though.
Numpy has high performance arrays for numerical computations, but all elements must be of the same type.


text:
Q: 404 error with restangular What I'm I doing wrong from the code below. I'm trying to fetch data from an API however I get a 404 not found. the URL if I hit the browser works and it's the correct URL. I have even tried adding n the full url i.e. http://127.0.0.1:8000/api/v1/campaign/testcamp/ but this still gives me the same 404. Why?
I'm using angularjs with restangular:
app.controller("CampaignData" , ['$scope', 'Restangular',
    function($scope, Restangular){
        Restangular.one('/api/v1/campaign/testcamp/', "").get().then(
            function(campaign) {
                $scope.campaign = campaign;
                console.log(campaign)
            }
        );
}]);

A: Instead of an empty string you should specify the id of item you want to GET, like that:
Restangular.one('/api/v1/campaign/testcamp/', "id_of_item")

and looking into the query itself it will probably look something like that:
Restangular.one('/api/v1/campaign/', "testcamp")

If you get still 404 it may simply mean that your server is not configured properly.


text:
Q: Can't get html5 download to work programmatically in Firefox(Works on Safari, IE, Opera, Chrome)     onDownload: function() {
        var element = document.createElement("a");
        element.setAttribute("href", "/metadata/rest/swagger?namespace=" + this.namespace);
        element.click();
    },

Add a download function to a button. But it doesn't work in Firefox.(Works on Safari, IE, Opera, Chromes)
After changing the code in following way:
Create  anchor (<a>) in the html page, make it hidden and give  an id before. Get the element by id.  Set the href attribute
onDownload: function() {
        var element = document.getElementById("download");
        element.setAttribute("href", "/metadata/rest/swagger?namespace=" + this.namespace);
        element.click();
},

It works on all the browsers mentioned. Why?

A: I can see in the docs:
createElement

Doesn't conform to the DOM spec for XUL and XHTML documents: localName and namespaceURI are not set to null on the created element.

Though, I'm not fully convinced, you may use createElementNS instead:
var element = document.createElementNS(this.namespace, 'a');

This post might not fully answer, but I hope you'll get some help to go through. Just trying to help if you can find it useful for a solution.

A: You may use HTML5 download attribute.

<a href="/path/to/file" download>

*

*For more about the HTML5 download attribute you may read Anchor element - MDN Docs

*For browser support check here
You can change the href value accordingly using javascript.


text:
Q: On rational functions with rational power series  Let $f(z)=\sum_{n\geq 0}a_n z^n$ be a Taylor series with rational coefficients with infinitely non-zero $a_n$ which converges
in a small neighboorhood around $0$. Furthermore, assume that
\begin{align*}
f(z)=\frac{P(z)}{Q(z)},
\end{align*}
where $P(z)$ and $Q(z)$ are coprime monic complex polynomials. By developing $\frac{P(z)}{Q(z)}$ as a power sereis around $0$ and comparing it with $f(z)$ we obtain infinitely many polynomial equations in the roots of $P(z)$ and $Q(z)$ which are equal to rational numbers so this seems to force the roots of $P(z)$ and $Q(z)$ to be algebraic numbers.
Q: How does one prove this rigourously?

A: Let there be two fields $k\subset K$, and let $f\in k[[x]]$ be a formal power series with coefficients in $k$. If $f\in K(x)$ (rational functions with coefficients in $K$) then $f\in k(x)$. A proof of this is given in J.S. Milne's notes on Etale Cohomology (lemma 27.9).

A: Well, I think there is a simpler argument. For a power series $g(x)\in\mathbb{C}[[x]]$
and $\sigma\in Aut(\mathbb{C})$ (note that except for the complex conjugation or the identity $\sigma$ is not continuous!) we may define define the power series with coefficients twisted by $\sigma$ which we denote by $g^{\sigma}(x)$. Now an element in $Aut(\mathbb{C})$ respect finite sum and products so it follows from that,
that for all $\sigma\in Aut(\mathbb{C})$ one has
$$
f^{\sigma}(z)=\frac{P^{\sigma}(z)}{Q^{\sigma}(z)}.
$$
From this (and the unique factorization of $\mathbf{C}[x]$) it follows that $P(z)$ and $Q(z)$ have rational coefficients.


text:
Q: How to use Limits in DynamoDB I have a dynamoDb table customers.
In this table I have 20m+ rows of data.
Schema of the table:

*

*Partition Key - group_id

*Sorting Key - customer_email

I have an attribute called
     "assigned_lists": [
        "e9d55940-77da-11e9-9c25-df4d7393de10",
        ...
     ]

in this table. The assigned_lists is a list datatype of strings. I want that customer who belongs to some assigned_lists. Simply I searched for the contains function of the dynamo DB
 FilterExpression: "contains(#list, :searchForThisList)"

I'm querying on this table with the limit of 100 means I need 100 customers which belong in given assigned_lists one customer can be in multiple assigned_lists so I use the LIST datatype.
My approach for limit:
Limit : 100,
        Dynamo.query(params, (err,data)=>{
          if (typeof data.LastEvaluatedKey != "undefined") {
             if (data.Count < params.Limit) { //calculating that we get all the data or not

                    params.ExclusiveStartKey = data.LastEvaluatedKey;
                    params.Limit -= data.Count; //Setting the new limit for the next query
                    dynamoDb.query(params, againComeHere);
                    } else {
                       //my process with the data
                    }
        })

I have some questions:
Note: I'm beginner with dynamoDB
1. Have I use a fine logic for limiting? Because it takes more than 2 minutes for generating the results and I need to show it to the front in my website
2. Is the dynamoDb is a correct database for me?
I m eager for the responses.


text:
Q: Android Gridview getting focus I have a Linear Layout and at the very bottom i have a gridview (hotelsGrid) that i populate with more items to see, the problem is that after i set my adapter the view on the screen jumps to the bottom to show the gridview and i need to stay on the top, how can i archieve this?
Here is my XML:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/hotel_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".ActivityHotelDetail">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <include
            android:id="@+id/toolbar"
            layout="@layout/toolbar"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:background="@color/colorPrimaryDark"
            android:hapticFeedbackEnabled="true"
            app:tabGravity="fill"
            app:tabIndicatorColor="@color/colorPrimary"
            app:tabIndicatorHeight="3dp"
            app:tabMode="fixed"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <ScrollView
        android:id="@+id/mainScroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/activity_vertical_margin"
                android:background="@drawable/panel_with_border_nopadding"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/hotelName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/fondo_titulo"
                    android:gravity="center"
                    android:paddingBottom="10sp"
                    android:text="Nombre del Hotel"
                    android:textAppearance="@android:style/TextAppearance.Large"
                    android:textColor="@color/textColorPrimary"
                    android:textSize="28sp"/>

                <ImageView
                    android:id="@+id/hotelMainImage"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:adjustViewBounds="true"
                    android:paddingLeft="1dp"
                    android:paddingRight="1dp"
                    android:scaleType="fitCenter"
                    android:src="@drawable/fondo_360"/>

                <LinearLayout
                    android:id="@+id/video360"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:visibility="gone">

                    <FrameLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentTop="true"
                        android:layout_centerHorizontal="true">

                        <com.google.vr.sdk.widgets.video.VrVideoView
                            android:id="@+id/video_view"
                            android:layout_width="match_parent"
                            android:layout_height="250dip"
                            android:scrollbars="@null"/>

                        <ImageView
                            android:id="@+id/playButton"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:layout_marginBottom="10dip"
                            android:adjustViewBounds="true"
                            android:background="@drawable/playbutton"
                            android:scaleType="fitXY"/>
                    </FrameLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal">

                        <ImageButton
                            android:id="@+id/play_toggle"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:background="@android:color/transparent"
                            android:paddingStart="0dp"
                            android:paddingTop="4dp"
                            android:src="@drawable/play_on"/>
                        <!-- Seeking UI & progress indicator.-->
                        <SeekBar
                            android:id="@+id/seek_bar"
                            style="?android:attr/progressBarStyleHorizontal"
                            android:layout_width="0dp"
                            android:layout_height="32dp"
                            android:layout_weight="8"/>

                        <ImageButton
                            android:id="@+id/volume_toggle"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:background="@android:color/transparent"
                            android:paddingStart="0dp"
                            android:paddingTop="4dp"
                            android:src="@drawable/volume_on"/>
                    </LinearLayout>
                </LinearLayout>

                <TextView
                    android:id="@+id/hotelDistance"
                    android:layout_width="match_parent"
                    android:layout_height="26sp"
                    android:layout_marginBottom="@dimen/activity_vertical_margin"
                    android:layout_marginLeft="1dp"
                    android:layout_marginRight="1dp"
                    android:background="@drawable/fondo_distancia"
                    android:gravity="center"
                    android:text="distance"
                    android:textColor="@color/textColorPrimary"/>

                <TextView
                    android:id="@+id/hotelAddress"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_below="@+id/imagepreview"
                    android:layout_marginBottom="@dimen/activity_vertical_margin"
                    android:gravity="center"
                    android:text="Direccion"
                    android:textColor="@color/textColorSecundary"/>

                <TextView
                    android:id="@+id/hotelDescription"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/activity_vertical_margin"
                    android:gravity="center"
                    android:paddingLeft="@dimen/activity_horizontal_margin"
                    android:paddingRight="@dimen/activity_horizontal_margin"
                    android:text="Descripcion"/>
            </LinearLayout>

            <RelativeLayout
                android:id="@+id/otherHotelsRL"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginRight="@dimen/activity_vertical_margin"
                android:layout_marginTop="20dp"
                android:background="@drawable/panel_with_border_nopadding"
                android:paddingLeft="1dp"
                android:paddingRight="1dp">

                <TextView
                    android:id="@+id/otherViewsTxt"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:text="Fotos"
                    android:textColor="@color/textColorSecundary"
                    android:textSize="22sp"/>

                <HorizontalScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_alignParentStart="true"
                    android:layout_below="@+id/otherViewsTxt"
                    android:layout_marginBottom="10dp"
                    android:fillViewport="true">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent"
                        android:orientation="horizontal">

                        <ImageView
                            android:id="@+id/thumb1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginEnd="5dp"
                            android:layout_weight="1"
                            android:src="@mipmap/icon_360"/>

                        <ImageView
                            android:id="@+id/thumb2"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/thumb1"
                            android:layout_marginEnd="5dp"
                            android:layout_weight="1"
                            android:src="@mipmap/icon_360"/>

                        <ImageView
                            android:id="@+id/thumb3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/thumb2"
                            android:layout_weight="1"
                            android:src="@mipmap/icon_360"/>
                    </LinearLayout>
                </HorizontalScrollView>

                <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_centerVertical="true"
                    android:layout_weight="1"
                    android:alpha="0.8"
                    android:background="#222222"
                    app:srcCompat="@drawable/ic_chevron_left_white_24dp"/>

                <ImageView
                    android:id="@+id/imageView2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_centerVertical="true"
                    android:layout_weight="1"
                    android:alpha="0.8"
                    android:background="#222222"
                    app:srcCompat="@drawable/ic_chevron_right_white_24dp"/>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="30dp"
                android:layout_marginLeft="@dimen/activity_vertical_margin"
                android:layout_marginRight="@dimen/activity_vertical_margin"
                android:layout_marginTop="20dp"
                android:orientation="vertical"
                android:paddingBottom="1dp"
                android:paddingLeft="1dp"
                android:paddingRight="1dp">

                <TextView
                    android:id="@+id/otherHotelsTxt"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="5dp"
                    android:background="@drawable/panel_with_border_padding"
                    android:gravity="center"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:text="Mas Hoteles Interesantes"
                    android:textColor="@color/textColorSecundary"
                    android:textSize="22sp"/>

                <GridView
                    android:id="@+id/hotelsGrid"
                    android:layout_width="match_parent"
                    android:layout_height="350dp"
                    android:layout_marginTop="@dimen/activity_vertical_margin"
                    android:horizontalSpacing="15dp"
                    android:numColumns="2"
                    android:stretchMode="columnWidth"
                    android:verticalSpacing="15dp"/>
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

A: Add this to your top level Layout View --Linearlayout. to make it focusable
<LinearLayout
android:id="@+id/top_layout"
android:focusable="true"
android:focusableInTouchMode="true">

Now in Activity:
LinearLayout layout = (LinearLayout) findViewById(R.id.top_layout);
layout.requestFocus();

Then call layout.requestFocus(); after you have set the Adapter


text:
Q: Why do you need to specify the controller and action in the default route for the RoutesTable in ASP.NET MVC? Why do we have to specify the defaults for the default route?
This is a normal default route:
  routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
  );

Why can't I just do this:
  routes.MapRoute(
        name: "Default",
        url: "Home/Index/{id}",
        defaults: new {id = UrlParameter.Optional }
  );

I already specified the action and controller but when I use this way, I get an error. Does anyone know why you have to specify the action and controller in the default route?

A: Without a default set of parameters, how is routing supposed to know where to send this URL?
/
The defaults let you do that URL, so it knows to use the 'Home' controller's 'Index' method.
Or:
/Articles
In this case, the 'Index' action of the 'Articles' controller would be called. Without those defaults, again, routing has no way to know what to do.


text:
Q: Unable to received notification in device notification section in android This is my code to receive notification
public class FirebaseMessageReceiver
        extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        sendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());

    }

    private void sendNotification(String messageTitle,String messageBody) {
        Intent intent = new Intent(this, NotificationActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);

        long[] pattern = {500,500,500,500,500};

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setVibrate(pattern)
                .setLights(Color.BLUE,1,1)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

i am trying to received notification  from firebase console i am able to get to get call back when fire notification i am also getting title and msg code executed successfully but i am unable to see notification in notification section of device can any one please help me what i am doing mistake .

A: For devices running Android O or higher, you need to create a notification channel first in order to receive notifications like this:
private void createNotificationChannel() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Channel 1",
                    NotificationManager.IMPORTANCE_HIGH
            );

            channel.setDescription("This is Channel 1");

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
}

Also, you need to pass this CHANNEL_ID constant in NotificationCompact.Builder constructor like this:
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this, CHANNEL_ID)

A: Do you use notification channel?
If you are using Adroid 8 or higher it's expected behavior:

Starting in Android 8.0 (API level 26), all notifications must be
assigned to a channel or it will not appear.

https://developer.android.com/guide/topics/ui/notifiers/notifications#ManageChannels
Here you can find detail tutorial how to create notification channel:
https://developer.android.com/training/notify-user/channels


text:
Q: Why does docker container prompt "Permission denied"? I use following command to run a docker container, and map a directory from host(/root/database) to container(/tmp/install/database):
# docker run -it --name oracle_install -v /root/database:/tmp/install/database bofm/oracle12c:preinstall bash

But in container, I find I can't use ls to list contents in /tmp/install/database/ though I am root and have all privileges:
[root@77eb235aceac /]# cd /tmp/install/database/
[root@77eb235aceac database]# ls
ls: cannot open directory .: Permission denied
[root@77eb235aceac database]# id
uid=0(root) gid=0(root) groups=0(root)
[root@77eb235aceac database]# cd ..
[root@77eb235aceac install]# ls -alt
......
drwxr-xr-x. 7 root root  4096 Jul  7  2014 database

I check /root/database in host, and all things seem OK:
[root@localhost ~]# ls -lt
......
drwxr-xr-x.  7 root root       4096 Jul  7  2014 database

Why does docker container prompt "Permission denied"?
Update:
The root cause is related to SELinux. Actually, I met similar issue last year.

A: I had a similar issue when sharing an nfs mount point as a volume using docker-compose. I was able to resolve the issue with:
    docker-compose up --force-recreate

Eventhough you found the issue, this may help someone else.

A: Another reason is a mismatch with the UID/GID. This often shows up as being able to modify a mount as root but not as the containers user
You can set the UID, so for an ubuntu container running as ubuntu you may need to append :uid=1000 (check with id -u) or set the UID locally depending on your use case.

uid=value and gid=value
Set the owner and group of the  files  in  the  filesystem  (default: uid=gid=0)

There is a good blog about it here with this tmpfs example
docker run \
       --rm \
       --read-only \
       --tmpfs=/var/run/prosody:uid=100 \
       -it learning/tmpfs

http://www.dendeer.com/post/docker-tmpfs/

A: I got answer from a comment under: Why does docker container prompt Permission denied?
man docker-run gives the proper answer:

Labeling systems like SELinux require that proper labels are placed on volume content mounted into a container. Without a label, the security system might prevent the processes running
inside the container from using the content. By default, Docker does not change the labels set by the OS.
To change a label in the container context, you can add either of two suffixes :z or :Z to the volume mount. These suffixes tell Docker to relabel file objects on the shared volumes. The z option tells Docker that two containers share the volume content. As a result, Docker labels the content with a shared content label. Shared volume labels allow all containers to
read/write content.  The Z option tells Docker to label the content with a private unshared label.  Only the current container can use a private volume.

For example:
  docker run -it --name oracle_install -v /root/database:/tmp/install/database:z ...

A: A permission denied within a container for a shared directory could be due to the fact that this shared directory is stored on a device. By default containers cannot access any devices. Adding the option $docker run --privileged allows the container to access all devices and performs Kernel calls. This is not considered as secure.
A cleaner way to share device is to use the option docker run --device=/dev/sdb (if /dev/sdb is the device you want to share).
From the man page:

  --device=[]
      Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)

  --privileged=true|false
      Give extended privileges to this container. The default is false.

      By default, Docker containers are "unprivileged" (=false) and cannot, for example, run a Docker daemon inside the Docker container. This is because by default  a  container is not allowed to access any devices. A "privileged" container is given access to all devices.

      When  the  operator  executes  docker run --privileged, Docker will enable access to all devices on the host as well as set some configuration in AppArmor to allow the container nearly all the same access to the host as processes running outside of a container on the host.

A: So I was trying to run a C file using Python os.system in the container but the I was getting the same error my fix was while creating the image add this line RUN chmod -R 777 app it worked for me


text:
Q: ReactJS/Javascript/Graphql/React-apollo: passing query variables I am trying to figure out how to pass the input variables to a graphql query function to run a query and display the results.  Not sure if I am passing the variables correct when the button is clicked.  The getObjectQuery takes two variables startTime and endTime, both will be selected on the frontend by the user.
Parent Component:
class Calendar extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
          startTime: '',//This will keep track of the time
          endTime:'',

        };

        this.handleSubmit = this.handleSubmit.bind(this);

      }

      handleSubmit = event => {
        event.preventDefault();

        console.log(this.state.startTime);
        this.setState({
          startTime: new Date(document.getElementById("startTime").value).valueOf(),//getElementById is a jQuery method
          endTime: new Date(document.getElementById("endTime").value).valueOf()
        }, () => {
          this.props.data.refetch({//Assign the inputvalues, which is the current state, to the variables after pressing the submit button
            startTime: this.state.startTime,
            endTime:this.state.endTime
          });
          console.log(this.state.startTime);
          console.log(this.state.endTime);
        });
      };

      render() {

        console.log(this.props.data);//This is where data is.
        return (

            <form onSubmit={this.handleSubmit.bind(this)}>
              Start Time
              <input type="datetime-local" id="startTime" step="1" />

              End Time
              <input type="datetime-local" id="endTime" step="1" onSubmit={this.handleSubmit.bind(this)}/>
              <input type="submit" value="Submit" />

            </form>

            {<ElementList startTime={this.state.startTime} endTime={this.state.endTime}/>}

        );
      }
};
export default graphql(getObjectsQuery,
  { options: (ownProps) => {
    console.log(ownProps.startTime);
    return ({ variables: { startTime: ownProps.startTime,
                            endTime: ownProps.endTime
     } })
  } } )(Calendar);

Child Function
const ElementList = (props) => (
  <Query
    query={getObjectsQuery}
    variables={props.startTime, props.endTime}
  >
    {({ loading, error, data }) => {
      if (loading) return
Loading...
;
      if (error) return
Error
;

          return (
            <Item.Group divided>
              {data.action.map(action =>

{action.action}

{action.timestamp}

                  {action.object.map( (obj) => {
                    return (
{obj.filename}
)
                  })}

              )}

              </Item.Group>

            );

        }}

  </Query>
);

export default ElementList;

A: I believe your problem may be that you're just passing your props in as variables. They need to be set to specific property names in order for your graphql resolvers to accept them.
variables={{start: props.startTime, end: props.endTime}}


text:
Q: Ocaml, Module Graphics - Queuing keypresses I am writing a simple game in Ocaml, using its module Graphics to perform drawing and interaction. I came across the problem that Graphics.read_key() queues all presses for later use, therefore when I hold a key for a while then many "presses" are put into memory. After release the action is still performed.
Is there any way to delete entries from this queue, or just (even better) not queue them at all?

A: THis is problably not the most beautiful solution, but you can use key_pressed.
This function will return true if a keypress is available.
So once you have read a keypress with read_key you can flush your queue by calling read_key until key_pressed is false and ignoring the result.
(* flush_kp : unit -> unit *)
let flush_kp () = while key_pressed () do
                      let c = read_key ()
                      in ()
                  done ;;

Hope this could help.


text:
Q: VSCode C++ Compiled exe was infected with Win32:TrojanX-gen[Trj] I am setting up VSCode for C++, made some simple code (test.cpp) to test if things are working.
  #include <iostream>

using namespace std;

int main(){
    cout << "Hello";
}

When I click run code the console says "Access is denied" and my antivirus pops up and says the test.exe and tempCodeRunnerFile.exe was infected with Win32:TrojanX-gen[Trj].
What exactly is Win32:TrojanX-gen[Trj] and how do I grant access so my antivirus wont pop up?

A: I had this issue as well. Its simply because some antiviruses think that unsigned .exe files (which is the output of your CPP file after you compile) are some sort of malicious file. You do need to exclude this from your antivirus, and your best bet is to first find out which antivirus you have, and second go to the "exclusions" list and add either the folder you're working with, or the file itself. I'm assuming you have AVG lol Exclusions can be found in the settings of your antivirus. Right click on the icon and see if you can go to preferences or settings. Then look for exclusions, or even an advanced setting option, and keep looking for something along the exclusions nature.

A: Just add an exception to the folder which contains your c++ code. (The whole folder). It did the job for mine ^-^


text:
Q: Difference between jQuery selectors "ancestor descendant" and "parent > child" The following two forms of jQuery selectors seem to do the same thing:

*

*$("div > ul.posts")

*$("div ul.posts")

which is to select all the "ul" elements of class "posts" under "div" elements.
Is there any difference?

A: The first only selects ul.posts whose parentNode is div.
The second would also select:

A: Concerning $("div > ul.posts"), only direct descendants of DIVs will be selected.

List Item

Sub list item

    <fieldset>

List item

    </fieldset>

List item

while $("div ul.posts") will select all descendants matching the criteria. So all and any ul.posts will be selected, whatever their nesting level is as long as somewhere along the chain, they are within a div.

A: Oh. So "ancestor descendant" refers to all specified elements under a parent, no matter how deeply nested
While "parent child" refers only to the first specified element even if it occurs again somewhere else under the parent

A: I'm just adding a familiar reference here. I realize it's years after the original question but it was on the first page on Google and maybe this will help someone else.
Think of real-world ancestors and parents. Parent and Child are always one generation apart, but ancestors and their descendants can be hundreds of years apart. The > symbol helps symbolize the direct relation between parent and child.


text:
Q: ilike search really uses its index? I have a column called nickname and have created index for it.
 create index test_idx on test_table using btree (nickname);

My query is,
 select * from test_table where nickname ilike '%pga%';

test_table is having around 100k records. when I'm doing explain, i am getting some cost which is same as before creating the index. Why is that.?
(using Postgresql 9.2)
Edit 1:
nickname column is character varying(100)

A: LIKE with a wildcard at the start of the expression can't use a btree index. In order to make that query use an index, you need to create a trigram index for which you need to install the pg_trgm extension first.
create index on test_table using gin (nickname gin_trgm_ops);


text:
Q: For what reason there is PlatformID.MacOSX? Environment.OSVersion.Platform returns a PlatformID (Info: MSDN PlatformID).
This PlatformID's value can also be "Unix" or "MacOSX".
My question is - for what reason are these values implemented? I thought .NET wouldn't run on MacOSX or Unix systems?! I know that there is Mono for example and in my mind it would make sense if this were/is implemented in Mono. But why in MS .Net which won't run on Unix systems anyway?

A: Silverlight, which has a very .NET-like Runtime and is an official Microsoft product, runs fine on OSX - and does return "MacOSX" when used in Silverlight.