text:
Q: Find the element in an array, in which left elements are smaller and right elements are larger? Suppose if there's an array, find out the element left to which the elements are smaller and right to which the elements are larger. Else return -1. I know how to do this in O(n^2). But how can this be done in O(n)?
The code for O(n^2):
#include <iostream>
using namespace std;
int main(){
int array[] = {5, 1, 4, 3, 2, 8, 10, 7, 9};
int sizeOfArray = sizeof(array)/sizeof(array[0]);
for (int i = 1; i < sizeOfArray-1; ++i) {
    int j = i-1;
    int k = i+1;
    while(array[j] < array[i] && array[k] > array[i]){
        if(j == 0 && k == sizeOfArray-1){
            cout << array[i];
            return 0;
        }
        if(j>0){
            j--;
        }
        if(k<sizeOfArray){
            k++;
        }

    }
}
cout << -1;
return 0;
}

A: 1) scan the array from left to right, remembering the largest value so far;
2) scan the array from right to left, remembering the smallest value so far.
3) scan the two new arrays until you find a largest value not exceeding a smallest value.
Examples:
3 6 4 5 9 8 7

3 6 6 6 9 9 9
3 4 4 5 7 7 7

There is no solution.
3 2 4 6 9 8 7

3 3 4 6 9 9 9
2 2 4 6 7 7 7
    ^ ^

There are two solutions.
Actually, two scans are enough.

A: This is an O(3n) = O(n) implementation:
private static int findPivot(int[] a) {
    int length = a.length;
    int[] leftMax = new int[length];
    int[] rightMin = new int[length];
    leftMax[0] = a[0];
    for(int i=1; i<length; i++) {
        leftMax[i] = leftMax[i-1]>a[i]?leftMax[i-1]:a[i];
    }

    rightMin[length -1] = a[length-1];
    for(int i=length-2; i>0; i--) {
        rightMin[i] = rightMin[i+1]<a[i]?rightMin[i+1]:a[i];
    }

    int position = -1;
    for(int i=1; i<length-1; i++) {
        if(leftMax[i-1] < rightMin[i+1]) {
            position = i;
            break;
        }
    }

    return position;
}

These are the running results:
Initial array:  [5, -1, 3, 8, 6, 10]
Partitions:     [5, -1] 3 [8, 6, 10]
Initial array:  [5, 5, -2, -3, 0, 3, 8, 6, 10]
Partitions:     [5, 5, -2, -3, 0] 3 [8, 6, 10]
Initial array:  [3, -2, -2, -3, 0, 7, 2, 8, 6, 10]
Partitions:     [3, -2, -2, -3, 0, 7, 2, 8] 6 [10]

And here is how to print it that way:
public static void main(String[] args) {
    int[] a = { 5, -1, 3, 8, 6, 10 };

    int pivot = findPivot(a);
    if (pivot != -1) {
        printPartitions(pivot, a);
    }
    int[] b = { 5, 5, -2, -3, 0, 3, 8, 6, 10 };
    int pivot1 = findPivot(b);
    if (pivot1 != -1) {
        printPartitions(pivot1, b);
    }
    int[] c = { 3, -2, -2, -3, 0, 7, 2, 8, 6, 10 };
    int pivot2 = findPivot(c);
    if (pivot2 != -1) {
        printPartitions(pivot2, c);
    }
}

private static void printPartitions(int pivot, int[] a) {
    System.out.println("Initial array:\t" + Arrays.toString(a));
    System.out.println("Partitions:\t" + Arrays.toString(Arrays.copyOfRange(a, 0, pivot)) + " " + a[pivot] + " "
            + Arrays.toString(Arrays.copyOfRange(a, pivot + 1, a.length)));
}

A: // example with n2 complexity.

class Elementwithleftsidesmallerandrightsidegreater {

  static void find(int[] arr) {

    for (int i = 1; i < arr.length; i++) {

        int head = arr[i];

        int left = i - 1;
        int right = i + 1;

        while (left >= 0 && arr[left] < head) {

            left--;
        }

        while (right < arr.length && arr[right] > head) {
            right++;
        }

        if (left == -1 && right == arr.length) {
            System.out.println("index is " + i);
            System.out.println("value is " + arr[i]);

        }

    }

  }

  public static void main(String[] args) {
    int arr[] = new int[] { 2, 1, 1, 3, 111, 80, 100, 79, 19 };

    find(arr);

  }
}

A: It's O(n):
I've replaced my algorithm description with a code on JavaScript, so you can simply run it and see what's going on there. This code can be easily converted to C++.

var arrayItems = [1, 3, 2, 3, 4, 6, 4, 7, 9, 10, 8];
var sizeOfArray = arrayItems.length;
var maxValue = arrayItems[0];
var pointValue = maxValue;
var elIndex = -1;
for (var index = 0; index < sizeOfArray; index++) {
  var set = false;

  // Check set of new point value
  if (-1 === elIndex && arrayItems[index] > maxValue) {
    pointValue = arrayItems[index];
    elIndex = index;
    set = true;
  }

  // Update max value
  if (arrayItems[index] > maxValue) {
    maxValue = arrayItems[index];
  }

  // Reset point value
  if (!set && -1 !== elIndex && arrayItems[index] <= pointValue) {
    pointValue = maxValue;
    elIndex = -1;
  }

  console.log([arrayItems[index], maxValue, pointValue, elIndex, index]);
}

console.log(elIndex);

When to the loop ends you'll get the value in elIndex:

 arrayItems:  1  3  2  3  4  6  4  7  9  10   8
   maxValue:  1  3  3  3  4  6  6  7  9  10  10
 pointValue:  1  3  3  3  4  4  6  7  7   7   7
    elIndex: -1  1 -1 -1  4  4 -1  7  7   7   7
      index:  0  1  2  3  4  5  6  7  8   9  10


text: Q: Book about human-like aliens with power of teleportation who initiate a galactic war against deficient (aka normal) humankind Spacefaring humans meet a race that is almost identical physically. But the aliens have the ability to teleport themselves. The normal humans are judged deficient by the human race who can teleport and (for some reason) determine to control the mentally deficient humans. Technologically, they are about the same level so a war ensues. The humans are losing but also have several victories. I recall a chapter where a human boy on an occupied world ambushes and kills a patrolling soldier who relied on his teleportation capability too much. There is an attraction between a teleporting human and a captured non-teleporting human that help resolves the conflict. Seems to me they find a way to prove that the non teleporting humans teleport. They just never learned how. Maybe Van Vogt? I thought it might be a Philip High story but apparently not. Asimov? Brunner? Rackam? Was that 1960s era.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I connect this css3 webkit animation to an element when it is clicked? I know, a very simple question, but I don't know!
I have:
.touch img{
-webkit-transform: scale(2);
}

How would I make that activate when someone clicks on the element?
Thanks!

A: $(function() {
 $('#click').click(function() {
    $('.touch img').css({'-webkit-transform' : 'scale(2)'})
 });
});

This should work :)

A: Make it:
.touch img.clicked

And use the script:
$(".touch img").click(function(){this.addClass("clicked")});

A: active is the psuedo class you're looking for.
.touch img:active{
    -webkit-transform: scale(2);
}


text:
Q: Django - How to SUM the related Model field with Filter in Annotate? I've been facing this issue. I have 2 models with relationship like below, I tried to Sum all the PRICE of each author with filter: sale_type=sl01 and I was stuck all day.
Can someone point the right way for it to solve it,
many thanks in advance,
from django.db.models import Q, Subquery, OuterRef

    SALE_CHOICES = (
        ("sl01", "sl01"),
        ("sl02", "sl02")
    )

    class Author(models.Model):
        created = models.DateTimeField(auto_now_add=True)
        name = models.CharField(max_length=50, default='', null=True)
        password = models.CharField(max_length=20, default='', null=True)
        phone = models.CharField(max_length=15, default='', null=True)
        address = models.CharField(max_length=100, default='', null=True)

    class Sale(models.Model):
        created = models.DateTimeField(auto_now_add=True)
        author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True)
        price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
        sale_type = models.CharField(choices=SALE_CHOICES, default='sl01', max_length=10)

    data = Author.objects.annotate(total_amount=Subquery(Sale.objects.filter(author=OuterRef('author'), sale_type='sl01').aggregate(total_amount=Sum('price'))['total_amount']))

A: You can pass a filter keyword argument to aggregation functions to filter on the aggregations. See Filtering on annotations [Django docs]
from django.db.models import Q, Sum

data = Author.objects.annotate(total_amount=Sum('sale__price', filter=Q(sale__sale_type='sl01')))


text:
Q: Background image isn't showing up? Okay, so I've linked an image to a div section for a website. However, the image will not show up once uploaded to the server. I've double checked my CSS file, and nothing seems amiss, but perhaps I'm missing something.
CSS:
div{
    background-image: url(/images/medical-marijuana-background.jpg);
    background-repeat: space;
    border: solid #0D8200 .15em;
}

HTML:

 About this website

This page is dedicated to educating those who are interested in the medical benefits of marijuana as a medical option, and also to refute some of the misinformation about cannabis. As a  medical option, or even in general terms, cannabis is drastically under-researched. In fact in July of 2015 eight senators not only indicated that there is a lack of research on marijuana as a medical option, but also asked the Obama administration what is being done to further advance the reasearch.( Medical marijuana research , 2015) Ultimately, the purpose of this site is to not just educate, but also raise awareness. Raise awareness of the benefits of cannabis, raise awareness of the need to conduct more research/studies on cannabis as a medical option, and also give some history about cannabis.

Any ideas guys?

A: First off your CSS does not match your HTML. In your HTML you set div id="about". so to call it in your CSS you have to write #about instead of "div", like so:
#about {
background-image: url(/images/medical-marijuana-background.jpg);
background-repeat: space;
border: solid #0D8200 .15em;
}

Second, you are calling your image improperly. if your .html file is in the same directory as your image, you call the image like so:
url(input.jpg)

If the image is in a subfolder called images one level below your .html, then you call it like this:
url(images/input.jpg)

Finally if your image is actually one level ABOVE your .html, and in a subfolder called images, you would call it like this:
url(../images/input.jpg)

Hope this helps!

A: You need to add a width and a height of the background image for it to display properly.
div{
    background-image: url(images/medical-marijuana-background.jpg);
     width:xxpx;
     height:xxpx;
    border: solid #0D8200 .15em;
}

If you want to repeat
div{
    background-image: url(images/medical-marijuana-background.jpg);
    background-repeat: repeat-y; /* for vertical repeat */
    background-repeat: repeat-x; /* for horizontal repeat */
    height:xxpx;
    border: solid #0D8200 .15em;
}

A: You need to make use of :before or :after selector in css.
 div
{
  border: solid #0D8200 .15em;
  height: 150px;
  width: 350px;
}

