text:
Q: How to retrieve a channel id from a channel name or url I'm trying to retrieve the channel id of a YouTube channel using the new v3 API. I'm using the Python client and it seems that there is no straightforward way to find the mapping of a YouTube channel URL or name to its channel Id.
Using the Python API client, it seems that I have to issue a search query of type 'channel' for the channel name, then iterate through each search result until I find a match.
I'm going to use the http://youtube.com/atgoogletalks channel as an example
search_channel_name = 'atgoogletalks'     #Parsed from http://youtube.com/atgoogletalks
search_response = youtube.search().list(
    type='channel',
    part='id,snippet',
    q=search_channel_name,
    maxResults=50
    ).execute()
for sri in search_response["items"]:
    channels_response = youtube.channels().list(
        id=sri["id"]["channelId"],
        part="id, snippet, statistics, contentDetails, topicDetails"
        ).execute()

    for cr in channels_response["items"]:
        channelname = cr["snippet"]["title"]
        if channelname.lower() == search_channel_name:
            return 'Success'

I've crawled the documentation looking for one a more straightforward way of doing this and come up short. Is there an easier way? If not, is there a plan to add this functionality to the API?

A: Following YouTube Data API
you could use forUsername parameter of youtube.channels.list()
Using your own example:
search_channel_name = 'atgoogletalks'
channels_response = youtube.channels().list(
        forUsername=search_channel_name,
        part="id, snippet, statistics, contentDetails, topicDetails"
).execute()

A: Sometimes the forUsername parameter doesn't return the required results. What you could do is:
from googleapiclient import build
import requests
import json

youtube = build('youtube', 'v3', developerKey=your_key_here)

channel_id = requests.get('https://www.googleapis.com/youtube/v3/search?part=id&q={search_query_here}&type=channel&key={api_key_here}').json()['items'][0]['id']['channelId']

channels_response = youtube.channels().list(id=channel_id, part='id, snippet, statistics, contentDetails, topicDetails').execute()


text:
Q: What are the connotations of the word "pedantry"? This is a request of help for the connotations of a word
If native speakers hear the word, pedantry, does it assume an air of showy, academically pompous, impudent impression to them?
Would this word or these words, pedantry or pedant, mean a person who is excessively fussy on academic minutia and thus a bit irritable to us?

A:
... and thus a bit irritable to us?

No, there is nothing about the definition of pedant or pedantry that relates to people's reactions to the behavior, just as there is nothing about the definition of murder that relates to the way people react to it.
And words do not "assume airs".  Speakers assume airs.
The basic meanings of those words can be found in good dictionaries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OS X NSStatusItem How to set the accessibility title for VoiceOver There is no direct API (as far as I can see) but some applications seem to have it.
Although Apple's own icons (e.g. fast user switching, keyboard layout switching) do not have it.

A: Since OS X 10.10, NSStatusItem has button property, which is a regular NSView-based control that conforms to NSAccessibility protocol and which allows to change accessibilityTitle property directly.
On earlier versions of OS X, you can implement a custom button that looks and behaves exactly like vanilla NSStatusItem and assign it to the item via -[NSStatusItem setView:] method, then use -[NSView accessibilitySetOverrideValue:... forAttribute:NSAccessibilityTitleAttribute] on your custom control to provide a voiceover title.