div:before{
    content:url(http://placehold.it/350x150);
    background-repeat: space;
}

example : http://jsfiddle.net/mo7c1swt/3/

A: You're missing "" on arg -  should be background-image: url("paper.gif");


text:
Q: Choose between two templates render with Marionette I use Marionette (Backbone.js) on my Rails app.
What i want to do is load another template if matches an id, this is what i have
join_room.html.slim file
...
MyAppManager.start({
      tmpltRoute: templateRoute
});
...

menu_view.js.coffee
@MyAppManager.module "Layout", (Layout, MyAppManager, Backbone, Marionette, $, _) ->
  Layout.MenuView = Marionette.ItemView.extend
    initialize: (options)->
      @isPremium = options.isPremium
      @isStandard = options.isStandard
      @tmpltRoute = options.tmpltRoute
    template: JST[this.tmpltRoute]

A: You can override getTemplate on your ItemView to achieve this (see docs)
https://marionettejs.com/docs/v2.4.0/marionette.view.html#change-which-template-is-rendered-for-a-view
getTemplate: function(){
    if (this.model.get("foo")){
      return JST[foo];
    } else {
      return JST[bar];
    }
}

A: Layout.MenuView = Marionette.ItemView.extend
    template: JST["marionette/app/templates/layout-menu"]
    getTemplate: ->
      if this.isCase
        return JST["marionette/app/templates/layout-menu-case"]
      else
        return JST["marionette/app/templates/layout-menu"]


text:
Q: How do I pass variables from a postgresql script to an external script How do I pass variables from as postgresql script to an external script in a right way? It seems, that the variable interpolation will work well, if I use \echo '...', but not with \echo `...` and \!. Here example code lines:
-- set the variables
\set DB_SCHEMA     GT1
\set GEO_VAR_EPSG  '32632'
\set GEO_VAR_TMAX  '250'
-- :DBNAME is a local psql variable
-- print via echo '...'
\echo 'CALL mk-exp-position.pl' :DBNAME :GEO_VAR_TMAX :GEO_VAR_EPSG :DB_SCHEMA.exp_position :DB_SCHEMA.exp_transect
-- try to call some external stuff via \echo `...`
\echo `./mk-exp-position.pl :DBNAME :GEO_VAR_TMAX :GEO_VAR_EPSG :DB_SCHEMA.exp_position :DB_SCHEMA.exp_transect`
-- try to call external script via \! ...
\! ./mk-exp-position.pl :DBNAME :GEO_VAR_TMAX :GEO_VAR_EPSG :DB_SCHEMA.exp_position :DB_SCHEMA.exp_transect

The perl scriptlet that reads the params from the command line to some variables and print them:
#!/usr/bin/perl -w
use warnings;
use strict;
use DBI;

# check parameter count, give help and die
if ( $#ARGV < 4) {
 die " USAGE: $0 DB_NAME MAX_DIST EPSG SRC_TAB DST_TAB\n"
}

# read assign the command line parameter array to some variables
my ($DB_NAME, $MAX_DIST, $EPSG, $TAB_IN, $TAB_OUT) = @ARGV;

# print the variables to the stdout
print "#FILL.TABLE $TAB_OUT FROM $TAB_IN IN $DB_NAME PARAM MAX_DIST=$MAX_DIST EPSG=$EPSG\n";

And the result \echo 'CALL...':
CALL mk-exp-position.pl daisi_2017_06_06 250 32632 GT1.exp_position GT1.exp_transect

And the result \echo `...` or \! ... :
#FILL.TABLE :DB_SCHEMA.exp_transect FROM :DB_SCHEMA.exp_position IN :DBNAME PARAM MAX_DIST=:GEO_VAR_CMAX EPSG=:GEO_VAR_EPSG

Regards


text:
Q: Insert list of attributes into list of objects in python How do I insert a list (or numpy array) containing attribute values into a list of objects (as shown below)?
class myClass(object):
    def __init__(self, attr):
        self.attr = attr
        self.other = None

objs = []
for i in range(10):
        objs.append(myClass(i))

attrs = [o.attr for o in objs]
print attrs
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[o.attr for o in objs] = range(10)
#SyntaxError: can't assign to list comprehension

This is the inverse problem to Extract list of attributes from list of objects in python.

A: I'd do something like this:
for i, o in enumerate(objs):
    o.attr = i

enumerate(objs) is sort of like zip(range(len(objs)), objs), so in case you actually want to take values from another sequence, you can:
for i, o in zip(sequence, objs):
    o.attr = i

For efficiency you might use itertools.izip there too.

A: You can also use obj.__setattr__() within a list comprehension:
[o.__setattr__('attr',v) for o,v in zip(objs,range(10)[::-1])]
print [o.attr for o in objs]
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


text:
Q: How to associate a app.manifest with a Windows Store 8.1 Project My Visual studio project only has only a Package.appxmanifest but I need to add  to the app.manifest.
It is straight forward to add the app manifest and this setting but how do you tell the app to use it?
In older projects you would go into project properties but this only lists the appxmanifest which is a different structure

A: Unfortunately, the Package.appxmanifest was the new implementation for the app manifest and adding the old manifest file will have no impact on the application.


text:
Q: DAML bug when following the tutorial I followed the DAML tutorial, and it seems that there is a bug:
https://docs.daml.com/getting-started/quickstart.html#try-out-the-application

Try creating a contract from a template. Issue an Iou to yourself by
  clicking on the Iou:Iou row, filling it out as shown below and
  clicking Submit.
  http://localhost:4000/templates/Iou:Iou@f7592b50015725110188fe00bea8373fdcdceaeea90a1664682df422a9853b6e/

After filling out the form and clicking Submit, I get this error:

Error: Network error: Network request failed with status 500 -
  "Internal Server Error"


text:
Q: How to use WHERE clauses for a complex JOIN query I'm trying to make my data set smaller, where I'm currently bringing in data from 8 different tables. In order to do this, I'd like to use the WHERE clause to filter out unnecessary data, but I'm not sure how to do that for all 8 tables. This is my current query:
--GroupA first, to join the hits and sessions tables
SELECT
GroupA_hits.session_id, GroupA_hits.hits_eventInfo_eventCategory, GroupA_hits.hits_eventInfo_eventAction, GroupA_hits.hits_eventInfo_eventLabel, GroupA_hits.cd126_hit_placeholder,
GroupA_sessions.session_id, GroupA_sessions.userId, GroupA_sessions.fullVisitorId, GroupA_sessions.visitNumber, GroupA_sessions.date,
GroupB_hits.session_id, GroupB_hits.hits_eventInfo_eventCategory, GroupB_hits.hits_eventInfo_eventAction, GroupB_hits.hits_eventInfo_eventLabel, GroupB_hits.cd126_hit_placeholder,
GroupB_sessions.session_id, GroupB_sessions.userId, GroupB_sessions.fullVisitorId, GroupB_sessions.visitNumber, GroupB_sessions.date,
GroupC_hits.session_id, GroupC_hits.hits_eventInfo_eventCategory, GroupC_hits.hits_eventInfo_eventAction, GroupC_hits.hits_eventInfo_eventLabel, GroupC_hits.cd126_hit_placeholder,
GroupC_sessions.session_id, GroupC_sessions.userId, GroupC_sessions.fullVisitorId, GroupC_sessions.visitNumber, GroupC_sessions.date,
GroupD_hits.session_id, GroupD_hits.hits_eventInfo_eventCategory, GroupD_hits.hits_eventInfo_eventAction, GroupD_hits.hits_eventInfo_eventLabel, GroupD_hits.cd126_hit_placeholder,
GroupD_sessions.session_id, GroupD_sessions.userId, GroupD_sessions.fullVisitorId, GroupD_sessions.visitNumber, GroupD_sessions.date
FROM `GroupA-bigquery.170369603.ga_flat_hits_202104*` GroupA_hits
LEFT JOIN `GroupA-bigquery.170369603.ga_flat_sessions_202104*` GroupA_sessions
ON (
    GroupA_hits.session_id = GroupA_sessions.session_id
)
--Next, join GroupB to GroupA
LEFT JOIN `GroupB-bigquery.170359716.ga_flat_hits_202104*` GroupB_hits
ON (
    GroupB_hits.session_id = GroupA_hits.session_id
)
LEFT JOIN `GroupB-bigquery.170359716.ga_flat_sessions_202104*` GroupB_sessions
ON (
    GroupB_sessions.session_id = GroupA_sessions.session_id
)
--Now, join GroupC to GroupA
LEFT JOIN `GroupC-bigquery.170726426.ga_flat_hits_202104*` GroupC_hits
ON (
    GroupC_hits.session_id = GroupA_hits.session_id
)
LEFT JOIN `GroupC-bigquery.170726426.ga_flat_sessions_202104*` GroupC_sessions
ON (
    GroupC_sessions.session_id = GroupA_sessions.session_id
)
--Next, join GroupD to GroupA
LEFT JOIN `GroupD-bigquery.170374765.ga_flat_hits_202104*` GroupD_hits
ON (
    GroupD_hits.session_id = GroupA_hits.session_id
)
LEFT JOIN `GroupD-bigquery.170374765.ga_flat_sessions_202104*` GroupD_sessions
ON (
    GroupD_sessions.session_id = GroupA_sessions.session_id
)

I would like to also include the below clauses, these are all the same column names in the different _hits tables. This is what I've tried, but I get a "This query returned no results" back. I think it's because the way this query is written, BigQuery is looking for a row where all of these exist in one hit (is my assumption), which, there won't be any. But I'd like it to look through these four tables and grab all matching rows.
WHERE GroupA_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupB_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupC_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupD_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupA_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupB_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupC_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupD_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupA_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupB_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupC_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupD_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupA_hits.cd126_hit_placeholder Is Not NULL
AND GroupB_hits.cd126_hit_placeholder Is Not NULL
AND GroupC_hits.cd126_hit_placeholder Is Not NULL
AND GroupD_hits.cd126_hit_placeholder Is Not NULL

A: Consider moving the WHERE conditions into ON clauses to filter those tables during the LEFT JOIN operations:
...
FROM `GroupA-bigquery.170369603.ga_flat_hits_202104*` GroupA_hits
LEFT JOIN `GroupA-bigquery.170369603.ga_flat_sessions_202104*` GroupA_sessions
ON GroupA_hits.session_id = GroupA_sessions.session_id
AND GroupA_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupA_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupA_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupA_hits.cd126_hit_placeholder Is Not NULL

--Next, join GroupB to GroupA
LEFT JOIN `GroupB-bigquery.170359716.ga_flat_hits_202104*` GroupB_hits
ON GroupB_hits.session_id = GroupA_hits.session_id
AND GroupB_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupB_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupB_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupB_hits.cd126_hit_placeholder Is Not NULL

LEFT JOIN `GroupB-bigquery.170359716.ga_flat_sessions_202104*` GroupB_sessions
ON  GroupB_sessions.session_id = GroupA_sessions.session_id

--Now, join GroupC to GroupA
LEFT JOIN `GroupC-bigquery.170726426.ga_flat_hits_202104*` GroupC_hits
ON GroupC_hits.session_id = GroupA_hits.session_id
AND GroupC_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupC_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupC_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupC_hits.cd126_hit_placeholder Is Not NULL

LEFT JOIN `GroupC-bigquery.170726426.ga_flat_sessions_202104*` GroupC_sessions
ON GroupC_sessions.session_id = GroupA_sessions.session_id

--Next, join GroupD to GroupA
LEFT JOIN `GroupD-bigquery.170374765.ga_flat_hits_202104*` GroupD_hits
ON GroupD_hits.session_id = GroupA_hits.session_id
AND GroupD_hits.hits_eventInfo_eventCategory = 'rewards'
AND GroupD_hits.hits_eventInfo_eventAction = 'redeem points confirm'
AND GroupD_hits.hits_eventInfo_eventLabel = 'gas savings'
AND GroupD_hits.cd126_hit_placeholder Is Not NULL

LEFT JOIN `GroupD-bigquery.170374765.ga_flat_sessions_202104*` GroupD_sessions
ON GroupD_sessions.session_id = GroupA_sessions.session_id

A:
BigQuery is looking for a row where all of these exist in one hit (is my assumption), which, there won't be any.

Sounds like you want each option in an OR group, which could be further simplified like this:
WHERE
       'rewards' IN (GroupA_hits.hits_eventInfo_eventCategory, GroupB_hits.hits_eventInfo_eventCategory, GroupC_hits.hits_eventInfo_eventCategory, GroupD_hits.hits_eventInfo_eventCategory)
   AND 'redeem points confirm' IN (GroupA_hits.hits_eventInfo_eventAction, GroupB_hits.hits_eventInfo_eventAction, GroupC_hits.hits_eventInfo_eventAction, GroupD_hits.hits_eventInfo_eventAction)
   AND 'gas savings' IN (GroupA_hits.hits_eventInfo_eventLabel, GroupB_hits.hits_eventInfo_eventLabel, GroupC_hits.hits_eventInfo_eventLabel, GroupD_hits.hits_eventInfo_eventLabel)
   AND COALESCE(GroupA_hits.cd126_hit_placeholder, GroupB_hits.cd126_hit_placeholder, GroupC_hits.cd126_hit_placeholder, GroupD_hits.cd126_hit_placeholder) Is Not NULL

Note that I'm making some assumptions about how BigQuery handles ANSI standard SQL, as I'm not a regular BigQuery user.


text:
Q: syslog error, unknown priority name "" I am editing syslog and want to log ppp to a log. I added the last two lines to do so, as recommended in the ppp configuration. It appears to log ppp but also other things, due to the * I guess. I also get the error in the title. Any idea what the logging lines should be?
# /etc/syslog.conf - Configuration file for syslogd

auth,authpriv.*     /var/log/auth.log
*.*;auth,authpriv.none  /var/log/messages
user.*          /var/log/user.log
local0.*        /var/log/switch.log
local1.*        /var/log/audit.log
*.emerg         *
local0.*        /dev/ttyS0
!ppp
*.*             /var/log/switch.log

A: to make it short, syslog.conf is configured like this
 facility.priority /place/to/log

ppp's facility is daemon.
priority range from debug to panic.
your last line
 *.* /var/log/switch.log

will log any facility on any priority to switch.log. This likely result in a flood.
Try
  daemon.debug /var/log/daemon.log

note also that according to pppd(8) (man page for pppd), pppd can be told to log to specific file.
Edit:

*

*you have to guess what is the facility, I did it more or less for HPUX logging ftp connection .

*two or more programs can share the same facility, some post processing (e.g. grep ppp) on log file is required.

A: I was getting this error when using logger command from bash and incorrectly using the '-p' flag. See its man page under 'FACILITIES AND LEVELS' for all allowed values.  My working command looks like:
logger -p cron.info -t "($0)[$$]" "I'm going to the cron log."


text:
Q: Timer, TimerTask and battery consumption Assume there is a large set of reminders, and every reminder stores time when it should go off in long format.
What is more efficient from power consumption point of view:

*

*Create TimerTask for every reminder, even there are many reminders, and put these TimerTask instances to the Timer process to control when they should go off.

*Have one scheduled TimerTask process that runs every minute over this list of reminders and compares current time in milliseconds with the reminder's time in long format. And when it is necessary, it shows alarm according to the reminder.
At the first glance, the second approach should consume more power and drain the battery much more faster.
Am I right, or making many (100, 200, or even more) TimerTask instances and putting them to Timer via schedule or other relevant method will drain the battery faster?

A: You can use the AlarmManager class. It much better way than others.
Read the official document regarding AlarmManager here


text:
Q: C# get text from file between two hashes In my C# program (at this point) I have two fields in my form. One is a word list using a listbox; the other is a textbox. I have been able to successfully load a large word list into the listbox from a text file. I can also display the selected item in the listbox into the textbox this way:
private void wordList_SelectedIndexChanged(object sender, EventArgs e)
     {
          string word = wordList.Text;
          concordanceDisplay.Text = word;
     }

I have another local file I need to get at to display some of its contents in the textbox. In this file each headword (as in a dictionary) is preceded by a #. So, I would like to take the variable 'word' and search in this local file to put the entries into the textbox, like so:

#headword1
    entry is here...
    ...
    ...
#headword2
    entry is here...
    ...
    ...
#headword3
    entry is here...
    ...
    ...

You get the format of the text file. I just need to search for the correct headword with # before that word, and copy all info from there until the next hash in the file, and place it in the text box.
Obviously, I am a newbie, so be gentle. Thanks much.
P.S. I used StreamReader to get at the word list and display it in the listbox like so:
StreamReader sr = new StreamReader("C:\\...\\list-final.txt");
       string line;
       while ((line = sr.ReadLine()) != null)
       {
           MyList.Add(line);
       }
       wordList.DataSource = MyList;

A: var sectionLines = File.ReadAllLines(fileName) // shortcut to read all lines from file
    .SkipWhile(l => l != "#headword2") // skip everything before the heading you want
    .Skip(1) // skip the heading itself
    .TakeWhile(l => !l.StartsWith("#")) // grab stuff until the next heading or the end
    .ToList(); // optional convert to list

A: string getSection(string sectionName)
{
    StreamReader sr = new StreamReader(@"C:\Path\To\file.txt");
    string line;
    var MyList = new List<string>();
    bool inCorrectSection = false;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.StartsWith("#"))
        {
            if (inCorrectSection)
                break;
            else
                inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"($| -)");
        }
        else if (inCorrectSection)
            MyList.Add(line);
    }
    return string.Join(Environment.NewLine, MyList);
}

// in another method
textBox.Text = getSection("headword1");

Here are a few alternate ways to check if the section matches, in rough order of how accurate they are in detecting the right section name:
// if the separator after the section name is always " -", this is the best way I've thought of, since it will work regardless of what's in the sectionName
inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"($| -)");
// as long as the section name can't contain # or spaces, this will work
inCorrectSection = line.Split('#', ' ')[1] == sectionName;
// as long as only alphanumeric characters can ever make up the section name, this is good
inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"\b");
// the problem with this is that if you are searching for "head", it will find "headOther" and think it's a match
inCorrectSection = line.StartsWith("#" + sectionName);


text:
Q: Make required validation conditional in Rails 3 How can I do a required validation a given field based on the value of another completely different field?

A: Try
attr_accessible :supplier_id, :supplier_type

validates :supplier_type, :presence  => true,
    :if => lambda{ check_supplier_exists }

def check_supplier_exists
  @supplier = Supplier.find(self.supplier_id)
  if @supplier != nil
    return true
  else
    return false
  end
end

A: Check the unless conditions on validations.
Here you have an example:
class Person < ActiveRecord::Base

  validates :post_code, :presence => true, :unless => :no_postcodes?

  def no_postcodes?
    ['TW'].include?(country_iso)
  end

end


text:
Q: Find the formula for $1 + 4 + 7 +\ldots+ (3n - 2)$ and verify the formula by induction I wrote it as the following sum:
$$1 + \sum_{k=1}^n (3k - 2)$$
Which I solved for and got the following formula:
$$\frac{3n^2 - n + 2}2$$
But this seems wrong to me because the base case seems incorrect to me. Any help with this?

A: The sum should be $\sum_{k=1}^n (3k-2)$.
Using the arithmetic series formula, we have
$$\sum_{k=1}^n (3k-2)=\frac{n}{2}(3n-1)$$
Try to prove it using induction.

A: The numbers $1,\,4,\,7,\,\ldots,\,(3n-2)$ form an arithmetic progression. The  first term is $a_1=1$, and the $n$-th term is $3n-2$, so their sum, $S$, is given by
$$S=\frac{n\left[1+(3n-2)\right]}2=\frac{n(3n-1)}{2}$$


text:
Q: Pass data to django view with ajax I am very new to django and the whole world of jquery, ajax, etc.
I am having a page that when a function (javascript, jquery) function is run, I use the POST method to pass some data to my django view.
My jquery function is:
    function handleClick(e) {
        var myDataVariable = Variable
        var url = window.location.href
        var obj = {'Cellid': myDataVariable }
        $.ajax(
            {type:'POST',
             url: url,
             data: JSON.stringify(obj),
             contentType: 'application/json; charset=utf-8',
             success: function (data) {}
          });
    }

and in my django views I have:
    def Main(request):

        if request.method == 'POST':
            params = json.loads(request.body)
            Cellid = params['Cellid']
            CellData = cellData.cell_Data(int(Cellid))
        else:
            CellData =[]

        context = {
            'CellData':CellData,
        }

        return render(request, 'Main/Main.html', context)

Although the page works fine, when the function is called I am getting an error:
Forbidden (CSRF token missing or incorrect.): /Main/Main
Can someone please help me with this error? It is probably something simple but as I said I am very new to this and it is killing me! I would really appreciate a simple and easy to understand explanation.
Many thanks!

A: You must first extract your django CSRF token into jquery using this function:
// using jQuery to define CSRF token
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