text:
Q: Castle.MicroKernel.ComponentNotFoundException : No component for supporting the service Castle.Services.Transaction.ITransactionManager was found Hi I am using Castle with the NHibernate Integration Faclility
I am running a few tests and they are failing with the error
at Castle.MicroKernel.DefaultKernel.get_Item(Type service)
at Castle.Facilities.NHibernateIntegration.DefaultSessionManager.ObtainCurrentTransaction()
at Castle.Facilities.NHibernateIntegration.DefaultSessionManager.OpenSession(String alias)
at Castle.Facilities.NHibernateIntegration.DefaultSessionManager.OpenSession()
at Core.Repositories.NHibernateSqlDbLiteRepository`1.GetAll()

A: well I think the error is pretty obvious - you didn't register transaction manager. This probably means you didn't add Transaction facility to the container, did you?


text:
Q: Setting opacity on $primary-color in sass Is there an option to include opacity on the colors you define to be your primary/secondary colors in the sass variables? In the fashion of the lighten($color, amount) function?

A: You can use rgba, i.e.
$primary: rgba(20,20,20, .5);

It works for hex values as well
$primary: rgba(#4B00B5, .3);

You can also set the opacity of colors based on a variable value. For example:
$primary-color: #a61723;
....
color: rgba($primary-color, .5);

Demo


text:
Q: How do I link an image in my plugin so it displays on WordPress? I'm creating a plugin for a college project. The plugin is very simple: it searches for name of the site address and upon finding it in a post, it outputs the site address with an image. However, I cannot get the code working. I've tried this:
<?php
/*
Plugin Name: Murtaghs Trademark Plugin
Plugin URI: http://www.MurtaghsPub&Undertakers.ie
Description: Adds Murtaghs Logo Wherever name Of Business Displayed On Page.
Author: Connell Gray
Version: 1.0
Author URI: http://www.MurtaghsPub&Undertakers.ie
*/
function Murtaghs_Trademark_Plugin($text) {

    $site_name = get_bloginfo();
    //the logo.jpg file is stored in a folder called images which i  have created in the plugins folder//
    $new_site_name = $site_name . 'echo ' '';

    $text = str_replace($site_name,$new_site_name,$text);

    return $text;
}
add_filter('the_content','Murtaghs_Trademark_Plugin');

?>

A: This line is your problem:
$new_site_name = $site_name . 'echo ' '';

Here you've muddled up the quotes and put PHP code inside a string expecting it to still work.
e.g.
echo ' this is inside a quote:' inside a quote ' . ';

It doesn't work because the quote in your string closes the starting quote, ending the string. To fix this you need to either:

*

*use a double quote

*escape your characters

e.g.
echo 'this is inside a quote \' inside a quote \' .';

As a side note, make sure that your code editor supports syntax highlighting with a good colour scheme, it will make these kinds of issues more obvious.


text:
Q: $event.stopPropagation() runs but parent event still executes So I have a button that is inside an   tag that links to another location. When I click the button I want it so that it does not trigger the link in the parent tag. I have tried using $event.stopPropagation() but it does not seem to work.
here is my html:

        //divs

{{eventObj.eventName}}

{{eventObj.eventStart | date}} - {{eventObj.eventEnd | date}}

{{eventObj.eventVenue}}

              <button ng-click="deleteEvent(eventObj,$event)"></button>
        //divs

and the function in my controller:
$scope.deleteEvent = function(delEvent,$event){
            $event.stopPropagation();
            console.log($event.isPropagationStopped())
            $scope.targetEvent = delEvent;
            if(confirm("Note: This will permanently delete the event and games associated with it.")==true){
                EventService.deleteEvent($scope.targetEvent)
                .then(function(){
                    EventService.getEvents()
                    .then(function(events){
                        $scope.events = events;
                    });
                })
                window.location.reload();
            }
        }

What do I do here?

A: Use event.preventDefault instead, here is an example

  <button onclick="clickFunction(event);">
  test
  </button>

https://jsfiddle.net/3Lrr24qu/
As to why it doesn't work, triggering hyperlink is a default event not an event listener. If you had an onclick instead of the href on the link the event.stopPropagation would work, see the documentation below.
From https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-capture :
1.2.3. Event bubbling
Events which are designated as bubbling will initially proceed with the same event flow as non-bubbling events. The event is dispatched to its target EventTarget and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the EventTarget's parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including the Document. EventListeners registered as capturers will not be triggered during this phase. The chain of EventTargets from the event target to the top of the tree is determined before the initial dispatch of the event. If modifications occur to the tree during event processing, event flow will proceed based on the initial state of the tree.
Any event handler may choose to prevent further event propagation by calling the stopPropagation method of the Event interface. If any EventListener calls this method, all additional EventListeners on the current EventTarget will be triggered but bubbling will cease at that level. Only one call to stopPropagation is required to prevent further bubbling.
1.2.4. Event cancelation
Some events are specified as cancelable. For these events, the DOM implementation generally has a default action associated with the event. An example of this is a hyperlink in a web browser. When the user clicks on the hyperlink the default action is generally to active that hyperlink. Before processing these events, the implementation must check for event listeners registered to receive the event and dispatch the event to those listeners. These listeners then have the option of canceling the implementation's default action or allowing the default action to proceed. In the case of the hyperlink in the browser, canceling the action would have the result of not activating the hyperlink.
Cancelation is accomplished by calling the Event's preventDefault method. If one or more EventListeners call preventDefault during any phase of event flow the default action will be canceled.
Different implementations will specify their own default actions, if any, associated with each event. The DOM does not attempt to specify these actions.


text:
Q: join two tables and pivot in oracle sql I need to join two tables.
Table 1 contains the quarterly lists and contains the following columns:
Year, ID, ID2, Quarter(value can be 1, 2, 3, 4), Amount_Due_for_the_Quarter
2018, 001, 000, 3, $1.00
2018, 001, 000, 4, $2.000

Table 2 contains the monthly submission of list and contains the following columns:
Year, ID, ID2, Mo (value is from January[1] to December[12]), Amount_Due_ per_Month
2018, 001,000, 8, $5.00
2018, 001,000, 10, $6.00
2018, 001,000, 11, $7.00

these tables can joined using ID and ID2 and year. the 1st table may or may not have submission for all the quarters. the 2nd table may or may not have submission for all the months. 1st quarter corresponds to month1, month2,  2nd quarter for months 4 and 5, and so on.
After join, output should be:
Year, ID, ID2, Quarter, Amount Due for Qtr, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
2018, 000, 001, 3, $1, null, null, null, null, null, null, null, $5.00, null, null, null, null
2018, 000, 001, 4, $2, null, null, null, null, null, null, null, null, null, $6.00, $7.00, null

select
      a.qtr,
      b.id,
      b.id2,
      nvl(b.Amount_Due_ per_Month,0)
from  tbl1  a
      left join tbl2 b
        on a.year = b.year
        and a.id = b.id
        and a.id2 = b.id2
  where a.year = '&year'
        and a.id = '&id'
        and a.id2 = '&id2';

but gives me:
Year, ID, ID2, Quarter, Amount Due for Qtr, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
2018, 000, 001, 3, $1, null, null, null, null, null, null, null, $5.00, null, $6.00, $7.00, null
2018, 000, 001, 4, null, null, null, null, null, null, null, null, null, null, $6.00, $7.00, null

A: You have to join quarters and months properly, for instance with floor((mo-1)/3) + 1 = qtr, this way you assign Jan, Feb, Mar to quarter 1, Apr, May, Jun to 2 etc. Like here:
select *
  from (
    select * from t1
      join t2 using (year, id, id2)
      where id = '001' and id2 = '000' and floor((mo-1)/3) + 1 = qtr)
  pivot (max(amt_mth) for mo in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))

dbfiddle demo


text:
Q: End tag for body not found and unclosed div elements Here is the problem that is been bugging me for 2 days now. My website which is running on Wordpress, was working just fine until i've added 1 new article; after that the template gets messed up and after running a validation on w3.org, it says that i'm missing an end tag for  and 2 unclosed  elements.
Now the strange thing is this. When i remove (unpublish) one article, the template is working again just fine.. But when i publish that article back, the validation errors reappear.
I've eliminated the possibility that that the error is a result of an unwanted html code (accidentally) included in the editor, but I cant find whats causing this error.
Can someone, please, help me out? I'm running out of ideas :(
My website: http://www.vantagemag.com/
The validation code: http://validator.w3.org/check?uri=http%3A%2F%2Fwww.vantagemag.com%2F&charset=%28detect+automatically%29&doctype=Inline&group=0

A: Turns out, an earlier article had  elements in the code, which my client didn't see when he was posting that article. Now i've removed all unwanted elements and everything is back to normal.
Thank you all for the responses and for your time!


text:
Q: Sign In With Google Button Padding in iframe I'm using the Sign In With Google Button using this library (https://www.npmjs.com/package/@react-oauth/google).
The button is being rendered in an iframe.
How do I get rid of the padding (green portion in the picture) in one of the divs (in the iframe)?

A: Unfortunately you can't, Google controls the render of the iframe
you can use useGoogleLogin and create your custom login button if you want to have dark theme


text:
Q: How to display customer address in Textarea insteadof selectbox in Checkout page in Mag I am trying to display all address of customer in Textarea in shipping address and billing address of checkout page instead of selectbox,  where customer should have the option to choose among their list of address.Anybody help me to achieve it. Thanks in advance.

A: Plesae remove/comment the dropdown and customize the file.Please try this way.
<?php
$session = Mage::getSingleton('customer/session');
$cidData = $session->isLoggedIn();
$cidvar = $session->getId();

$customer = Mage::getModel('customer/customer')
        ->load($cidvar); //put customer id here
$data = array();
$i = 0;
foreach ($customer->getAddresses() as $address) {
    $data[$i] = $address->toArray();
    $i++;
}

foreach ($data as $values) {
    ?>
    <div id="<?php echo $values['entity_id'] ?>">

                    <?php echo $values['firstname']; ?>
            <?php echo $values['city']; ?>
            <?php echo $values['region']; ?>
            <?php echo $values['street']; ?>

        <form>

                <a class="group1" href="<?php echo Mage::getBaseUrl() . 'customer/address/edit/id/' . $values['entity_id']; ?>?popupEdit=1&meth=billing" >
                    <input type="button"  value="EDIT" class="gray_btn"/>

        </form>

<?php } ?>


text:
Q: PyQt SpinBox value is always returning value of 0 / SpinBox not recognized I'm creating a plugin in which I use spinboxes. The value set by the user on the spinboxes is meant to define precision in which the result will be printed. Even though my spinbox has different values each time I'm debugging it with print(QSpinBox().value) it always returns 0.
I suppose that 0 is a default value to be printed, but I can't get to find any solution to my problem.
I'm a beginner in Python.
This is my code:
class ALCalculatorDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(ALCalculatorDialog, self).__init__(parent)

        self.setupUi(self)

        self.stackedWidget.setCurrentWidget(self.home)

        self.pbAreaPage.clicked.connect(self.gotoArea)
        self.pbLengthPage.clicked.connect(self.gotoLength)
        self.pbJumpArea.clicked.connect(self.gotoArea)
        self.pbJumpLength.clicked.connect(self.gotoLength)

        self.cbLengthLayerList.setFilters(QgsMapLayerProxyModel.LineLayer)
        self.cbAreaLayerList.setFilters(QgsMapLayerProxyModel.PolygonLayer)

        self.pbLengthCalc.clicked.connect(self.onPbLengthCalcClicked)
        self.pbAreaCalc.clicked.connect(self.onPbAreaCalcClicked)

    def onPbLengthCalcClicked(self):
        self.sb = QSpinBox()
        precision_value = self.sb.value()
        self.cb = QgsMapLayerComboBox(self)
        layer = self.cb.currentLayer()
        miles_conv = 0.621371192
        yard_conv = 1093.6132983377
        meters_conv = 1000
        if self.rbLengthMeters.isChecked():
            total_length = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_length += geometry.length()
            total_length = total_length * meters_conv
            self.lblLengthResult.setText('%.*f' % (precision_value, total_length))
        elif self.rbLengthKilometers.isChecked():
            total_length = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_length += geometry.length()
            self.lblLengthResult.setText('%.*f' % (precision_value, total_length))
        elif self.rbLengthMiles.isChecked():
            total_length = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_length += geometry.length()
            total_length = total_length * miles_conv
            self.lblLengthResult.setText('%.*f' % (precision_value, total_length))
        elif self.rbLengthYards.isChecked():
            total_length = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_length += geometry.length()
            total_length = total_length * yard_conv
            self.lblLengthResult.setText('%.*f' % (precision_value, total_length))

    def onPbAreaCalcClicked(self):
        self.sb = QSpinBox()
        precision_value = self.sb.value()
        self.cb = QgsMapLayerComboBox(self)
        layer = self.cb.currentLayer()
        sqmiles_conv = 0.386102159
        sqyards_conv = 1195990.05
        sqmeters_conv = 1000000
        hectares_conv = 100
        acres_conv = 10000
        if self.rbAreaMeters.isChecked():
            total_area = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_area += geometry.area()
            total_area = total_area * sqmeters_conv
            self.lblAreaResult.setText('%.*f' % (precision_value, total_area))
        elif self.rbAreaKilometers.isChecked():
            total_area = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_area += geometry.area()
            self.lblAreaResult.setText('%.*f' % (precision_value, total_area))
        elif self.rbAreaAres.isChecked():
            total_area = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_area += geometry.area()
                total_area = total_area * acres_conv
            self.lblAreaResult.setText('%.*f' % (precision_value, total_area))
        elif self.rbAreaHectares.isChecked():
            total_area = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_area += geometry.area()
                total_area = total_area * hectares_conv
            self.lblAreaResult.setText('%.*f' % (precision_value, total_area))
        elif self.rbAreaMiles.isChecked():
            total_area = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_area += geometry.area()
                total_area = total_area * sqmiles_conv
            self.lblAreaResult.setText('%.*f' % (precision_value, total_area))
        elif self.rbAreaYards.isChecked():
            total_area = 0
            for feat in layer.getFeatures():
                geometry = feat.geometry()
                total_area += geometry.area()
                total_area = total_area * sqyards_conv
            self.lblAreaResult.setText('%.*f' % (precision_value, total_area))

        #debug
        print(precision_value)

    def gotoArea(self):
        self.stackedWidget.setCurrentWidget(self.area)

    def gotoLength(self):
        self.stackedWidget.setCurrentWidget(self.length)


text:
Q: how to prevent an event for first time running in C# I have a Combobox that hav an event like this:
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (MessageBox.Show("  آیا مطمئن هستید","",
            MessageBoxButtons.OKCancel,MessageBoxIcon.Warning) == DialogResult.OK)
        {

            NotGrazingradioButton.Checked = true;

            if (CowTypeSelect.SelectedIndex == 0)
            {
                CowTypeDefaults.LactatingCow(this);
                CowTypeVarlbl.Text = "گاو شیری";
            }
            else if (CowTypeSelect.SelectedIndex == 1)
            {
                CowTypeDefaults.DryCow(this);
                CowTypeVarlbl.Text = "گاو خشک";
            }
            else if (CowTypeSelect.SelectedIndex == 2)
            {
                CowTypeDefaults.ReplacementHeifer(this);
                CowTypeVarlbl.Text = "تلیسه جایگزین";
            }
            else
            {
                CowTypeDefaults.YoungCalf(this);
                CowTypeVarlbl.Text = "گوساله";
            }
        }

    }

but I set a default index for this combox in load form,
now the problem is that when I run the program before it even opened the messageBox shows firs, is there any way to prevent the logic if to don't run in the first time?
//-----
as you said I changed the code like this:
    bool FirstRun = true;
    private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (FirstRun == true)
        {
            FirstRun = false;
            return;
        }

        if (MessageBox.Show("آیا مطمئن هستید؟", "",
  MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)

        {
            NotGrazingradioButton.Checked = true;

        if (CowTypeSelect.SelectedIndex == 0)
        {
            CowTypeDefaults.LactatingCow(this);
            CowTypeVarlbl.Text = "گاو شیری";
        }

        else if (CowTypeSelect.SelectedIndex == 1)
        {
            CowTypeDefaults.DryCow(this);
            CowTypeVarlbl.Text = "گاو خشک";
        }
        else if (CowTypeSelect.SelectedIndex == 2)
        {
            CowTypeDefaults.ReplacementHeifer(this);
            CowTypeVarlbl.Text = "تلیسه جایگزین";
        }
        else
        {
            CowTypeDefaults.YoungCalf(this);
            CowTypeVarlbl.Text = "گوساله";
        }

        }

but now the problem is that these code doesn't run for the first time and I need them to run:
    NotGrazingradioButton.Checked = true;

    if (CowTypeSelect.SelectedIndex == 0)
    {
        CowTypeDefaults.LactatingCow(this);
        CowTypeVarlbl.Text = "گاو شیری";
    }

what should I do ?

A: You either register the event handler after you loaded the combobox, or you build in a check on the first run, something like this:
private bool firstRun = true;

In your method:
if (firstRun)
{
    firstRun = false;
    return;
}

A: Seems like you don't understands @Patrick Hofman's code.
The firstRun variable indicates whether the function is executed in the first time.
and the lines below means if it's executed for the first time, it changes firstRun to false and stop executing the codes after the return; line. (I've added some comments to make it clearer to you.)
// Put codes here if you want it to execute every time.
if (firstRun)
{
    // Codes here execute at the first time only.
    firstRun = false;
    return;
}
//Codes here execute except the first time.

Fixed Code
This runs the below lines at the first time
NotGrazingradioButton.Checked = true;

if (CowTypeSelect.SelectedIndex == 0)
{
    CowTypeDefaults.LactatingCow(this);
    CowTypeVarlbl.Text = "گاو شیری";
}

and lines after if (MessageBox.Show(...)) runs except the first time
Full code below:
bool FirstRun = true;
private void CowTypeSelect_SelectedIndexChanged(object sender, EventArgs e)
{
    if (FirstRun == true)
    {
        // Codes here execute at the first time only.
        NotGrazingradioButton.Checked = true;
        if (CowTypeSelect.SelectedIndex == 0)
        {
            CowTypeDefaults.LactatingCow(this);
            CowTypeVarlbl.Text = "گاو شیری";
        }
        FirstRun = false;
        return;
    }

    //Codes below execute except the first time.
    if (MessageBox.Show("آیا مطمئن هستید؟", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
    {
        NotGrazingradioButton.Checked = true;

        if (CowTypeSelect.SelectedIndex == 0)
        {
            CowTypeDefaults.LactatingCow(this);
            CowTypeVarlbl.Text = "گاو شیری";
        }

        else if (CowTypeSelect.SelectedIndex == 1)
        {
            CowTypeDefaults.DryCow(this);
            CowTypeVarlbl.Text = "گاو خشک";
        }
        else if (CowTypeSelect.SelectedIndex == 2)
        {
            CowTypeDefaults.ReplacementHeifer(this);
            CowTypeVarlbl.Text = "تلیسه جایگزین";
        }
        else
        {
            CowTypeDefaults.YoungCalf(this);
            CowTypeVarlbl.Text = "گوساله";
        }
    }


text:
Q: Fabric JS: Copy/paste object on mouse down I'm trying to create a block game where you select shapes from a menu and place them on the canvas.  There is a shape menu where you can drag the shapes onto the canvas. I would like for it to leave the main shape in the menu as it drags a clone onto the canvas. Is this possible? I have created a jsfiddle to help.
JSFIDDLE
window.canvas = new fabric.Canvas('fabriccanvas');
var edgedetection = 10; //pixels to snap
canvas.selection = false;

window.addEventListener('resize', resizeCanvas, false);

function resizeCanvas() {
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
canvas.renderAll();
}

// resize on init
resizeCanvas();

//Initialize Everything
init();

function init(top, left, width, height, fill) {

    var bg = new fabric.Rect({
    left: 0,
    top: 0,
    fill:  "#eee",
    width: window.innerWidth,
    height: 75,
    lockRotation: true,
    maxHeight: document.getElementById("fabriccanvas").height,
    maxWidth: document.getElementById("fabriccanvas").width,
    selectable: false,
    });

    var squareBtn = new fabric.Rect({
    top: 6,
    left: 18,
    width: 40,
    height: 40,
    fill: '#af3',
    lockRotation: true,
    originX: 'left',
    originY: 'top',
    cornerSize: 15,
    hasRotatingPoint: false,
    perPixelTargetFind: true,
    });

    var circleBtn = new fabric.Circle({
    radius: 20,
    fill: '#f55',
    top: 6,
    left: 105,
    });

    var triangleBtn = new fabric.Triangle({
    width: 40,
    height: 35,
    fill: 'blue',
    top: 10,
    left: 190,
    });

    var sqrText = new fabric.IText("Add Square", {
    fontFamily: 'Indie Flower',
    fontSize: 14,
    fontWeight: 'bold',
    left: 6,
    top: 50,
    selectable: false,
    });

    var cirText = new fabric.IText("Add Circle", {
    fontFamily: 'Indie Flower',
    fontSize: 14,
    fontWeight: 'bold',
    left: 95,
    top: 50,
    selectable: false,
    });

    var triText = new fabric.IText("Add Triangle", {
    fontFamily: 'Indie Flower',
    fontSize: 14,
    fontWeight: 'bold',
    left: 175,
    top: 50,
    selectable: false,
    });

    var shadow = {
    color: 'rgba(0,0,0,0.6)',
    blur: 3,
    offsetX: 0,
    offsetY: 2,
    opacity: 0.6,
    fillShadow: true,
    strokeShadow: true
    }

    window.canvas.add(bg);
    bg.setShadow(shadow);
    window.canvas.add(sqrText);
    window.canvas.add(cirText);
    window.canvas.add(triText);
    window.canvas.add(squareBtn);
    window.canvas.add(circleBtn);
    window.canvas.add(triangleBtn);

    canvas.forEachObject(function (e) {
    e.hasControls = e.hasBorders = false; //remove borders/controls
});

this.canvas.on('object:moving', function (e) {
    var obj = e.target;
    obj.setCoords(); //Sets corner position coordinates based on current angle, width and height
    canvas.forEachObject(function (targ) {
        activeObject = canvas.getActiveObject();

        if (targ === activeObject) return;

        if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
            activeObject.left = targ.left - activeObject.currentWidth;

        }
        if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) {
            activeObject.left = targ.left + targ.currentWidth;

        }
        if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) {
            activeObject.top = targ.top - activeObject.currentHeight;
        }
        if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) {
            activeObject.top = targ.top + targ.currentHeight;
        }
        if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) {

        } else {
            targ.strokeWidth = 0;
            targ.stroke = false;

        }
        if (!activeObject.intersectsWithObject(targ)) {
            activeObject.strokeWidth = 0;
            activeObject.stroke = false;
            activeObject === targ
        }
    });
});
}

A: See Jsfiddle here, I add the function to do this.
function draggable(object) {
    object.on('mousedown', function() {
        var temp = this.clone();
        temp.set({
            hasControls: false,
            hasBorders: false,
        });
        canvas.add(temp);
        draggable(temp);
    });
    object.on('mouseup', function() {
        // Remove an event handler
        this.off('mousedown');

        // Comment this will let the clone object able to be removed by drag it to menu bar
        // this.off('mouseup');

        // Remove the object if its position is in menu bar
        if(this.top<=75) {
            canvas.remove(this);
        }
    });
}

draggable(squareBtn);
draggable(circleBtn);
draggable(triangleBtn);


text:
Q: Vectorise a string Im a python noob but trying to vectorise a string with no luck. So far I extract data from an article from a URL and now im trying to clasfiy that article but so far its not working.

(keep getting the error: raise AttributeError(attr + " not
  found")AttributeError: lower not found)

Nothing out there seems to be helping either.
    url = input("Paste the webiste containing the article you want to analise here: ");
print "Analysing Webpage"
#Gets the URL from the extension
#Goose loaded
g = Goose()
#Extract the text and feed it to the classifier
article = g.extract(url=url)
article = article.cleaned_text
article = clean(article)
article =str(article)
print "Vectorising Text"
article = article.split();
vect = CountVectorizer(min_df=0., max_df=1.0)
X = vect.fit_transform(article)
X.toarray()
X = vect.transform(X).toarray()
print X
print "Predicting Political Bias"
loaded_model = pickle.load(open("text_clf_svm.pkl", 'rb'))
predicted_svm = loaded_model.predict(X)
print predicted_svm

Any kind of help or indication is very welcomed, and thanked =)

A: It seems that you apply a fit_transform to your text. This result to a different X matrix to the one you/someone trained the classifier on. You need to have both "aligned".
In your case, you have the word "lower" in your X matrix but the model has been trained on a matrix without this word.
In your case, either you have the CountVectorizer model used to train the model and you have to apply only a transform, or you should use fit_transform but on a full corpus to train after the model and use it later in production.
I hope it helps,
Regards,
Nicolas


text:
Q: Updating an array element identified by other fields in the object using jq Goal
I'd like to add a proxy-url field to the currently active clusters entry of my kubeconfig file. The "active" cluster is identified by the "active" context, which is itself identified by a top-level key current-context. Simplified, the JSON object looks something like:
{
  "clusters":[
    {
      "name":"cluster1",
      "field":"field1"
    },
    {
      "name":"cluster2",
      "field":"field2"
    }
  ],
  "contexts":[
    {
      "name":"context1",
      "context": {
        "cluster":"cluster1"
      }
    },
    {
      "name":"context2",
      "context": {
        "cluster":"cluster2"
      }
    }
  ],
  "current-context": "context1"
}

And I'd like to update the clusters entry for cluster1 from:
{
  "name":"cluster1",
  "field":"field1"
}

to
{
  "name":"cluster1",
  "field":"field1",
  "proxy-url":"my-url"
}

First attempt
jq '. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o.clusters[] | select(.name == $context.context.cluster)
  | .proxy_id |= "my-url"'

gives me
{
  "name": "cluster1",
  "field": "field1",
  "proxy_id": "my-url"
}

-- great! But I need the rest of the object too.
Parentheses almost work
With parentheses, I can get the whole object back & add a "proxy-url" field to the active context, but I can't take it one step further to update the active cluster. This filter:
jq '(. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name)
  | ."proxy-url")
  |= "my-url"'

works mint:
{
  "clusters": [...],  // omitted for brevity, unchanged
  "contexts": [
    {
      "name": "context1",
      "context": {
        "cluster": "cluster1"
      },
      "proxy-url": "my-url"  // tada!
    },
    {...}  // omitted for brevity, unchanged
  ],
  "current-context": "context1"
}

Trying to take it one step further (to update the cluster identified by that context, instead):
jq '(. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o.clusters[] | select(.name == $context.context.cluster)
  | ."proxy-url")
  |= "my-url"'

gives me the following error:
jq: error (at <stdin>:26): Invalid path expression near attempt to access element "clusters" of {"clusters":[{"name":"clus...
exit status 5

How can I use the $context.context.cluster result to update the relevant clusters entry? I don't understand why this approach works for adding something to contexts but not to clusters.
Dirty solution
I can kludge together a new clusters entry & merge that with the top-level object:
jq '. as $o
  | $o."current-context" as $current_context_name
  | $o.contexts[] | select(.name == $current_context_name) as $context
  | $o + {"clusters": [($o.clusters[] | select(.name == $context.context.cluster)."proxy-url" |= "my-url")]}

but this feels a bit fragile.

A: This solution retrieves the active cluster using an INDEX construction, then just sets the new field directly without modifying the context:
jq '
  INDEX(.contexts[]; .name)[."current-context"].context.cluster as $cluster
  | (.clusters[] | select(.name == $cluster))."proxy-url" = "my-url"
'

{
  "clusters": [
    {
      "name": "cluster1",
      "field": "field1",
      "proxy-url": "my-url"
    },
    {
      "name": "cluster2",
      "field": "field2"
    }
  ],
  "contexts": [
    {
      "name": "context1",
      "context": {
        "cluster": "cluster1"
      }
    },
    {
      "name": "context2",
      "context": {
        "cluster": "cluster2"
      }
    }
  ],
  "current-context": "context1"
}

Demo


text:
Q: Sharing variables between classes in Java EE I'm developping a Java Web Application and I have some problems with sharing variables.
To the best of my knowledge, there is two ways :
(1) by using static variables, then each class can access to the given var,
(2) by using setter and getter.
I have an issue for each method. With the first one, all users (even with different session ids) will share the same values.
And, for the second one, access via getters force the program to use constructors and in this case we will loose the values we previously got for current user.
So, anyone can explain me how to share information only for a given sessionId?
To be more explicit :
I tried to seperate the model from the view aspect of my application. So, the package Model will contain all databases access or Web Service requests for example, and the View package will contain all servlet pages and user interactions with the programme.
When the user select an option, this information is stored in a public static var then the other classes can access. But conflicts occur when two users select two different options. Cause the variable is static...
I need a variable which can be shared between classes and keep its value only for a given user

A: I would use the HttpSession. You can set and get attributes.

A: Your first option listed, using static variables to store mutable state, doesn't work in a Java EE web application. You're right that different users on the same server will see the same values. In addition to that, if multiple instances of your application are deployed, the static variables on one server can contain different values from what they contain on another server, so if you have several boxes, each with an instance of your web application, and a load balancer in front of them sending requests round-robin, users can see different state for different requests. So you can exclude that option.
Your second option, "(2) by using setter and getter", isn't clear at all.
If you want to keep state where it is visible to only one user, you can put it in the HttpSession. Things stored in the HttpSession are specific to the logged-in current user. This is a temporary storage spot only, when the session times out the contents of the session go away. Putting too many things in the HttpSession can be a problem; it can take up a lot of memory, and can cause slowdowns in a clustered application as the nodes try to copy information between nodes to keep every server's session contents current. (An alternative is pinning users to a given server with the result that load is distributed unevenly.)
It can be preferable to keep user-specific information in the database. That way the data is in one place that is available to all instances of the application, you can cache it like any other data you get from the database, and your application can make sure only the appropriate user sees it. Also the data is persistent instead of going away when the session times out.


text:
Q: Is this the correct way to create and post a mutipart form data in CakePhp3? I am trying to post a mutipart form data in CakePhp3. The form should contain a few information about the user (text fields) and an image.
I'm doing something like this:
$request = [
  'fistname'=>$user->firstname,
  'lastname'=>'$user->lastname',
  '_session'=>'$session'
];

$form = new FormData();
foreach ($request as $key => $value) {
  $form->add($key,$request);
}
$file = $form->addFile('upload',fopen(WWW_ROOT.'img/picture.png','r'));
$file->contentId('mypicture'); // <-- not sure what this is
$file->disposition('attachment');

$response = $http->post(
  $url,
  (string)$form,
  ['headers' => ['Content-Type' => $form->contentType()]]
);

Is this the correct way to create and post a mutipart form data in CakePhp3?
Thanks for your help.
EDIT
If I post to my own server it seems to be working (thanks @Mary), but I get firstname and lastname replicated (this might be the problem):
object(Cake\Http\ServerRequest) {
trustProxy => false
...
[protected] data => [
    'fistname' => [
        'fistname' => 'Test',
        'lastname' => 'Test'
    ],
    'lastname' => [
        'fistname' => 'Test',
        'lastname' => 'Test'
    ],
    'upload' => [
        'tmp_name' => '/private/var/folders/g5/jjd1vc557bs21hq805lcxjk80000gn/T/phpAVXNqK',
        'error' => (int) 0,
        'name' => 'SELL5BAE2B6348272_gallery_1.png',
        'type' => 'image/png',
        'size' => (int) 200231
    ]
]
...

If I post to the API server it doesn't work.
I did the same with CURL and it works:
$filename = WWW_ROOT.'ufiles/medium/'.$img['image_1'];
$cFile = curl_file_create($filename);
$request = [
  '_operation'=>'uploadFile',
  'id'=>$ticket_id,
  '_session'=>$session,
  'file' => $cFile
];

try{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_URL,$this->crm['endpoint']);
  curl_setopt($ch, CURLOPT_POST,1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
  $response=curl_exec($ch);
  curl_close ($ch);
}catch(\Exception $e){
  $response = null;
}

A: Counterquestion: Does it work?
As you can see here, $file->contentId() sets the Content ID or part in a multipart form data request body:
https://github.com/cakephp/cakephp/blob/master/src/Http/Client/FormDataPart.php#L114
I'm not sure about this, but I don't think you have to set it as it doesn't seem to be required for multipart/form-data:
https://www.w3.org/TR/2006/REC-xforms-20060314/slice11.html#serialize-form-data

Edit
I did some testing and: It. works. Here is what I tried:
use Cake\Http\Client;
use Cake\Http\Client\FormData;

public function test() {

    $request = [
        'fistname'=>'Test',
        'lastname'=>'Test'
    ];

    $form = new FormData();
    $http = new Client();

    foreach ($request as $key => $value) {
        $form->add($key,$request);
    }
    $file = $form->addFile('upload',fopen(WWW_ROOT.'img/awards.png','r'));
    $file->contentId('mypicture'); // <-- not sure what this is
    $file->disposition('attachment');

    $response = $http->post(
      'http://www.testurl.dev/test',
      (string)$form,
      ['headers' => ['Content-Type' => $form->contentType()]]
    );
    var_dump($response);
    exit;
}

Output of var_dump($response):
object(Cake\Http\Client\Response)#150 (12) {
  ["code":protected]=>int(200)
  …
  ["headers":protected]=>array(12) {
    ["Date"]=>array(1) {
      [0]=>string(29) "Fri, 28 Sep 2018 12:44:31 GMT"
    }
    …
  }
}

Server access log output:
[28/Sep/2018:14:44:31 +0200] "POST /test HTTP/1.1" 200 6852 "-" "CakePHP"


text:
Q: Error 432 while exporting tables from word to excel I'm trying to export a word doc. tables to an excel file.
Expected result:

*

*export only the first row for every column (avoiding the rest of the table content)

*no space between tables

I tried with this but I get this 432 error on "Set wdDoc = GetObject(wdFileName)":
432 error
Can someone help me?
Sub Trouble()

    Dim word_app As Object, word_doc As Object, word_table As Word.Table, wdFileName As Variant, wdDoc As Object

    Set word_app = CreateObject("Word.Application")
    ActiveSheet.Calculate

    wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
    "Browse for file containing table to be imported")

    If wdFileName = False Then Exit Sub
    ActiveSheet.Range("A:A").ClearContents

    Set wdDoc = GetObject(wdFileName)
    word_app.Visible = True
    wdDoc.Activate

    excel_row = 1

    On Error Resume Next

    For Each word_table In wdDoc.Tables
        Err.Clear
        For i = 1 To word_table.Rows.Count

            For j = 1 To word_table.Columns.Count
                part = word_table.Rows(i).Cells(j).Range.Text
                part = Left(part, Len(part) - 1)
                part = Replace(part, vbNewLine, "")

                Sheet2.Cells(excel_row, j).Value = part
            Next j
            excel_row = excel_row + 1
        Next i
    Next word_table

    MsgBox "done"

    wdDoc.Save
    'word_app.Quit
    Set wdDoc = Nothing
    Set word_app = Nothing

End Sub

A: This works for me (just the word-related parts):
Sub Trouble()

    Dim word_app As Object, wdFileName As Variant, wdDoc As Object

    Set word_app = CreateObject("Word.Application")

    wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
                             "Browse for file containing table to be imported")

    If wdFileName = False Then Exit Sub

    Set wdDoc = word_app.documents.Open(wdFileName)
    word_app.Visible = True
    wdDoc.Activate

End Sub


text:
Q: getting min and max value from a column in vectors of vector I know how to get min and max value in a vector through iterators as shown below, But how about getting a min and max value of a matrix table in vectors of vector: for example i have:
vector<vector<float> > vec;

the above vector has a matrix (my program reads data from csv file and enters into these vectors of vector as a matrix) , such that i want to check a specific column in the vector of vector and find the min and max values in that particular column, keeping in mind that finding min and max from a specific column of a vector specified.
normal way to find min and max value in a single vector is :
int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

but what if the vector has another vector like  vector<vector<float> > vec;

A: You can use the second form of max_element and write your own compare functor like this:
template< class T >
struct ColumnAdapter {
    ColumnAdapter( size_t column ) : m_column( column ) {}
    bool operator()( const std::vector< T > & left, const std::vector< T > & right ) {
        return left.at( m_column ) < right.at( m_column );
    }
private:
    size_t m_column;
};

int main() {
    std::vector< std::vector< int > > v = {
        { 2,  3, 4, 5, 6, 7 },
        { 1,  2, 3, 4, 5, 6 },
        { 20, 30, 40, 50, 60, 70 },
        { 2,  3, 4, 5, 6, 7 },
    };
    const size_t COLUMN = 1;
    auto biggest = std::max_element(std::begin(v), std::end(v), ColumnAdapter< int >( COLUMN ) );
    std::cout << "Max element is " << (*biggest).at( COLUMN )
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v), ColumnAdapter< int >( COLUMN ) );
    std::cout << "min element is " << (*smallest).at( COLUMN )
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
    return 0;
}

Output:

Max element is 30 at position 2
min element is 2 at position 1

live demo

A: One option is to override the the < used with a lambda expression like:
size_t col = 1; // tells which column to check
auto comp = [&] (const vector<float> &a, const vector<float> &b)
{
    return a[col] < b[col];
}

//usage

auto max = max_element(mat2d.begin(), mat2d.end(), comp);
float max_val = (*max)[col];


text:
Q: Angular UI Router - Views in an Inherited State edit: Based on the answer by @actor2019 I want to update my question to better explain the problem:
Using Angular UI-Router(v0.0.2), I've setup the app to properly navigate between main "pages"/state, while inheriting the base state.
Index.html:

base.html:

The issue is here in the app.js file. When I add the views parameter to the base state, everything stops working(100% blank page). Without that parameter, the page renders correctly, but I have no search view.
app.js:
$urlRouterProvider.otherwise('/');

//
// Now set up the states
$stateProvider
  .state('base', {
    abstract: true,
    templateUrl: 'views/base.html',
    views: {
      "search": {
        templateUrl: "views/search.html"
      }
    }
  })
  .state('base.home', {
    url: "/",
    templateUrl: "views/home.html"
  })
  .state('base.page2', {
    url: "/page2",
    templateUrl: "views/page2.html"
  });

How do I add views to this parent 'base' state?

UPDATE:
The problem with @actor2019's answer here is that the search view gets reinitialized when the state changes. I'd like the views off the base level to persist through state changes.

A: The Child state should be home.search instead of header.search. In your case, you may want to write some abstract state to hold the layout,
base.html

in app.js
$stateProvider
    .state('base',{
        abstract:true,
        url:'/',
        templateUrl: viewBase+'base.html'
    })
    .state('base.main',{
        url:'',
        views:{
            "logo":{
                templateUrl:viewBase+'main/logo.html'
            },
            "menu":{
                templateUrl:viewBase+'main/menu.html'
            },
            "sidebar":{
                templateUrl:viewBase+'main/sidebar.html'
            },
            "entry":{
                templateUrl: viewBase+'main/entry.html'
            }
        }})

A: According to the ui-router documentation, when the application is in a particular state—when a state is "active"—all of its ancestor states are implicitly active as well. So, for example, when the "contacts.list" state is active, the "contacts" state is implicitly active as well, because it's the parent state to "contacts.list". Child states will load their templates into their parent's ui-view. I'd reccomend looking over the section of their documentation entitled Nested States & Views to gain a fuller understanding of how to do this.
In the code you have provided us here, the parent state of the search template is home, while
.state('header.search', {
    templateUrl: "views/search.html",
    controller: "SearchCtrl"
})

implies that the parent state of the search template should be header in order for the view to get loaded correctly. So, I believe the following changes to your app.js will fix your issue.
app.js
$stateProvider
  .state('home', {
    url: "/",
    views: {
      '': {
        templateUrl: "views/mainContent.html",
        controller: "MainCtrl"
      },
      'header': {
        templateUrl: "views/header.html"
      },
      'footer': {
        templateUrl: "views/footer.html"
      },
    }
  })
  .state('home.search', {
    views: {
      'search': {
        templateUrl: "views/search.html",
        controller: "SearchCtrl"
      }
  })
  .state('anotherPage', {
    url: "/anotherPage",
    templateUrl: "views/anotherPage.html"
  });

A: The first obvious mistake:
You can't specify controller and template on the state while your using views. They are mutually exclusive...
This is because when there is no "views" but a controller and template on the state, UI-Router automatically creates the "views" property and pulls those properties to an "empty" view...
.state('base', {
  abstract: true,
  templateUrl: 'views/base.html', //Can't do this
  views: { // when this is there.
    "search": {
      templateUrl: "views/search.html"
    }
  }
})

Instead do:
.state('base', {
  abstract: true,
    views: {
      "": {
        templateUrl: 'views/base.html'
      },
      "search": {
        templateUrl: "views/search.html"
      }
    }
  })

Second problem:
How views targeting works with nested views etc. is not very logical, it may work well if you restrict your self to one view in one view all the way down, but ones you start working with multiple named views it all gets confusing... Add unnamed views on top and many people gets lost...
The way views work in UI-Router is the worst part of UI-Router...
Given you example I am not even entirely sure of the way to target the search view from your abstract parent state... Might be:
.state('base', {
  abstract: true,
    views: {
      "": {
        templateUrl: 'views/base.html'
      },
      "search@base": {
        templateUrl: "views/search.html"
      }
    }
  })

If it can even be made to work... Alternatively you can move the search view out of base.html, but I guess you added it in there for a reason.
The whole view concept is the biggest reason why I ended up writing https://github.com/dotJEM/angular-routing instead.

A: This works for me.
$stateProvider
    .state('base', {
      abstract: true,
      url:'/',
      templateUrl: 'views/base.html'
    })
    .state('base.home', {
      url: "",
      views: {
      "search@base": {
        templateUrl: "views/searchOfHome.html"
      }
      //content@base, contentOfHome.html
    }
    })
    .state('base.page2', {
      url: "page2",
      views: {
      "search@base": {
        templateUrl: "views/searchOfPage2.html"
      }
      //content@base, contentOfPage2.html
    });

If 'base' is the root state, you don't need the '@base'


text:
Q: Why is a --new-branch flag needed? Isn't this a normal workflow?
[default] $ hg branch foo

[foo] $ [... some commits ...]

[foo] $ hg update default

[default] $ hg merge foo

[default] $ hg commit -m "merged foo"

[default] $ hg push
abort: push creates new remote branches: foo!
(use 'hg push --new-branch' to create new remote branches)

What is the otherwise ideal way to do branching → merging → pushing?

A: The mercurial philosophy is that you should not be pushing things which make it harder for other users of the repository. Relevant to this question is that multiple heads make it harder for other developers, since they would then need to merge your changes. Hence by default pushing new heads is rejected by the server. The -f option was used to allow pushing new heads.
However, the case of pushing a new named branch is quite different conceptually to pushing a new head on the same branch. Many workflows (including mine) do each task on a separate named branch. The --new-branch option allows you to push up a new branch, whilst rejecting new heads on existing branches. It's also different (as you've seen) because it's needed even if the new branch does not create a new head (due to merging).
My personal feeling is that new branches should be allowed by default, but the mercurial developers prefer otherwise.

A: This is a one-time thing. Just use --new-branch the first time you push a (new) branch. It's normal.
Every other push can remain as hg push, no --new-branch flag.

A: That depends on what the branch is used for.
Is it used internally in your own repository clone it would be appropriate to commit your changes to your branch as long as you develop on your feature decoupled from the others.
After you finished you'll have to invest some work to keep track on the efforts of other people who may have done changes on the default branch
Then you should update in their changes, resolve the conflicts commit your part.
Switch over to default and make your feature part of the default branch by merging in your changes. Now you can close your branch, commit the stuff and push it!


text:
Q: Running yasca tool from Runtime.getRunTime.exec() is taking more time than executing through command line Code below shows How I am executing yasca through java. Process starts but it is taking longer time than command line execution, which takes less than a minute.Even I tried using ProcessBuilder but it is also taking more time as Runtime.getRunTime().exec
            String[] command = {"cmd.exe", "/c","cd \"F:\\Security Tools\\yasca\" && F: &&     yasca \"F:\\Security Tools\\HacmeBooks\" --output \"F:\\index\""};

            p = Runtime.getRuntime().exec(command);


text:
Q: qtconsole not rendering pandas dataframes as html notebook_repr_html option I recently upgraded my version of pandas. I have the latest stable version installed now:
pd.__version__
Out[5]: '0.10.1'

prior to this upgrade, this is how dataframes were displayed in the qtconsole shell (this isn't my screenshot but simply one i found on the web).

The latest version of pandas also uses a different approach to setting the display options.
Rather than using pd.set_printoptions, pandas wants you to use the set_option configs like this:
pd.set_option('display.notebook_repr_html', True)

After upgrading my pandas version, qtconsole no longer renders dataframes as html tables.
An example:
import numpy as np
import pandas as pd

pd.set_option('display.notebook_repr_html', True)
pd.set_option('display.expand_frame_repr', True)
pd.set_option('display.precision', 3)
pd.set_option('display.line_width', 100)
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_colwidth', 15)

When I create a DataFrame...
f = lambda x: x*np.random.rand()
data = {"a": pd.Series(np.arange(10) ** 2 ),
        "b": pd.Series(map(f, np.ones(10))) }
df = pd.DataFrame(data)
df

This is what I see in the qtconsole shell:
Out[4]:
    a     b
0   0  0.15
1   1  0.74
2   4  0.81
3   9  0.94
4  16  0.40
5  25  0.03
6  36  0.40
7  49  0.43
8  64  0.56
9  81  0.14

You can check how your display configs are currently set:
opts = ["max_columns",
        "max_rows",
        "line_width",
        "max_colwidth",
        "notebook_repr_html",
        "pprint_nest_depth",
        "expand_frame_repr" ]

for opt in opts:
    print opt, pd.get_option(opt)

Out[5]
max_columns 10
max_rows 50
line_width 100
max_colwidth 15
notebook_repr_html True
pprint_nest_depth 3
expand_frame_repr True

What am I missing in order to render the prettified html tables in qtconsole?

A: As far as I know, the notebook_repr_html option only applies to the actual IPython Notebook and not the QTConsole.
In the QTConsole, you can do:
from IPython.display import HTML
import numpy as np
import pandas

df = pandas.DataFrame(np.random.normal(size=(75,5)))
HTML(df.to_html())

One problem you might encounter is if the HTML is too long for your QTConsole's buffer. In that case nothing will show up, in my experience.


text:
Q: Unable to connect to Embedded Derby Database I am developing a java desktop application with Java Embedded DB integrated into the NetBeans 7.2 IDE
 The database was created using the IDE and it is separate from the front end for now.
 Now I want to connect the database to the front end. When I try, it gives me a server not found error. below are codes snippets.
 static final String host   = "jdbc:derby:Wa_Poly";
 static final String uName  = "chief";
 static final String uPass  = "12345";

the code for the connection is :
    /* Connecting to the database */
    Connection  con = DriverManager.getConnection(host, uName, uPass);
    Statement stmt2 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    String sql = "SELECT * FROM APP.ALUMNUS";
    ResultSet rs = stmt2.executeQuery(sql);
    populateIndex(rs, Scrollable);

this is the error given:
Jul 17, 2014 2:40:40 PM SearchEngine.SearchDB searchDatabase
SEVERE: null
java.sql.SQLException: Database 'Wa_Poly' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection30.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at SearchEngine.Index.buildIndex(Index.java:118)
at SearchEngine.SearchDB.searchDatabase(SearchDB.java:96)
at wa_poly.MyJFrame.<init>(MyJFrame.java:47)
at wa_poly.MyJFrame$5.run(MyJFrame.java:292)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

Caused by: java.sql.SQLException: Database 'Wa_Poly' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown

Source)
    ... 32 more
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SearchEngine.SearchDB.searchDatabase(SearchDB.java:105)
at wa_poly.MyJFrame.<init>(MyJFrame.java:47)
at wa_poly.MyJFrame$5.run(MyJFrame.java:292)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

any idea to solve the problem is welcomed.

A: this is not enough :

jdbc:derby:Wa_Poly

for a embedded connection must be something like

jdbc:derby:C:/Dokumente und
  Einstellungen/Administrator/.netbeans-derby/Wa_Poly

look at my answer here
embedded Derby
EDIT
Right click Services -> JavaDB -> create database
look where your database folder is.


text:
Q: Loading Bootstrap in Joomla - JUI or local copy? I'm creating a template for Joomla 3.x using Bootstrap. I am aware of the fact that Bootstrap can be loaded or unloaded selectively. But I am torn as whether to use the built in JUI version or a local copy bundled with my template. Here's the pros and cons as I see them...
Using the JUI version:

*

*Unknown version

*Could change at any time in the future - for example to Bootstrap version 3 and break my template

*Consistent with the version used by the latest and upcoming extensions

Using a Template (local) Version:

*

*Controllable and static - no surprises

*Might not benefit from any Bootstrap "fixes" the Joomla guys have added

Does anybody have any experiences or advice for me? Should I go with JUI version or load my own? Anybody know how long Joomla plan on keeping the current version of Bootstrap?
And, just to be certain, I am right in saying that versions of Joomla prior to version 3 wont have Boostrap by default and so my template would not be backwards compatible without loading my own version anyway right?

A: Bootstrap will most likely be used for Joomla in the long term. It all depends on which version of Bootstrap you want to use to be honest. Joomla 3.x uses Bootstrap 2.x and the latest version of it is 3.0.0 which is rather a big difference in design.
If you plan in using Bootstrap 3, then you will need to include it with the template. If you plan on using 2.x, then it might be an idea to have a parameter so the user can select whether they load it from your template or from the Joomla core.
Some may say this is pretty pointless, however it's always good to have an option, just incase some users may have edited the core Bootstrap files or even removed them for some odd reason.
And yes, you're right in saying that versions of Joomla prior to version 3 wont have Boostrap by default, so even more of a reason to provide a parameter, as I gather you're making a template for Joomla 2.5 and 3.x
Hope this helps


text:
Q: JSON.NET JObject key comparison case-insensitive I'm using Newtonsoft Json.net to parse the JSON string. I convert the string into the JObject. When access the value of the element by the key, I want to the comparison is case-insensitive. In the code below, I use "FROM" as the key. I want it returns string "1" at the line json["FROM"].ToString(). But it fails. Is it possible to make the code below work?
String ptString = "{from: 1, to: 3}";
var json = (JObject)JsonConvert.DeserializeObject(ptString);

String f = json["FROM"].ToString();

A: c# allows you to use dictionaries with keys that are case insensitive, so a workaround I've used is to convert the JObject to a dictionary with StringComparer.CurrentCultureIgnoreCase set, like so:
JObject json = (JObject)JsonConvert.DeserializeObject(ptString);
Dictionary<string, object> d = new Dictionary<string, object>(json.ToObject<IDictionary<string, object>>(), StringComparer.CurrentCultureIgnoreCase);

String f = d["FROM"].ToString();

A: This should work:
var json = @"{UPPER: 'value'}";
var jObj = JObject.Parse(json);
var upper = jObj.GetValue("upper", StringComparison.OrdinalIgnoreCase)?.Value<string>();

Console.WriteLine(upper); // value


text:
Q: Check password expiration or days to expire in WSO2 Identity Server I am using WSO2 Identity Server (5.1.) using MySQL as my DB for users & roles. I with to use some password expiration check on authentication or at least to be able to query time for expiration or if had expired.
I have set these in repository/conf/identity/identity-mgt.properties:
Authentication.Policy.Enable=true

Authentication.Policy.Check.Account.Exist=false
Authentication.Policy.Check.Account.Lock=false
Authentication.Policy.Check.OneTime.Password=false
Authentication.Policy.Check.Password.Expire=true

Authentication.Policy.Password.Expire.Time=2

However, I can't get to use this. RemoteUserStoreManagerService / getPasswordExpirationTime always return -1. What should I configure or what API should I use to extract expiration true/false or when password will expire?

A: These two properties had been introduced initially to IS planning to support password expiry, but the implementation was never done.
if Authentication.Policy.Check.Password.Expire is set to true, then the when the user updates the password, timestamp of password update is set as a user claim.
But Authentication.Policy.Password.Expire.Time is not logically used anywhere in the code base, and ideally should be removed.
Anyways, you can achieve the same functionality in a different way using password policy authenticators in IS. Hope this helps


text:
Q: vlc : how to specify playlist on command line The playlist is a plain text file of filenames
I have tried :
 cvlc --playlist playlist
 cvlc -playlist playlist

And each of those with playlist=playlist.
I have renamed the playlist to playlist.m3u
I have tried :
 vlc --longhelp | grep playlist

And see nothing but options for a running playlist.
My web searches have lots on how to use the GUI for a playlist but not for the commandline.
This used to work but I haven't used VLC for a while.

A:
The playlist is a plain text file of filenames

It needs to be a .m3u list and it will look like this example:
# This is a comment
/music/opeth/white cluster.mp3
/music/moonlapse vertigo.mp3
http://ccmixter.org/a/song.mp3
/video/mononoke.avi

and you play them without any parameters like:
vlc playlist.m3u

The only issue I can see here is that the files are not correct in your file.


text:
Q: How can I get a list of models from the collection that have changes since constuction If I initialize a collection with an array of objects for the model attributes when a dialogview is initialized. Then the dialog view that lets the user edit the list updates those model values with calls to model set. When the dialog's ok button is clicked, Does backbone provide a way to get the list of only those models that changed since the collection was created/initialized?

A: There are various model methods that look tempting:

*

*Model#hasChanged

*Model#changedAttributes

*Model#previous

*Model#previousAttributes
But don't be fooled, those only apply while a "change" event is being triggered:

Note that this method, and the following change-related ones, are only useful during the course of a "change" event.

so they're useless after the event has been triggered and handled.
I think you have to track which models have changed yourself. You can do this on the collection itself without too much effort since

Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience.

and the collection can bind to its own events. For example, you could have something like this in your collection:
Backbone.Collection.extend({
    initialize: function() {
        this.delta = { };
        this.on('change', this._a_model_has_changed);
    },
    changed_models: function() {
        return _.chain(this.delta).values();
    },
    _a_model_has_changed: function(m) {
        this.delta[m.id] = m;
    }
});

Then you could get the models that have changed by calling collection.changed_models(). You'd want to listen for other events as well so that you could update this.delta when models are deleted or synced with the server; the above is just for illustration. If you didn't want an Underscore object returned you could use this instead:
changed_models: function() {
    return _(this.delta).values();
}

but being able to collection.changed_models().each(function() { ... }) is convenient.
Demo: http://jsfiddle.net/ambiguous/8PQh9/
You could also let the models track their own dirtiness through a similar set on the models. Then you could do something like this:
collection.filter(function(m) { return m.is_dirty() });

where, of course, is_dirty would return true if the model had been changed.


text:
Q: CodeIgniter Models & Controllers Confusion Today i've decided that I should start relying on a PHP framework because writing from scratch every time is really exhausting. As my framework I've chosen CodeIgniter, and I want to say It's amazing and easy to use. But I have some questions and confusion all over. I'm not pretty sure how to structre my website since I don't know when to use Models, and when to use Controllers.What I have right now is:

Pages Controller
// PAGES CONTROLLER
// As its name, this controller simply loads pages by a url query.
class Pages extends CI_Controller {
    /*
     * Constructor - loads the variables model.
     */
    public function __construct() {
        parent::__construct ();
        $this->load->model ( 'variables' );
    }
    /*
     * Displays a page by its name.
     */
    public function view($page = 'home') {
        if (! file_exists ( "application/views/pages/$page.php" )) {
            show_404 ();
        }
        $data ['title'] = ucfirst ( $page );
        $data ['variables'] = $this->variables;

        $this->load->view ( "templates/header", $data );
        $this->load->view ( "pages/$page", $data );
        $this->load->view ( "templates/footer", $data );
    }
}

Variables Model
// VARIABLES MODEL
// Used like a "mysql variables", all the data is taken from a table contains 2
// rows: id and value. and those variables are mostly used for site settings.
class Variables extends CI_Model {
    /*
     * Constructor, simply loads the database.
     */
    public function __construct() {
        $this->load->database ();
    }
    /*
     * Gets a variable stored in the database.
     */
    public function get($id) {
        $query = $this->db->get_where ( 'variables', array (
                'id' => $id
        ) );
        return $query->row_array ()["value"];
    }
    /*
     * Sets a variable stored in the database.
     */
    public function set($id, $value) {
        $this->db->where ( 'id', $id );
        $this->db->update ( 'variables', array (
                'value' => $value
        ) );
    }
}

Am I using the correct hierarchy? Is there something I could change?
Now for my main question: lets say for example that I want to add a membership functionality for my websites. Should I do the following? :
Member Controller - Managing the current member, and all the forms actions are leading to this controller which communicates with the Members model(see below).
Members model - Handles all the database handling, functions like: login, register, getMember.

A: I just want to suggest in your controller you can do this in two lines:
    $this->load->view ( "templates/header", $data );
    $this->load->view ( "pages/$page", $data );
    $this->load->view ( "templates/footer", $data );

Since you can load your view inside a view then you can try: In your view e.g template.php
    $this->load->view('templates/header');
    $this->load->view($main_content);
    $this->load->view('templates/footer');

And you might want your controller on not having too much code because all heavy task should be in your model  so in your controller :
   $data['main_content'] = $page;
    $this->load->view('templates/template',$data);


text:
Q: Cant figure out how to use lists in the constructor and edit the value This is my blueprint script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Blueprint

{
     public string craftedItemName;
     public string craftedUnits;
     public int minNeeded;
     public string neededItemsUnits;
     public List<string> resourcesList = new List<string>();

     public Blueprint(string name,string craftunits,int minneed,string needunits,List<string> resList)
     {
        craftedItemName = name;
        craftedUnits = craftunits;
        minNeeded = needunits;
        neededItemsUnits = needunits;
        resourcesList = resList;
     }

And in my crafting script i have
//other code
public Blueprint GlBeBLP = new("Glass Beaker","Units",1,"Kg",*Here i dont know how to say Glass*);
//other code

I know i could just use a string because its just one item but i need it to be a list for future items that will need more than one resource any help or suggestions would be greatly appreciated.
I have tried resList.Add("Glass") but didnt work, i have tried just glass and converting it to a list with a cast but didnt work and didnt expect it to but yeah i cant figure it out alone and have searched on the web but cant find one that helps with my case.

A: You would need to pass in a new List<string> as your last parameter of your constructor, with one item, "Glass", so you could do so in the following way:
   public Blueprint GlBeBLP = new("Glass Beaker","Units",1,"Kg",
        new List<string> { "Glass" });


text:
Q: Make text appear entirely inside div I'm trying to have my text inside the 'container' div show up entirely but it seems to get cut off? .. It works if there is only a bit of text but if the text is more than 1 page it will cut it off.. Also the page seems to load very long because of the background image (defined in stylesheet.css) How do I fix this the best ? Thanks in advance!

* {
  box-sizing: border-box;
}

@font-face {
 font-family: 'zcool';
 src:  url('fonts/zcool.ttf') format('ttf');
 local:  url('fonts/zcool.ttf') format('ttf');
 font-weight: normal;
 font-style: normal;
}

html,
body {
  height: 100%;
  width: 100%;

}

body {
 padding: 0;
 margin: 0;
 border: 0;
 background-attachment: fixed;
 background-size: 100% auto;
 background-image: url("img/bg.png");
 background-repeat: no-repeat;
 background-size: 100% 100%;
}

@media (max-width: 768px) {  /* when screen size is < 768px apply the following styles */
  body {
    padding: 0;
 margin: 0;
 border: 0;
 background-attachment: fixed;
 background-size: 100% auto;
 background-image: url("img/bgm.png");
 background-repeat: no-repeat;
 background-size: 100% 100%;
  }
}

ul#horizontal-list {
  list-style: none;
}

ul#horizontal-list li {
  display: inline;
}

ul {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

li {
  float: center;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 16px;
  text-decoration: none;
}

li a:hover {
  background-color: red;
}

.navbar {
 position: fixed;
 top: 0;
 height: 50px;
 width: 100%;
 background-color: black;
 color: white;
 text-align: center;
 left: 0;
 right: 0;
 z-index: 1;
}

.navbar ul {
  display: flex;
  align-items: center;
  justify-content: center;
  list-style-type: none;
  margin-top: 0px;
}

.header {
 background-image: url(img/j.svg);
 background-repeat: no-repeat;
 background-size: 100% 100%;
 height: 100%;
 width: 100%;
 margin-top: 10%;
    margin-bottom: 10%;
}

@media (max-width: 768px) {  /* when screen size is < 768px apply the following styles */
  .header {
    background-image: url("img/johnswork-mobile.svg");
 background-repeat: no-repeat;
 background-size: 100% 100%;
 height: 100%;
 width: 100%;
 margin-top: 10%;
    margin-bottom: 10%;
  }
}

.body {
 height: 100%;
 width: 90%;
 margin: auto;
 padding: 0;
 border: 0;
 color: black;
 padding-left: 5%;
 padding-right: 5%;
 overflow: hidden;

 /*background-color: grey;*/
}

.johnswork {
 background-image: url(img/johnswork.svg);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 20%;
    width: 100%;
    margin-bottom: 5%;
}

.content {
 margin: auto;
 height: 100%;
 width: 90%;
 background-color: white;
 color: black;
 border-right: double;
 border-left: double;
 box-shadow: 0px -21px 28px 7px rgb(162, 27, 27);
 text-align: justify;
 font-size: 20px;
 padding-top: 2%;
 padding-bottom: 10%;
 padding-left: 5%;
 padding-right: 5%;
}

@media (max-width: 768px) {  /* when screen size is < 768px apply the following styles */
  .content {
    margin: auto;
 height: 100%;
 width: 90%;
 background-color: white;
 color: black;
 border-right: double;
 border-left: double;
 box-shadow: 0px -21px 28px 7px rgb(27, 125, 162);
 text-align: justify;
 font-size: 20px;
 padding-top: 2%;
 padding-bottom: 10%;
 padding-left: 5%;
 padding-right: 5%;
  }
}

.social {
 margin: auto;
 display: flex;
 justify-content: center;
}

.me {
 float: left;
 margin-right: 3%;
 height: 100%;
}

.footer {
  height: 50px;
  width: 72%;
  background-color: black;
  color: white;
  vertical-align: middle;
  margin: auto auto 50px;
}

#copyright {
 display: table;
}

#cpy{
    display: table-cell;
    vertical-align: middle;
}
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" href="stylesheet.css"/>

  <link rel="icon" type="image/x-icon" href="img/favicon.ico"/>
  <meta name="description" content="My Personal Portfolio">
  <title>John's Work</title>

HOME

ABOUT

CONTACT

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac ipsum non diam faucibus dignissim. Praesent a dolor tincidunt, rutrum diam ut, convallis orci. Maecenas eleifend, sapien id blandit rutrum, enim augue cursus magna, vitae varius orci nulla eu arcu. Cras ultrices condimentum libero nec vulputate. Praesent id ante dignissim, congue elit id, iaculis eros. Aliquam lacus quam, facilisis et pulvinar quis, hendrerit varius erat. Duis feugiat imperdiet lobortis. Ut et faucibus dui. Integer quis bibendum tortor, at mattis dolor. Sed id lacus nec nisi iaculis blandit. Duis nec ligula orci. Quisque tincidunt, orci id tincidunt consequat, eros erat dictum urna, vel ultricies sem nisl eu nunc. Nulla facilisi. Suspendisse at malesuada magna, in suscipit purus.

   Fusce facilisis pharetra dui, ut cursus orci maximus non. Cras nec magna ac odio ornare ornare. Proin id commodo eros. Phasellus dui est, malesuada non mi sit amet, fringilla rhoncus ante. Phasellus non elit id est cursus malesuada. Maecenas accumsan erat in urna pulvinar, sit amet egestas felis facilisis. Nullam tincidunt porta nulla, a consectetur sapien venenatis in. Phasellus elementum est sit amet sem accumsan tincidunt. In semper vulputate risus, sed sollicitudin libero consectetur eget. Curabitur pulvinar eleifend augue. Sed facilisis ligula sed arcu vulputate tempus.

   Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut mi nisi, mattis sed est a, luctus aliquet metus. Integer fringilla, massa nec laoreet dapibus, odio sem convallis massa, a vestibulum tellus mi in massa. Sed at vulputate velit, id sagittis sem. Vestibulum ac libero massa. Vivamus et libero vel orci auctor sodales a a quam. Vivamus semper tortor eget lacus euismod, non dignissim tellus feugiat. Donec tincidunt nisi at ornare ullamcorper. Nulla at mi nulla. Phasellus ligula ante, vehicula sit amet mauris et, consectetur mollis odio.

   Donec massa risus, ultricies et enim quis, vestibulum consectetur arcu. Nunc sed convallis dui, sagittis imperdiet metus. Sed non ultrices velit. Nullam arcu sem, varius non pulvinar id, convallis eget erat. Nam porta tincidunt lorem, non venenatis sapien hendrerit vitae. Suspendisse nec est leo. Nunc commodo, lectus nec facilisis laoreet, ex velit dapibus dui, et aliquet lacus est non velit. Vestibulum nisl velit, tempor vel lacus at, ultricies pellentesque nisi. Mauris velit tortor, aliquam a magna eget, efficitur fringilla erat. Praesent massa nisl, maximus sit amet viverra in, varius vel urna.

   Pellentesque eget leo vitae neque dictum egestas at ullamcorper nulla. Aenean lacinia venenatis metus, in faucibus dolor sollicitudin eget. Sed volutpat sit amet urna vel molestie. Donec dignissim velit tortor, a blandit ligula commodo dapibus. Vestibulum ac dolor facilisis mauris maximus mattis. Nullam vitae libero ut ligula sodales accumsan et vel dui. Quisque dapibus, lacus accumsan interdum efficitur, tellus augue maximus ipsum, quis ultricies dolor justo in diam. Pellentesque id lobortis diam. Suspendisse mollis eget orci eu auctor. Nullam porttitor arcu mi, nec varius magna viverra quis. Fusce eleifend sodales turpis et hendrerit.

© DA COSTA JOAO (2019)

A: Getting rid of
html,
body {
  height: 100%;
}

Seems to fix the problem of the text getting cut off.

A: I am assuming you want an image with text going around it. You can try this out!

  .image-container {
  float: left;
  margin: 0px 20px 5px 0px;

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ac ipsum non diam faucibus dignissim. Praesent a dolor tincidunt, rutrum diam ut, convallis orci. Maecenas eleifend, sapien id blandit rutrum, enim augue cursus magna, vitae varius orci nulla
    eu arcu. Cras ultrices condimentum libero nec vulputate. Praesent id ante dignissim, congue elit id, iaculis eros. Aliquam lacus quam, facilisis et pulvinar quis, hendrerit varius erat. Duis feugiat imperdiet lobortis. Ut et faucibus dui. Integer
    quis bibendum tortor, at mattis dolor. Sed id lacus nec nisi iaculis blandit. Duis nec ligula orci. Quisque tincidunt, orci id tincidunt consequat, eros erat dictum urna, vel ultricies sem nisl eu nunc. Nulla facilisi. Suspendisse at malesuada magna,
    in suscipit purus. Fusce facilisis pharetra dui, ut cursus orci maximus non. Cras nec magna ac odio ornare ornare. Proin id commodo eros. Phasellus dui est, malesuada non mi sit amet, fringilla rhoncus ante. Phasellus non elit id est cursus malesuada.
    Maecenas accumsan erat in urna pulvinar, sit amet egestas felis facilisis. Nullam tincidunt porta nulla, a consectetur sapien venenatis in. Phasellus elementum est sit amet sem accumsan tincidunt. In semper vulputate risus, sed sollicitudin libero
    consectetur eget. Curabitur pulvinar eleifend augue. Sed facilisis ligula sed arcu vulputate tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut mi nisi, mattis sed est a, luctus aliquet metus. Integer
    fringilla, massa nec laoreet dapibus, odio sem convallis massa, a vestibulum tellus mi in massa. Sed at vulputate velit, id sagittis sem. Vestibulum ac libero massa. Vivamus et libero vel orci auctor sodales a a quam. Vivamus semper tortor eget lacus
    euismod, non dignissim tellus feugiat. Donec tincidunt nisi at ornare ullamcorper. Nulla at mi nulla. Phasellus ligula ante, vehicula sit amet mauris et, consectetur mollis odio. Donec massa risus, ultricies et enim quis, vestibulum consectetur arcu.
    Nunc sed convallis dui, sagittis imperdiet metus. Sed non ultrices velit. Nullam arcu sem, varius non pulvinar id, convallis eget erat. Nam porta tincidunt lorem, non venenatis sapien hendrerit vitae. Suspendisse nec est leo. Nunc commodo, lectus
    nec facilisis laoreet, ex velit dapibus dui, et aliquet lacus est non velit. Vestibulum nisl velit, tempor vel lacus at, ultricies pellentesque nisi. Mauris velit tortor, aliquam a magna eget, efficitur fringilla erat. Praesent massa nisl, maximus
    sit amet viverra in, varius vel urna. Pellentesque eget leo vitae neque dictum egestas at ullamcorper nulla. Aenean lacinia venenatis metus, in faucibus dolor sollicitudin eget. Sed volutpat sit amet urna vel molestie. Donec dignissim velit tortor,
    a blandit ligula commodo dapibus. Vestibulum ac dolor facilisis mauris maximus mattis. Nullam vitae libero ut ligula sodales accumsan et vel dui. Quisque dapibus, lacus accumsan interdum efficitur, tellus augue maximus ipsum, quis ultricies dolor
    justo in diam. Pellentesque id lobortis diam. Suspendisse mollis eget orci eu auctor. Nullam porttitor arcu mi, nec varius magna viverra quis. Fusce eleifend sodales turpis et hendrerit.

A: As for the text cutting off, the below css seems to fix it without cutting off the image.
.body{
    height: auto;
}

As for the background image, it may be the file size. I usually use https://compressor.io/ to reduce my file sizes while maintaining image quality.


text:
Q: Android Broadcast Security: Custom Permission AND Specific Receiver Class? I'm reading up on Android Security when sending broadcasts, and came across these very helpful notes from a talk: https://defcon.org/images/defcon-19/dc-19-presentations/O%27Neil-Chin/DEFCON-19-O%27Neil-Chin-Google-Android.pdf
In the part about unauthorized intent receipt, two possible measures are suggested:
Intent i = new Intent();
i.setClassName("some.pkg.name", "some.pkg.name.TestDestination");

OR
Intent i = new Intent();
i.setAction("my.own.action");
sendBroadcast(i, "my.own.permission");

I don't see how those two are mutually exclusive. Is there a reason not to do both if I can, for extra security? In my particular case, since I know the target app/package/class, the first is a given, but I'm wondering if anything should keep me from implementing the second one as well.


text:
Q: Dependency Injection in Spring? How can we know if spring framework is using constructor based dependency injection or setter method based dependency injection, when both the constructor and setter method is defined?
for example.. I have two java classes as follows..
TextEditor.java
public class TextEditor {
    private SpellChecker spellChecker;

    TextEditor(SpellChecker spellChecker){

       this.spellChecker = spellChecker;
    }

    public void setSpellChecker(SpellChecker spellChecker) {

      this.spellChecker = spellChecker;
    }

   // a getter method to return spellChecker
    public SpellChecker getSpellChecker() {
      return spellChecker;
    }

    public void spellCheck() {
      spellChecker.checkSpelling();
    }
}

and
SpellChecker.java
public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

in configuration file, pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean using inner bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <property name="spellChecker">
         <bean id="spellChecker" class="SpellChecker"/>
       </property>
   </bean>

</beans>

now, how can we know that spring has added dependency using Constructor or using Setter method?

A: When using a <property>, spring injects dependencies via setter.
If you want to inject it via constructor, you use <constructor-arg>.
Also see: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators

A: It is all about developer choice how does he/she configure spring to inject dependency.
Since everyone could write big wall of text about how Dependency Injection works you should see/read this:
http://www.journaldev.com/2410/spring-dependency-injection-example-with-annotations-and-xml-configuration


text:
Q: How to get React state array to permanently update I'm learning Node and React and now know how to integrate them and am working on making registration and login using Node and React. I'm going step by step, so currently I'm trying to at least get the inputs and put them into state as an array, and then after I get that I will go to hashing the password, sending the data to Node and the database, et cetera.
At the moment however, I'm a little bit stuck here. I'm trying to enter the username and password into my "details" state and then render it on the screen (or console log it, or whatever), but when I do it it shows up very quickly and then disappears. Why is the details state reverting to an empty array? How do I fix it? I did some research on here but couldn't figure it out.
import { useState } from 'react';

function App() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [details, setDetails] = useState([]);

  const readUsername = (e) => {
    setUsername(e.target.value);
  }

  const readPassword = (e) => {
    setPassword(e.target.value);
  }

  const updateDetails = () => {
    setDetails([username, password]);
  }

  return (

Register

      <form>
        Username:
        <input htmlFor="username" name="username" onChange={readUsername} />

        Password:
        <input htmlFor="password" name="password" type="password" onChange={readPassword} />

        <button onClick={updateDetails}>Submit</button>
      </form>

{details}

  );
}

export default App;

A: with the onChange handler on your input's, it is considered a "controlled" component. you also need to assign the value prop.
<input onChange={readUsername} value={username} />

A: Forms in React have the default behaviour as in HTML: refreshing the page upon submission.
React state only exists during the component's life. When you refresh the page, the component is unmounted, and the state is lost.
To prevent the page refresh, use a function to handle the form submission, and prevent the default behaviour.
const handleSubmit = (e) => {
  e.preventDefault();
}

return (
  ...
    <form onSubmit={handleSubmit}>
      ...
    </form>
  ...
  );
}

View demo on codesandbox
Further reading:

*

*Forms in React

*Preventing default behaviour of events

A: You want to create a controlled input so you should pass the value={password} attribute
like this:
<input htmlFor="username" name="username" onChange={readUsername} value={username} />

Also, I'd change how you handle to form. Change the button to type="submit"
like this
 <button type="submit">Submit</button>
And then handle the submit from the <form>
like this:
<form onSubmit={(event) => updateDetails(event)}

And then on the function, you can use the submit event like this for example
const updateDetails = (e) => {
event.preventDefault()
...rest of logic
}


text:
Q: mingw gcc compiler is giving an error which i m unable to understand, when i m trying to print 1- 10 numbers using recursion the following error shows ,when i try to compile the source code
C:/Program Files (x86)/mingw-w64/i686-7.1.0-posix-dwarf-rt_v5-rev2/mingw32/bin/.
./lib/gcc/i686-w64-mingw32/7.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot
 open output file print.exe: Permission denied
collect2.exe: error: ld returned 1 exit status

the code of my program is given below
#include<stdio.h>

void print(int x)
 {
  if(x==1)
  {
   printf("%d\n", x);
   return;
  }
 else
{
 print(x-1);
 printf("%d\n",x);
}
}
 void main()
{
print(10);
}

it is working fine in Turbo C.
what kind of error it is ? how can I correct it?

A: You have to kill the existing process that is running. kill the print.exe process an it will be accessible or simply close the command prompt window which opened the execution instance.


text:
Q: MPI Isend/Irecv performance behavior I have a routine named transfer(int) which calls MPI routines. In my main program, transfer() is called twice.
... // do some work
transfer(1); // first transfer
... // do some work again
transfer(2); // second transfer

The transfer(int) function looks like this
... // do some work
MPI_Barrier(MPI_COMM_WORLD);
t0 = clock();
for(int k=0; k<mpisize; k++) {
    MPI_Irecv( (void*)rbuffer[k], rsize[k], MPI_BYTE, k, 0, MPI_COMM_WORLD, reqs+2*k );
    MPI_Isend( (void*)sbuffer[k], ssize[k], MPI_BYTE, k, 0, MPI_COMM_WORLD, reqs+2*k+1);
}
MPI_Waitall(2*mpisize, reqs, status);
MPI_Barrier(MPI_COMM_WORLD);
if (mpirank==0) cerr << "Transfer took "<< (double)(clock()-t0)/CLOCKS_PER_SEC << " secs" << endl;

Note that I only measure the communication time, excluding the pre-processing.

For transfer(1), all send and receive buffers have size 0 for each k. So essentially, there's no communication going on. Yet, the transfer took 1.95 seconds.
For transfer(2), each processor has to send/receive about 20KB to/from every other processor. Yet, the whole transfer took only 0.07 seconds.
I ran the experiment many times with 1024 processors and the measurements are consistent. Can you explain this phenomenon or what could possibly be wrong?
Thanks.

A: You could use a MPI performance analysis tool such as Vampir or Scalasca to better understand what is happening:

*

*Are all communications slow or just a few the rest is waiting at the barrier?

*What is the influence of the barrier?

The actual answer highly depends on your System and MPI implementation. Anycorn's comment that zero size messages still require communication and the first communication can have additional overhead is a good start of investigating. So another question you should try to answer is:

*

*How does a second zero size message behave?

Also MPI implementations can handle messages of different sizes fundamentally different, e.g. by using unexpected message buffers, but that again is implementation and system dependent.


text:
Q: PHP Populating an Array of Associated Array I'm looping through some results list that contains information about fruit and who has picked.
Each iteration contains a single fruit and a single person who picked it.
foreach($Jobs as $key => $val) {

//set values
$fruit = $val->FruitName;
$picker = $val->Picker->ForeName;

//build my array here
$myArray[$val->FruitName] = $val->Picker->ForeName;

}

I'm trying to build up an associative array (using fruit names) that holds an array of the picker names, like so;
$myArray = array (
"apple" => array ("Jon","Jo","Dave"),
"pear" => array ("Ben"),
"plumb" => array ("Jane"),
"melon" => array ("Jon","Jo","Dave","Sarah"),
);

The way I'm currently attempting this simply overwrites the existing array of picker names.

A:     foreach($Jobs as $key => $val) {

        //set values
        $fruit = $val->FruitName;
        $picker = $val->Picker->ForeName;

        //build my array here
        $myArray[$val->FruitName][] = $val->Picker->ForeName;
    }

Using your example you need to add the [] to the build array line. This is so the names are added to the array rather than overwriting the value.