Then you can pass the csrftoken variable into your ajax request headers like so:
$.ajax({
        url: url,
        method: "POST",
        data: {
          data
        },
        headers: { "X-CSRFToken": csrftoken }.....

For some context on CSRF tokens: they are basically security tokens which are passed between POST api calls in your application which demonstrate that the request is being made from within the app and not from a potentially malicious third party
Hope this helps


text:
Q: Why does Jest needs Babel to test async code? The Jest "An Async Example" guide starts with:

First, enable Babel support in Jest...

But I miss to see why and where does Jest needs Babel for.

A: Node.js has supported async functions by default since version 7.6.0, so (as you suspected) Babel is not needed for Jest to run tests using async functions.
I just confirmed this by installing only Jest v24.6.0 and ran this test with Node.js v10.15.1:
test('hi', async () => {
  const val = await Promise.resolve('hello');
  expect(val).toBe('hello');
});

...and it passed just fine.

On the other hand, Babel is required to use ES6 module syntax.
Many of the examples in the "An Async Example" doc use ES6 module syntax (export default ..., import * as ..., etc.) so Babel is required for any of those examples to work.


text:
Q: Accessing Data Controls from a different form i have two forms, form A and form B, to access form B from from A i pass form B in the constructor of form A, that way i am able to access a gridview.
Suggestions were made directing me towards exposing my gridview in a public property and passing it to the other form i want to access it from.
This is my understanding of what was suggested to me:
public RadGridView Grid
{
    get { return GridViewDisplay; }
}

then i pass this property to my second form:
Form1 f1 = new form1();
Form2 f2 = new form2(f1.Grid);

This is my issue here:
public void DockAllWindows()
    {
        SideBar sb = new SideBar();
        Summary sm = new Summary();
        SalesPoint sp = new SalesPoint(sb, sm); // This is where my issue is, Point A
        StartPage start = new StartPage();
        radDock.DockControl(sp, (DockPosition.Fill), DockType.Document);
        radDock.DockControl(start, (DockPosition.Fill), DockType.Document);
        radDock.DockControl(sm, (DockPosition.Right), DockType.ToolWindow);
    }

At Point A i am passing an object instance of my summary form to my SalePoint form.
therefore i cannot execute the following code as it would generate an error:
Summary sm = new Summary(sp.Grid); // Error right here
            SalesPoint sp = new SalesPoint(sb, sm);

I would like some help getting around the above error.

A: You need to set the Summary.Grid property after you've created your SalesPoint class.
Summary sm = new Summary();
SalesPoint sp = new SalesPoint(sb, sm);
sm.Grid = sp.Grid.

To be clear you need a public grid property on your SalesPoint class and one on your Summary class. And make you implement the set on the property of the Summary class so you know when someone else changes it.
public RadGridView Grid
{
    get { return grid; }
    set
    {
        if (grid != value)
        {
            grid = value;
            // Add any special processing that summary needs to do to pull data from the SalesPoint Grid property.
        }
    }
}


text:
Q: Using geom_function in ggplot2 to call a function written in postgreSQL plr I struggle to call a plr function in postgreSQL from a R-script and use it in ggplot2 - geom_function. The following examples are extremly simplified but hopefully show the issue.
Let's assume I have the following plr function:
CREATE OR REPLACE FUNCTION public.mypgfunc(
    x numeric,
    a numeric)
    RETURNS numeric
    LANGUAGE 'plr'
    COST 100
    VOLATILE PARALLEL UNSAFE
AS $BODY$
    return (x*a)
$BODY$;

To call this from ggplot - geom_function I thought, I could write the following simple wrapper function to do the query (I use the rpostgres package):
myWrapper <- function(x , a) {
  con <- dbConnect(drv = RPostgres::Postgres() , dbname='mydb')

  q <- dbSendQuery(con , "select mypgfunc( $1 , $2 )")
  dbBind(q , c(x,a))
  y <- dbFetch(q)
  dbClearResult(q)

  dbDisconnect(con)

  return(y)
}

But if I now call this function from ggplot, I get the following warning message and an empty plot:

Computation failed in stat_function():
Query requires 2 params; 102 supplied.

The ggplot code looks as follows:
ggplot() +
  geom_function(fun = myWrapper , args = list(a = 5))

If I write the plr function in R instead and call this from geom_function, everything works fine.
If I call the myWrapper directly (outside ggplot) with just one value for x and a, respectively, everything works fine as well.
So, what do I have to change?

A: I don't now much about using SQL databases in R. But I think I know the reason of your error.
If you look at the help page for stat_function (which is what geom_function uses under the hood), you will see that, by default, it creates 101 values of x over an arbitrary range (I think it is [0,1]).
This is why the error message mentions that "Query requires 2 params; 102 supplied". You are concatenating x (which is a vector of length 101) with a (length 1), when you call dbBind(q , c(x,a)).
The size of x is defined by the parameter n. So if you run:
ggplot() + geom_function(fun = myWrapper , args = list(a = 5), n=1)

You are passing a single value of x to myWrapper(I think x=0) and you should get the same result as the situation you described in the last sentence (I got a warning message because ggplot could not draw a line with only 1 point).
So, basically, you need to do separate queries for each value of the vector x. A straight forward way of doing this is looping over the values of x:
y <- NULL
for (xx in x) {
    q <- dbSendQuery(con , "select mypgfunc( $1 , $2 )")
    dbBind(q , c(xx, a))
    if (is.null(y)) {
        y <- dbFetch(q)
    } else {
        y <- rbind(y, dbFetch(q))
    }
    dbClearResult(q)
}

Like I said, I have not worked with SQL in R. So I am sure there are smarter ways of doing this where you don't need to call an ugly for loop (not sure also if you need the dbSendQuery inside the loop).

A: I did some more research and found another solution which avoids a for-loop.
I just had to change the myWrapper function into the following code:
myWrapper <- function(x , a) {
  con <- dbConnect(drv = RPostgres::Postgres() , dbname='mydb')

  a <- rep(a , length(x))
  q <- dbSendQuery(con , "select mypgfunc( $1::numeric , $2::numeric )")
  dbBind(q , list(x,a))
  y <- dbFetch(q)
  dbClearResult(q)

  dbDisconnect(con)

  return(y[,1])
}


text:
Q: Javascript Function Still Not Working.. Tests and Failed The first javascript function switchText() works fine and swap the texts as desired, but the second javascript function switchTextx() does not work at all except for the alert() function.
The second function looks identical to the working function switchText(). I've ensure there is no tag conflict but still now working.
What is the root of the problem and how can i get the second function switchTextx() to work?

    <title>
        ...Test
    </title>

    <button id = "buttonc" type="button" value="swap text" onclick="swithText()" >Toggle Text</button>

    <button id = "buttoncx" type="button" value="swap text" onclick="swithTextx()" >Toggle Text</button>

A: Your issue is with toggleButtonr.toggleStatusr = "on"; near the start of your switchTextx() function. You need to change it to contentSampler.toggleStatusr = "on"; to allow your switch statment to get activated initially.
See working example below:

function swithText() {
  alert('function running');

  var theTogglex = document.getElementById("buttonc");
  var toggleMex = document.getElementById("sample");
  toggleMex.toggleStatusx = "on";

  theTogglex.onclick = function() {
    switch (toggleMex.toggleStatusx) {
      case "on":
        toggleMex.toggleStatusx = "off";
        toggleMex.textContent = "I CHANGED MY CLOTHES ONE TIME";
        break;
      case "off":
        toggleMex.toggleStatusx = "on";
        toggleMex.textContent = "2ND CHANGE TODAY!";
    }
  }
}

function swithTextx() {
  alert("function running");
  var toggleButtonr = document.getElementById("buttoncx");
  var contentSampler = document.getElementById("samplex");
  contentSampler.toggleStatusr = "on";

  toggleButtonr.onclick = function() {
    switch (contentSampler.toggleStatusr) {
      case "on":
        contentSampler.toggleStatusr = "off";
        contentSampler.textContent = "I CHANGED MY CLOTHES ONE TIME";

        break;

      case "off":
        contentSampler.toggleStatusr = "on";
        contentSampler.textContent = "2ND CHANGE TODAY!";

    }
  }
}

  <title>
    ...Test
  </title>

  <button id="buttonc" type="button" value="swap text" onclick="swithText()">Toggle Text</button>

  <button id="buttoncx" type="button" value="swap text" onclick="swithTextx()">Toggle Text</button>


text:
Q: Kendo UI Grid from Html table - change event will not fire I have a Kendo UI grid, where the dataSource is an html table.
I am trying to fire the change: event, but it will not fire.
Here's a simple fiddle
It's based on this
And the change event here
I bind to the #grid as follows :
$("#grid").kendoGrid({
  dataSource: {
    data: products,
    schema: {
      model: {
        fields: {
          ProductName: { type: "string" },
          UnitPrice: { type: "number" },
          UnitsInStock: { type: "number" },
          Discontinued: { type: "boolean" }
        }
      }
    },
    pageSize: 20
  },
  height: 550,
  scrollable: true,
  sortable: true,
  filterable: true,
  pageable: {
    input: true,
    numeric: false
  },
  columns: [
    "ProductName",
    { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px"  },
    { field: "UnitsInStock", title: "Units In Stock", width: "130px" },
    { field: "Discontinued", width: "130px" }
  ]
});

var grid = $("#grid").data('kendoGrid');
grid.bind("change", function (e) {
    alert('CHANGE EVENT...')
});

Perhaps it's not possible where the DataSource is an Html table. I'm not certain of this.

Thank you in advance...
Bob

A: The problem ain't the change event...  the problem is that the grid didn't receive any selectable value.  Without this configuration value, the user won't be able to select any cell (or row), even if the change event was registered correctly.
Here's your updated code:
$("#grid").kendoGrid({
  dataSource: {
    data: products,
    schema: {
      model: {
        fields: {
          ProductName: { type: "string" },
          UnitPrice: { type: "number" },
          UnitsInStock: { type: "number" },
          Discontinued: { type: "boolean" }
        }
      }
    },
    pageSize: 20
  },
  height: 550,
  scrollable: true,
  sortable: true,
  filterable: true,
  selectable: "multiple cell",  //<--- Just add this line
  pageable: {
    input: true,
    numeric: false
  },
  columns: [
    "ProductName",
    { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px"  },
    { field: "UnitsInStock", title: "Units In Stock", width: "130px" },
    { field: "Discontinued", width: "130px" }
  ]
});

var grid = $("#grid").data('kendoGrid');
grid.bind("change", function (e) {
    alert('CHANGE EVENT...')
});

You can also try it in this jsfiddle example.
Here's a link to the selectable documentation.


text:
Q: Java handler error I am getting errors and i don't know why.
//skip 26-48
public void skip1() {
    session.setAttribute("baseline_du_26_years","-9");
    session.setAttribute("baseline_du_26_0","-9");
}

Here is where its being called
else if (session.getAttribute("baseline_du_25_1").equals("1")) {
    skip1();
    to="baseline_du_49.jsp";

I get back these
Syntax error on token(s), misplaced construct(s)
Syntax error on token "void", @ expected

Also on the call of the function I get these
The method skip1() is undefined for the type handler_jsp

What is wrong with this?
This is the primary issue
public void skip1() {

EDIT ~~~~~
this worked
public void skip1(HttpSession session){
// code here
}

skip1(session);

A: As far as this error is concern

The method skip1() is undefined for the type handler_jsp

It seems you have not defined skip1() in your JSP. You can declare using scriptlet.
<% !
 public void skip1(HttpSession session) {
       session.setAttribute("baseline_du_26_years","-9");
       session.setAttribute("baseline_du_26_0","-9");
}
%>

Make sure you have the session variable passed to the method skip1().


text:
Q: ClickOnce app installation and usage error I wrote ClickOnce application (WpfApplication) using Visual Studio 2012.
When I publish it (to removeable) and install on my computer it's working fine.
But when I try it on other computer, I get the following error:
PLATFORM VERSION INFO
    Windows             : 6.1.7600.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.17929
    System.Deployment.dll       : 4.0.30319.17929 built by: FX45RTMREL
    clr.dll             : 4.0.30319.17929 built by: FX45RTMREL
    dfdll.dll           : 4.0.30319.17929 built by: FX45RTMREL
    dfshim.dll          : 4.0.41209.0 (Main.041209-0000)

SOURCES
    Deployment url          : file:///D:/user/Downloads/WpfApplication.application

IDENTITIES
    Deployment Identity     : WpfApplication.application, Version=1.0.0.5, Culture=neutral, PublicKeyToken=e7100e24044f1f15, processorArchitecture=msil

APPLICATION SUMMARY
    * Installable application.

ERROR SUMMARY
    Below is a summary of he errors, details of these errors are listed later in the log.
    * Activation of D:\user\Downloads\WpfApplication.application resulted in exception. Following failure messages were detected:
        + Deployment and application do not have matching security zones.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [04/10/2014 10:39:05] : Activation of D:\user\Downloads\WpfApplication.application has started.
    * [04/10/2014 10:39:05] : Processing of deployment manifest has successfully completed.
    * [04/10/2014 10:39:05] : Installation of the application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [04/10/2014 10:39:05] System.Deployment.Application.InvalidDeploymentException (Zone)
        - Deployment and application do not have matching security zones.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, IDownloadNotification notification, DownloadOptions options, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

Before publishing, I made sure that my project is:

*

*a full trust application.

*aviliable offline as well

*signed my app using test certification

What am I missing here?

A: *

*Make sure to at least sign your application by test certification.

*If any antivirus program is installed, disable it

*If you are directly    install from an url, use Internet Explorer


text:
Q: can a conjunction be positively relevant to an event, if that event is independent of the two conjuncts taken separately. I'm wondering whether if we take an event $A$ that is probabilistically independent of two further events $B$ and $C$, the conjunction $B∩C$ could ever be positively relevant to $A$. I think this is equivalent to asking if the following conditions can be satisfied:
$P(A|B)=P(A)$
$P(A|C)=P(A)$
$P(A|B∩C)>P(A|B)$
I've wrestled with it for a good while, and I can't seem to show either that these conditions can be satisfied or that they can't.

A: Consider flipping a coin twice.
Let $A$ be the event that the second coin flip has the same result as the first.
Let $B$ be the event that the first coin flip is heads
Let $C$ be the event that the second coin flip is heads
Then $P(A|B)=P(A|C)=P(A)=\frac{1}{2}$
But $P(A|B \cap C) =1$


text:
Q: grabbing value from an html input I am trying to grab the value from an html input, and I am having trouble getting it to work, from what I was looking at doing my own research, it looks like I have the correct syntax? So I am confused.
when I console log the value, it looks like its not actually getting the value of the input.
let btn = document.getElementById("btn");
let grade = document.getElementById("gradeNum").value;

function getGrade() {
    console.log(grade);

    if (grade >= 90) {
        document.getElementById("gradeLetter").innerHTML = "You got an A!";
    } else if (grade < 90 && grade >= 80) {
        document.getElementById("gradeLetter").innerHTML = "You got a B!";
    } else if (grade < 80 && grade >= 70) {
        document.getElementById("gradeLetter").innerHTML = "You got a C!";
    } else if (grade < 70) {
        document.getElementById("gradeLetter").innerHTML = "You got an F! Study more!";
    }
};

A: Try this:
let btn = document.getElementById("btn");
// let grade = document.getElementById("gradeNum").value; <-- NOT HERE

function getGrade() {
  let grade = document.getElementById("gradeNum").value;   // BUT HERE
  console.log(grade);

  if (grade >= 90) {
    ...

A: A few things:
(1) If you're using typescript then HTMLElement (which is what document.getElementById returns) doesn't have the value property.
For that you'll need to cast to HTMLInputElement which has it:
let grade = (document.getElementById("gradeNum") as HTMLInputElement).value;

(2) The type of the value of this input element is a string, so grade is also a string, yet you treat it as a numer.
While "5" == 5 is true, "5" === 5 is false, so you might want to get the number value:
let grade = parseInt((document.getElementById("gradeNum") as HTMLInputElement).value);

(3) You set the value of grade as a global variable but it doesn't seem like you are reassigning it later on.
That is, when the page loads you're assigning it an empty string (as the user hasn't entered a value into the input box), and then when the getGrade function is invoked you don't check what is the current value.
It should be:
let grade: number;

function getGrade() {
    grade = parseInt((document.getElementById("gradeNum") as HTMLInputElement).value);

    console.log(grade);
    ...
}

A: The problem is here:
grade = document.getElementById("gradeNum").value;

This is on the second line, and evaluated whole before the user type an input.
Instead do it like:
grade = document.getElementById("gradeNum");

And later refer to grade like this:
if (grade.value >= 90)


text:
Q: Copy the output of `print` to clipboard directly I use inspect.getsource to check the libs I imported:
In[52]: from django.views.generic import View
In[53]: view_code = inspect.getsource(View)
In[54]: len(view_code)
Out[54]: 3242

Retrieve the formatted codes
In[55]: print(view_code)

class View(object):
    """
    Intentionally simple parent class for all views. Only implements
    dispatch-by-method and simple sanity checking.
    """

    http_method_names = ['get', 'post', 'put',
                        'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):

I'd like to store the codes to my notes for further reference,
to do this, I have to scroll through the entire code with the purpose to copy it.
It's not convenient if the codes are long enough.
How could I copy the output of print to clipboard in a straight-forward way?

A: Python doesn't have clipboard APIs built in, except as part of the tkinter GUI, but there are a number of libraries on PyPI that do.
For example, with pyperclip, you can copy any string you want to the clipboard like this:
In[56]: import pyperclip
In[57]: pyperclip.copy(view_code)

But you may be able to use tkinter. Depending on your platform, whether you're using a console-mode or qtconsole session, etc., this may not work, or may require popping up an unwanted window, but you can try it and see:
In [119]: import tkinter
In [120]: tk = tkinter.Tk()
In [121]: tk.clipboard_clear()
In [122]: tk.clipboard_append(view_code)

If your setup does require you to display a window (e.g., I think this will happen in a console-mode session on Windows), you might still be able to do it without too much distraction. See this answer, suggested by J.Doe if you're interested.

But it might be simpler and more useful to just write to a file:
In[58}: with open('spam.txt', 'w') as f: f.write(view_code)

Or, since you're using IPython, you can use %save or various other magic commands. (See this question so I don't have to go over them all here.)

Or, there are multiple third-party implementations of IPython addons to give you clipboard copy commands, like this one (which I just found in a random search, so I'm not endorsing it or anything… but it seems to work):
In[61]: %clip view_code

If you actually need to capture the output of print for some reason, the two obvious ways to do it are to monkeypatch or shadow print, or to patch sys.stdout. For example:
import builtins
import io
import sys
def print(*args, **kw):
    if kw.get('file', sys.stdout) is sys.stdout:
        buf = io.StringIO()
        builtins.print(*args, **kw, file=buf)
        pyperclip.copy(buf.getvalue())
    builtins.print(*args, **kw)


text:
Q: Is it possible to insert a Google Apps Script array value into a Sheet cell as plain text? Put simply, I am working in Google Apps script, and I have an array value. I want to insert the array value into a sheet cell and the end result being the cell is set to plain text.
Everything about my code works, but this line refuses to result in a plain text output:
function minimal()
{
   const allFormResponses = fetchFormResponses();  //loads numbers from form output into a 2D array
   var sheet = SpreadsheetApp.getActive().getSheetByName("All");
   var lastRow = sheet.getLastRow()+1;
   for(var d = 0; d < allFormResponses.length; d++)
   {
      var lastRow = sheet.getLastRow()+1;
      for (var e = 0, col = 1; e < allFormResponses[d].length; e++, col++)
      {
         sheet.getRange(lastRow,col).setValue(JSON.stringify(allFormResponses[d][e].itemResponse.toString())).setNumberFormat("@");
      }
   }
}

I have also tried just formatting the entire column after each value is added and that doesn't work either.
Feeling stumped and I feel like it's probably something dumb I am missing.

A: Replace
sheet.getRange(lastRow,col).setValue(allFormResponses[d][e].itemResponse).setNumberFormat("@");

by
sheet.getRange(lastRow,col).setValue(`'${allFormResponses[d][e].itemResponse}`);

Related

*

*Format a Google Sheets cell in plaintext via Apps Script

*Google App scripts: Unable to preserve Leading zeros since it is automatically removed


text:
Q: Can you open programs to the notification tray (i.e. not maximised) and close programs through a batch file? I am running a Ninite.exe in my startup folder so that the programs I have that are on Ninite are kept up to date which seems to work really well. However, I am encountering two problems with this:
1) A while ago, Glary Utilities stopped updating because Ninte said the program was running. I've somewhat got around this by not having Glary launch at startup anymore, but instead launching through a batch file that has a delay at the start. So Ninite can update Glary before Glary launches. The problem with this, is that the Glary window shows up every time it launches. If I use the option within Glary itself to start on Windows startup,  it launches minimised to the notification tray. Is there any parameters I can use in my batch file to make sure that Glary launches minimised to the notification tray?
2) Following on from this, I would like to know if there are any parameters for closing a window? I would like to use this to close the Ninite window when it has finished updating my programs.
TL;DR Are there any parameters in batch files to only open a program minimised to the notification tray and/or close a window.

A: I once made a batch file to open steam games and I used start
:START_CHOICE
echo [1] PUBG
echo [2] EXIT
if %input%==1 goto CHOICE_1 if NOT goto START_CHOICE
if %input%==2 goto CHOICE_2 if NOT goto START_CHOICE
:CHOICE_1
:CONFIRM2
echo Enter COMPUTER PASSWORD
set input2=
set /p input2=
If /I "%input2%"=="4862" goto PLAY2
echo Invalid password.
echo --------------------------
goto CONFIRM2
:PLAY2
echo Proceeding to PUBG!
timeout /t 3 /nobreak
start steam://rungameid/578080
EXIT
:CHOICE_2
EXIT

You'll have to do start --YourFileNameOrShortcut-- Just don't use --
Also to minimize it use EXIT


text:
Q: Is it just me or does the back button in Google Chrome not always work? Its strange, but a lot of the time I find myself clicking the back button a few times before it seems to work.
Is this just me with this issue, or has anyone else experienced this with Chrome?

A: I had a click and drag issue the other day, my mouse was connected to a usb hub, I connected it directly to the PC and the problem was gone.

A: Figured it out. Sometimes when Chrome is loading a page, and only somtimes ALL buttons are unresponsive just for a sec, its during this time the back button won't work.
The only workaround I can think of is to get into the habit of waiting for ALL page content to load before you click the back button.


text:
Q: How to simulate ctrl-c in Windows cmd line? I want to interrupt (I do not want to kill it) a process through the use of the terminal. Currently, the only way I am able to stop the process is by physically tapping Ctrl+C. However, for the sake of the program I am building, I do not want to have to tap Ctrl+C. Is there a way to type a command that does the same thing as tapping Ctrl+C on the Windows command line? I need to be able to do this for my program I am using paramiko to send cmd commands, but I can't use ctrl+c in paramiko.
i.e. cmd ctrl-c interrupt_this_program

A: From the command line use command taskkill. Get help on this command by running in a command prompt window taskkill /?.
taskkill without usage of option /F sends to the specified process the event message to terminate, i.e. the WM_CLOSE message. If the application is coded to process this general Windows message, it should terminate itself as soon as possible with saving all not yet saved data.
taskkill with usage of option /F really kills the specified process (application) by the operating system without giving the running application the chance to terminate itself with saving all data. So option /F should be used only if the application does not respond on the terminate message because of not being coded to break its execution on receiving that message from operating system.


text:
Q: Call Code Behind method (function) in RowCreated Gridview's handler I want to call a Code Behind method inside a Gridview.
This is the Code Behind method that loops through every webcontrol that's in the form:
private void SetupJSdataChange(Control parentControl)
{
    foreach (Control control in parentControl.Controls)
    {
        //Response.Write(control.ID + "
");
        if (control is WebControl)
        {
            WebControl webControl = control as WebControl;
            webControl.Attributes.Add("onchange", "InputChanged(this)");
        }
    }
}

And I want it to loop through every webcontrol that's in a RowCreated gridview's handler instead. This is my try:
protected void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {

        foreach (Control control in parentControl.Controls)
        {
            //Response.Write(control.ID + "
");
            if (control is WebControl)
            {
                WebControl webControl = control as WebControl;
                webControl.Attributes.Add("onchange", "InputChanged(this)");
            }
        }

    }

}

But I get an error that says "the name 'parentControl' doesn't exist in the current context" and I don't know how to handle it.
And this is the Gridview:
        <asp:GridView ID="GVTrabajadores" runat="server"
            CssClass="table table-hover table-striped"
            ShowHeaderWhenEmpty = "true"
            GridLines="None"
            AutoGenerateColumns="False"
            ShowFooter="true"
            OnRowCreated="GVTrabajadores_RowCreated"
            OnRowCommand="GVTrabajadores_RowCommand">

            <Columns>
                <asp:TemplateField HeaderText="Nombre">
                    <ItemTemplate>
                        <asp:TextBox ID="TxNombre" runat="server" Text='<%#Eval("nombre") %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="TxNombref" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cerrada">
                    <ItemTemplate>
                        <asp:CheckBox ID="CBCerrada" runat="server" Checked='<%# (Eval("cerrada").ToString() == "1" ? true : false) %>' />
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:CheckBox ID="CBCerradaf" runat="server" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>

        </asp:GridView>

A: This should work for you. Note that I used generic event args - if you need them you'll need to change them.
private void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
    {
        GridView gV = sender as GridView;
        for(int i = 0; i < gV.Columns.Count; i++)
        {
          Control c = e.Row.Cells[i].Controls[0];
            string controlType = c.GetType().ToString().Replace("System.Web.UI.WebControls.", "");
            switch (controlType)
            {
                case "TextBox":
                    TextBox t = c as TextBox;
                    t.TextChanged += GVTrabajadores_TextBox_TextChanged;
                    t.AutoPostBack = true;
                    break;
                case "CheckBox":
                    CheckBox cB = c as CheckBox;
                    cB.CheckedChanged += GVTrabajadores_CheckBox_Changed;
                    cB.AutoPostBack = true;
                    break;

            }
        }
    }
    private void GVTrabajadores_CheckBox_Changed(object sender, EventArgs e)
    {
        //process change
    }
    private void GVTrabajadores_TextBox_TextChanged(object sender, EventArgs e)
    {
        //process changed text
    }


text:
Q: not equal operation in joining of two tables I want to join two tables ,while joining two tables in that column ,sample query is
    from a in project_modules
   join b in module_functions on  a.project_module_id equals b.project_module_id

I want not equals operation inplace of equals

A: Taking literally what you ask would be:
from a in project_modules
from b in module_functions
where a.project_module_id != b.project_module_id

Note that it produces a cartesian product except the inner joined records. Well, maybe you need it for something.


text:
Q: What is the difference between the * and the & operators in c programming? I am just making sure I understand this concept correctly. With the * operator, I make a new variable, which is allocated a place in memory. So as to not unnecessarily duplicate variables and their values, the & operator is used in passing values to methods and such and it actually points to the original instance of the variable, as opposed to making new copies...Is that right? It is obviously a shallow understanding, but I just want to make sure I am not getting them mixed up. Thanks!

A: When a variable is paired with the * operator, that variable holds a memory address.
When it is paired with the & operator, it returns the address at which the variable is held.
If you had
int x = 5; //5 is located in memory at, for example, 0xbffff804
int *y = &x; //&x is the same thing as 0xbffff804, so y now points to that address

both x and *y would yield 5

A: Not quite. You're confusing a * appearing in a type-name (used to define a variable), with the * operator.
int main() {
    int i;    // i is an int
    int *p;   // this is a * in a type-name. It means p is a pointer-to-int
    p = &i;   // use & operator to get a pointer to i, assign that to p.
    *p = 3;   // use * operator to "dereference" p, meaning 3 is assigned to i.
}

A: One uses & to find the address of a variable. So if you have:
int x = 42;

and (for example) the computer has stored x at address location 5, &x would be 5. Likewise you can store that address in a variable called a pointer:
int* pointer_to_x = &x; // pointer_to_x has value 5

Once you have a pointer you can dereference it using the * operator to convert it back into the type to which it points:
int y = *pointer_to_x; // y is assigned the value found at address "pointer_to_x"
                       // which is the address of x. x has value 42, so y will be 42.


text:
Q: XML Descendants always return Empty result I don't know why I can't make this work in any case.
My code:
using System;
using System.Linq;
using System.Xml.Linq;

namespace XML_TESTER_CM
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            XDocument xDoc;
            xDoc = XDocument.Load("Palette_Sets.xml");

            var result1 = xDoc.Descendants("SETS");
            var result2 = xDoc.Descendants("PALETTE");
            var result3 = xDoc.Descendants("COLOR");
        }
    }
}

My XML file:
https://pastecode.xyz/view/25d53914
<?xml version="1.0" encoding="utf-8"?>

<SETS>
  <PALETTE id="Default Set">
    <COLOR>
      <Name>Red</Name>
      <RGBString>#FF0000</RGBString>
    </COLOR>
    <COLOR>
      <Name>Blue</Name>
      <RGBString>#0000FF</RGBString>
    </COLOR>
    <COLOR>
      <Name>Cyan</Name>
      <RGBString>#00FFFF</RGBString>
    </COLOR>
    <COLOR>
      <Name>Magenta</Name>
      <RGBString>#FF00FF</RGBString>
    </COLOR>
    <COLOR>
      <Name>Green</Name>
      <RGBString>#00FF00</RGBString>
    </COLOR>
    <COLOR>
      <Name>Orange</Name>
      <RGBString>#FFAA00</RGBString>
    </COLOR>
    <COLOR>
      <Name>Yellow</Name>
      <RGBString>#FFFF00</RGBString>
    </COLOR>
  </PALETTE>
  <PALETTE id="OLD Set">
    <COLOR>
      <Name>Olive</Name>
      <RGBString>#7f8229</RGBString>
    </COLOR>
    <COLOR>
      <Name>Dark Blue</Name>
      <RGBString>#272c72</RGBString>
    </COLOR>
    <COLOR>
      <Name>Silver</Name>
      <RGBString>#9597af</RGBString>
    </COLOR>
  </PALETTE>
</SETS>

xDoc returns the document correctly, but Descendants method doesn't work at all each resultX var has an empty result view.

A: I like using Dictionaries with xml.  Below I converted your xml into colors :
using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Drawing;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, Dictionary<string, PaletteColor>> dict = doc.Descendants("PALETTE")
                .GroupBy(x => (string)x.Attribute("id"), y => y.Elements("COLOR").Select(c => new PaletteColor() { name = (string)c.Element("Name"), color = Color.FromArgb(int.Parse(((string)c.Element("RGBString")).Substring(1), System.Globalization.NumberStyles.HexNumber)) })
                    .GroupBy(a => a.name, b => b)
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
    public class PaletteColor
    {
        public string name { get; set; }
        public Color color { get; set; }
    }
}

Here is answer using list instead of 2nd dictionary

using System;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Drawing;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, List<PaletteColor>> dict = doc.Descendants("PALETTE")
                .GroupBy(x => (string)x.Attribute("id"), y => y.Elements("COLOR").Select(c => new PaletteColor() { name = (string)c.Element("Name"), color = Color.FromArgb(int.Parse(((string)c.Element("RGBString")).Substring(1), System.Globalization.NumberStyles.HexNumber)) }).ToList())
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
    public class PaletteColor
    {
        public string name { get; set; }
        public Color color { get; set; }
    }
}


text:
Q: Can't display enough JLabels/TextFields properly I am trying to display roughly 7 or 8 multiple text fields and JLabels in a single frame. I am having trouble getting them all to show up. The only way I know to display the individual parts of the GUI is to create a JFrame, then create a container within that frame, then create multiple panels and add them to the container. Is there a better way to do this? One that isn't so restricting and allows me to display more than 4 frames? (I'm limited to only choosing NORTH, EAST, SOUTH, WEST and only one item will show up at those locations)

Here is my code:
Container content = n.getContentPane();
         Container contentTwo = n.getContentPane();

            JTextField JField = new JTextField(agentID);
            JTextField stateField = new JTextField("Running");
            JTextField transField = new JTextField(5);
            JTextField opsField  = new JTextField("0");
            stateField.setEnabled(false);
            transField.setEnabled(false);
            JField.setEnabled(false);
            opsField.setEnabled(false);
            JLabel stateLabel = new JLabel("State:");
            JLabel transLabel = new JLabel("Amount transferred:");
            JLabel opsLabel = new JLabel("Operations Completed:");
            JPanel fundsPanel = new JPanel(new BorderLayout());
            JLabel agentLabel = new JLabel("Agent ID: ");
            agentLabel.setDisplayedMnemonic(KeyEvent.VK_ENTER);
            stateLabel.setLabelFor(stateField);
            transLabel.setLabelFor(transField);
            agentLabel.setLabelFor(JField);
            opsLabel.setLabelFor(opsField);
            fundsPanel.add(agentLabel, BorderLayout.WEST);
            fundsPanel.add(JField, BorderLayout.CENTER);
            content.add(fundsPanel, BorderLayout.NORTH);

            JLabel accLabel = new JLabel("Amount in $: ");
            JPanel accPanel = new JPanel(new BorderLayout());
            JPanel accPanelTwo = new JPanel(new BorderLayout());
            JPanel accPanelThree = new JPanel(new BorderLayout());
            accLabel.setDisplayedMnemonic(KeyEvent.VK_ENTER);
            JFormattedTextField accTextField = new JFormattedTextField(amount);
            accTextField.setEnabled(false);
            JLabel opLabel = new JLabel("Operations per second:");
            opLabel.setDisplayedMnemonic(KeyEvent.VK_ENTER);
            JTextField accTextFieldTwo = new JTextField(Double.toString(opsPerSec), 5);
            accTextFieldTwo.setEnabled(false);
            accLabel.setLabelFor(accTextField);
            opLabel.setLabelFor(accTextFieldTwo);
            accPanel.add(accLabel, BorderLayout.WEST);
            accPanel.add(accTextField, BorderLayout.CENTER);
            accPanelTwo.add(opLabel, BorderLayout.WEST);
            accPanelTwo.add(accTextFieldTwo, BorderLayout.CENTER);
            accPanelTwo.add(opsLabel, BorderLayout.EAST);
            accPanelTwo.add(opsField, BorderLayout.NORTH);
            accPanelThree.add(stateLabel, BorderLayout.WEST);
            accPanelThree.add(stateField, BorderLayout.CENTER);
            content.add(accPanel, BorderLayout.CENTER);
            content.add(accPanelTwo, BorderLayout.EAST);
            contentTwo.add(accPanelThree, BorderLayout.EAST);

        JButton jButton1 = new JButton("Stop agent");
        JButton jButton2 = new JButton("Dismiss");
        jButton1.addActionListener(handler);
        jButton2.addActionListener(handler);
        buttonPanel.setLayout(new GridLayout(2, 3, 3, 3));
        n.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        buttonPanel.add(jButton2, null);
        buttonPanel.add(jButton1, null);
        n.pack();

A: I just coded the first few fields of your panel using the GridBagLayout to show you how to use the layout.
You'll have to finish the coding to get your full form created.
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class GridBagPanel {

    protected static final Insets leftInsets = new Insets(10, 10, 0, 0);
    protected static final Insets rightInsets = new Insets(10, 10, 0, 10);

    protected JPanel mainPanel;

    protected String agentID;

    public GridBagPanel() {
        createPartControl();
    }

    private void createPartControl() {
        mainPanel = new JPanel();
        mainPanel.setLayout(new GridBagLayout());

        int gridy = 0;

        JLabel stateLabel = new JLabel("State:");
        addComponent(mainPanel, stateLabel, 0, gridy, 1, 1, leftInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JTextField stateField = new JTextField("Running");
        stateField.setEnabled(false);
        stateLabel.setLabelFor(stateField);
        addComponent(mainPanel, stateField, 1, gridy++, 1, 1, rightInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JLabel transLabel = new JLabel("Amount transferred:");
        addComponent(mainPanel, transLabel, 0, gridy, 1, 1, leftInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JTextField transField = new JTextField(5);
        transField.setEnabled(false);
        transLabel.setLabelFor(transField);
        addComponent(mainPanel, transField, 1, gridy++, 1, 1, rightInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JLabel opsLabel = new JLabel("Operations Completed:");
        addComponent(mainPanel, opsLabel, 0, gridy, 1, 1, leftInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JTextField opsField = new JTextField("0");
        opsField.setEnabled(false);
        opsLabel.setLabelFor(opsField);
        addComponent(mainPanel, opsField, 1, gridy++, 1, 1, rightInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JLabel agentLabel = new JLabel("Agent ID: ");
        addComponent(mainPanel, opsLabel, 0, gridy, 1, 1, leftInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

        JTextField agentField = new JTextField(agentID);
        agentField.setEnabled(false);
        agentLabel.setLabelFor(agentField);
        addComponent(mainPanel, agentField, 1, gridy++, 1, 1, rightInsets,
                GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);

    }

    protected void addComponent(Container container, Component component,
            int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
            int anchor, int fill) {
        GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
                gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
        container.add(component, gbc);
    }

}


text:
Q: ffmpeg hangs on last frame during alphamerge I'm trying to blur specific part of video using alphamerge command.
The command that I'm using is following:
ffmpeg -y -i "odd resolution.3g2" -loop 1 -i cahceg0 -filter_complex "[0:v]scale='320:178',split=3[er0][ero1][er2];[er0][1:v]alphamerge,boxblur=chroma_radius=4:luma_radius=4:ap=0[alfb0];[er2]crop=256.0:18.956467:32.0:10.797836,boxblur=chroma_radius=4:luma_radius=4[alfb1];[ero1][alfb0]overlay[v0];[v0][alfb1]overlay=32.0:10.797836[v1]" -map [v1] -c:a copy -c:v libx264 output.3g2

The whole process works normally until the very last one frame, then ffmpeg just hangs indefinitely with this last output
frame=  312 fps= 19 q=27.0 size=     512kB time=00:00:17.22 bitrate= 243.5kbits/s speed=1.03x  .
At this point only fps and speed value change. The issue fixes if I remove '-loop 1' switch from second input or do not scale the first input but then it does not blur the video I want it to be
I am attaching input files and ffmpeg log
odd_resolution.3g2 cahceg0 ffmpeg_log

A: Try adding repeatlast=0 switch to your filtercomplex
ffmpeg -y -i "odd resolution.3g2" -loop 1 -i cahceg0 -filter_complex "[0:v]scale='320:178',split=3[er0][ero1][er2];[er0][1:v]alphamerge,boxblur=chroma_radius=4:luma_radius=4:ap=0[alfb0];[er2]crop=256.0:18.956467:32.0:10.797836,boxblur=chroma_radius=4:luma_radius=4[alfb1];[ero1][alfb0]overlay[v0];[v0][alfb1]overlay=32.0:10.797836:repeatlast=0[v1]" -map [v1] -c:a copy -c:v libx264 output.3g2

A: Issue was with the order of aliases in split command, so the aliases should be used in same order as they are declared in split expression else ffmpeg will stuck, following is fixed command.
ffmpeg -y -i "odd resolution.3g2" -loop 1 -i cahceg0 -filter_complex "[0:v]scale='320:178',split=3[er0][ero1][er2];[er0][1:v]alphamerge,boxblur=chroma_radius=4:luma_radius=4:ap=0[alfb0];[er1]crop=256.0:18.956467:32.0:10.797836,boxblur=chroma_radius=4:luma_radius=4[alfb1];[ero2][alfb0]overlay[v0];[v0][alfb1]overlay=32.0:10.797836[v1]" -map [v1] -c:a copy -c:v libx264 output.3g2


text:
Q: How to access keys and first string value while traversing a multi-dimensional array? Desired result: "My preferred salty food is the snack Rufles".
I would like to echo the array "snack" inside the array "salty food" as a string:
$food = array(
    "salty food" => array(
        "snack" => array(
            0 => "Rufles",
            1 => "Generic"
        )
    )
);

echo "My prefered ";

foreach($food as $key => $value)     //salty food
    echo $key;

echo " is the ";

//--MY DOUBT IS HERE. DESIRED ECHO: "snack" (FROM THE DEEP ARRAY):
foreach($food as $key => $value)
    echo $key["snack"];

print_r($food["salty food"]["snack"][0]);     //Rufles

A: Use nested loops:
echo "My preferred ";
foreach ($food as $type1 => $value1) {
    echo $type1;
    echo " is the ";
    foreach ($value1 as $type2 => $value2) {
        echo "$type2 $value2[0]";
    }
}

DEMO

A: Should be ok
<?php

    $food = array(
        "salty food" => array(
            "snack" => array(
                0 => "Rufles",
                1 => "Generic"
                )
            )
    );

    echo "My prefered ";

    foreach($food as $key1 => $value){
        echo $key1;
        echo " is the ";
        foreach($value as $key2 => $value){
            echo $key2." ";
        }
    }
    print_r($food["salty food"]["snack"][0]);

?>


text:
Q: How do I calculate a loss rate from the reflectivity? If I have a laser cavity that is contained between two mirrors and I know the reflectivity, R1 and R2, of each mirror, is there an easy way to calculate the photon loss rate through each of the mirrors per second?

A: Yes, suppose the laser cavity is of length $L$. The round trip time of photon is $\frac{2 L }{c}$. In each round trip, the fractional loss is $1-R_1R_2$.
So loss rate = $\frac{c(1 - R_1R_2)}{2 L}$. This has units of $s^{-1}$.


text:
Q: Nginx + PHP index.php not found 404 I'm running debian 9 with nginx 12 and php7.1
I've set evrrything up.
Nginx does not give me anything in error log, all the PHP scripts are working 100% fine. Nginx indexes index.html as index but DOES NOT find index.php and returns 404, even though I have it set in the nginx config.
Here is my nginx config:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.php index.html index.htm;

    server_name _;
    server_tokens off;

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri /index.html index.php;
    }

    # pass PHP scripts to FastCGI server
    #

    location ~ \.php$ {

            # With php-fpm (or other unix sockets):
            try_files $uri =404;
            include fastcgi.conf;
            fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
            fastcgi_index index.php;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #       deny all;
    #}}

A: All good, figured it out :)
This was the mistake I had in my cfg:
 location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri /index.html index.php;
    }


text:
Q: Can I use my existing git repo with openshift? Is it necessary to have git repo on openshift only? I already have bitbucket / github git repo and would prefer to push there only. Can I simply hook into it so that openshift gets intimation ?
Or for simplification, I push only at github, but when I want to deploy, I do something with openshift?
I did check this but it confused me:  it's talking about merging exiting and new (openshift) git ?

A: From you project folder, do
git remote add backup user@server:/path/to/git/test.git
git push backup master

You can read Pushing to two git remote origins from one repository and Changing git remote origin.

A: I agree with @adietisheim's answer: you need to understand better git before deploying with openshift =)
Now, even if you understand git, it is not necessarily obvious how to deploy your existing repo if your directory structure does not match the directory structure required by openshift, and if you want to keep your old directory structure.
For that, I have the following tips:

*

*separate options that are deployment dependent from those that are not into different files. For example, I separate my database settings from other settings into different files as:

*

*settings_deploy/openshift

*settings_deploy/localhost
and then symlink to your localhost test as something like:
ln -s settings_deploy/localhost settings_deploy_file

Another option is to detect the host by using environment variables:
if 'OPENSHIFT_APP_NAME' in os.environ:
    //openshift configurations
else:
    //localhost

This is a bit simpler since it allows you to put all the configs on a single file. It is a bit less general, since if ever another one of your hosts offers an OPENSHIFT_APP_NAME environment variable (unlikely for this one) the method breaks. Anyways, you still have to clearly separate what is deployment dependent and what is not.

*create a local deploy directory

*clone the initial openshift template into it

*create a deploy script that:

*

*hardlinks everything from your old existing local to their correct locations at the
hardlinks are fast to create and use very little memory
you could use something like:
cp -lrf original_repo_dir  deploy_repo_dir

*keep only the correct settings_deploy file in the deploy repo:
cd deploy_repo
mv settings_deploy/openshift settings_deploy_file
rm -r settings_deploy

*force push:
cd deploy_repo
git push -f origin master

*clean the deploy repo:
git reset --hard HEAD
git clean -df
for those interested in django deployment, I have an example on my github, in particular check out the deploy.sh script and the project projects/elearn which it deploys.

A: You should be able to pass in an existing Git repository into the asset pipeline via
rhc create-app $APPNAME ruby-1.9 --from-code $GIT_LOCATION

The remote Git repository then delivers the initial application for OpenShift.
As a second possibility, you can skip the creation of the local OpenSHift Git repository via
rhc create-app $APPNAME ruby-1.9 --no-git

and then use the steps described above to merge the OpenShift remote Git repository into your local Git repository.

A: Mohannd's answer is perfect, but I would like to sum up the complete solution, in case some else needs it:
To use your github repo as an Openshift repo, there is no perfect solution now, because, Openshfit uses git hooks to trigger the deployment or redeployment based on your commits. However, the smartest way would be to use 2 repos (the openshift's one and your github's one) to push simultaneously the code to.
To do this:
Add a remote named "all" and add 2 push urls to it.
git remote add all ssh://23456781234567@yourapp-namespace.rhcloud.com/~/git/yourapp.git
git remote set-url openshift-git-repo --push --add ssh://23456781234567@yourapp-namespace.rhcloud.com/~/git/yourapp.git
git remote set-url github-repo --push --add git@github.com:youruser/yourapp.git

Then set the remote named 'all' as the default push remote:
git push -u all

To commit and push your code, proceed as usual: It will push on the 2 remotes and deploy on OpenShift
git add .
git commit -m "my commit"
git push

And watch the result:
[master 3fc96b2] my commit
 1 file changed, 2 deletions(-)
MyLaptop:myapp User$ git push
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 291 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
To git@github.com:User/myapp.git
   a036a44..3fc96b2  master -> master
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 291 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Stopping PHP 5.4 cartridge (Apache+mod_php)
remote: Waiting for stop to finish
remote: Waiting for stop to finish
remote: Building git ref 'master', commit 3fc96b2
remote: Preparing build for deployment
remote: Deployment id is 9037d37a
remote: Activating deployment
remote: Starting PHP 5.4 cartridge (Apache+mod_php)
remote: Application directory "/" selected as DocumentRoot
remote: -------------------------
remote: Git Post-Receive Result: success
remote: Activation status: success
remote: Deployment completed with status: success
To ssh://23456789@myapp-namespace.rhcloud.com/~/git/myapp.git/
   a036a44..3fc96b2  master -> master
MyLaptop:myapp User$

Hope this helps

A: I know the question is 2-year old and the @adietisheim's answer has been accepted. I personally don't like to merge the openshift repo into my local clone because I don't want to mix the OpenShift repo into the master branch of my public repo.
Assuming you have added the remote using git remote add openshift <openshift-git-repo-url>, here is what I would do:
Create a new local branch openshift based on the master branch.
git checkout -b openshift

You could make some commits on the branch openshift such as your app deployment configurations.
Then, push the current branch to the remote ref matching master in the OpenShift repository with the flag -f to overwrite everything in the remote master branch.
git push openshift master -f

Whenever I want to deploy my app to OpenShift, I would check out the local openshift branch and merge master branch with it, then force push to OpenShift, however -f may not be required for the next pushes:
git checkout openshift
git merge --no-ff master
git push openshift master -f

A: I have the impression that you're not used to use git enough yet. I'd advise you to get into git to fully understand how to push your code to openshift. Nevertheless let me try to explain you the steps involved:
As you'd do with git in general, the approach to choose here is to clone your other git repo (ex. on bitbucket) to your local machine:
git clone <bitbucket-repo-url>
Your local clone has then your other repo (bitbucket etc.) as remote repo. Your remote repo is stored with the alias "origin" (the default alias used by git if you clone). You then add the openshift repo as remote to your clone. You do that while explicitly using an alias for the remote repo you add - I'm using "openshift" as alias here:
git remote add openshift -f <openshift-git-repo-url>
In order to then be able to push the code from your local git repo to openshift you first have to merge your openshift repo with your local bitbucket clone. You do that by issuing locally:
git merge openshift/master -s recursive -X ours
With this command you tell git to merge the master branch in the openshift git repo with your local git repo. You tell it to merge using the recursive merging strategy and to choose your ("ours") version when there are conflicts.
Once the merge is executed you're ready to push your git repo to openshift. You do that by doing:
git push openshift HEAD
You tell git to push your local code to the HEAD branch on the remote repo called "openshift" (the alias we stored the openshift git repo at, some paragraphs further up).
btw. I wrote a jboss tools blog which was demonstrating how to use the openshift-java-client some months ago: https://community.jboss.org/wiki/Enable-openshift-ciFullExampleUsingOpenshift-java-client . You'll spot the above steps in the last paragraph "We're almost there".

A: There is a way to do what you want, i.e. skip Openshift's repo.
What you need to do is set up a jenkins, and have it poll your own repository.
There's a link here that explains how to set it up from scratch:
http://blog.anthavio.net/2014/01/deploy-to-openshift-from-github.html

A: I ran into problems deploying a pre-existing code repository to Openshift. In my particular context, where I tried to deploy a tomcat webapp, the Openshift tomcat configuration files included in the .openshift folder were crucial.
What fixed it for me was the inclusion of the .openshift folder in my existing source tree, as well as the inclusion of the openshift profile in my maven pom.xml file.
This is highly likely the same that would happen by merging your repository with the new openshift upstream one. For me, this is the "why" behind following sentence in adietisheim's great answer:
"In order to then be able to push the code from your local git repo to openshift you first have to merge your openshift repo with your local bitbucket clone."
In my case, this merge was needed to get the config files from the .openshift directory. It took a long time to figure out for me because pushing without the .openshift directory still made my app build and deploy successfully. The only behaviour I saw was a report on missing jsp files, which made me think that the problem was related to my own web.xml and servlet configuration.

A: If you're using github you can configure travis to made the deployment each time you made a change in your github repository
http://docs.travis-ci.com/user/deployment/openshift/

A: If you are using java then there's is an alternative approach. But even in this approach you would still use the OpenShift git repository. The git repository provided by OpenShift is how you give OpenShift your code, your deployable(s):
You can - instead of committing your code to the OpenShift git repo - simply give it your war-file. You clone the OpenShift git repo to your local machine. You then build a war from your application source and put this war into the deployments folder within your OpenShift git repo (clone). You then add, commit and push your local clone to OpenShift. Once the push executed successfully, the JBoss AS7 will pick your war and deploy it.

A: TAKE EASY!
step 1: Create app. With your favorite method (from gitRepository, pre-maker Openshift, etc). if you use console metod
step 2: rhc git-clone nameApp
step 3: rhc app-configure nameApp --auto-deploy
step 4: ENJOY!


text:
Q: How to understand this C macro? I am not able to understand this code
#define sqt(x) x*x
int main(){
print("%d",sqt(3+1));
}

Manually I am getting the output of 10. But when write the code and compile it I am getting the answer as 7. Please explain this.

A: Remember, since you're using a macro, 3 + 1 is not evaluated before sqt is called. x becomes 3 + 1 (not 4), then order of operation causes an unexpected answer to be produced since addition happens after multiplication.
Or in other words:
sqt(3 + 1)

expands to:
3 + 1 * 3 + 1

Then, when you evaluate this like you would any other equation:
3 + 1 * 3 + 1 // Multiplication happens first
= 3 + 3 + 1
= 7

This is a good example of why you shouldn't use macros unless they're strictly necessary, or you've made proper care to ensure that things like order of operation mistakes don't happen. As @Barmar points out this particular case can be remedied by having the macro expand to include explicit parenthesis:
#define sqt(x) ((x)*(x))

Which would cause the evaluation to differ and give a proper answer:
(3 + 1) * (3 + 1)
4 * 4
16


text:
Q: Update entered date in CalendarView in Android I have a Calendarview and an Edittext. I wish to take the date entered in the edittext in the format DD/MM/YYYY and set it on the Calendarview. The view should update the current date bubble to the set date.
I have already tried:
How to set focus on a specific date in CalendarView knowing date is "dd/mm/yyyy"
This is my current code:
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2019);
        calendar.set(Calendar.MONTH, Calendar.JUNE);
        calendar.set(Calendar.DAY_OF_MONTH, 20);

        long milliTime = calendar.getTimeInMillis();
        CalendarView calendarView =  findViewById(R.id.calendar);
        calendarView.setFocusedMonthDateColor(Color.BLUE); //apparently this is deprecated so won't work. Not working without it either.
        calendarView.setDate (milliTime); //this is supposed to change the date but isn't

Thanks in advance!

A: I have read your question and i have try to solve this problem. pass date(time in milliseconds) in long type  value to set date in calendar view like this calendar_view.setDate(milliTime); try this code to achieve your goal .
Code
    calendar_view = findViewById(R.id.calendar_view);

  //replace date variable static value to your edit text
    value
  String date = "25/06/2019";
    String parts[] = date.split("/");

    int day = Integer.parseInt(parts[0]);
    int month = Integer.parseInt(parts[1]);
    int year = Integer.parseInt(parts[2]);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);

    long milliTime = calendar.getTimeInMillis();
    calendar_view.setDate(milliTime);


text:
Q: matching files to folders Can linux scan two directories? Once scanned match the two directories based on similarities in the file name and transfer files.
I'm looking to transfer file  "directory"/seq0001.pdf to folder "different directory"/001 and "directory"/seq0002.pdf to folder "different directory"/002
e.t.c
When newly incremented file number is created I would like to move that new file to the new directory.
The new folder doesn't need to be made. As when there is a new file some other job is putting information in this folder and creates the new folder.
I know how to do a straight move function but that would only work for the specified files.
Can you move the files by a match rather than having to manually move the files every time?

A: There might be a way to shorten this (actually, there are a ton of good alternatives for parsing the file name; check out this question - I will update here as soon as I get a chance), but one way is to first create a script that handles a single file. For example, save the following as move.sh:
#!/bin/sh
subdir=`echo -n "${1%.*}" | tail -c3`
mv -v "$1" "/path/to/$subdir"

Adjust to taste. That will take take the part of the filename before the last "." and use the rightmost three characters as the target directory (e.g. "seq0002.pdf" goes to "/path/to/002").
The chmod 755 move.sh to make it executable.
I recommend putting that script in a different directory so it doesn't interfere. Then you can use e.g. find to execute it on all files, or just run it on one file at a time, e.g.:
find . -maxdepth 1 -type f -exec /wherever/move.sh {} \;

Or for one file (and assuming move.sh is in current directory):
./move.sh seq0001.pdf

If you want to choose more complex paths you can extend the script, e.g.:
#!/bin/sh
subdir=`echo -n "${1%.*}" | tail -c3`

if [ $subdir = "001" ] ; then
    rootdir="/directory";
elif [ $subdir = "002" ] ; then
    rootdir="/another/place";
else
    rootdir="/default/root";
fi

mv -v "$1" "$rootdir/$subdir"

Again adjusting to taste. The possibilities are fairly limitless.