text:
Q: header/footer and page content not setup properly I am building a website and I am facing a position issue and I can't figure out why the footer is not properly placed.
So I have setup the App.js to display the header on top of the page and have always the footer at the bottom. But for some reasons when I am loading an other page such as here, the header is still ok but the footer and the page content overlap as in the image below. Do not pay attention to the header, it's cut because of the screenshort.

See how the content (txt, h tage and blue buttom) and the header overlap. I am looking to always have the content between the header and footer whatever happened.
it should like this:

Even the title is not shown on the picture
below are the App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Header from './components/Header';
import Footer from './components/Footer';

import Home from './pages/Home';
import NoPages from './pages/NoPages';
import Discover from './pages/Discover';
import HowItWorks from './pages/HowItWork';
import CreateClassAndHost from './pages/CreateClassAndHost';
import Profile from './pages/Profile';
import Messages from './pages/Messages';
import Settings from './pages/Settings';
import Logout from './pages/Logout';
import CreateClass from './pages/CreateClass';
import CreateHost from './pages/CreateHost';
import HereIsTheMission from './pages/HereIsTheMission';
import SuccessfullSubmission from './pages/SuccessfullSubmission';

import './App.css';

function App()  {
    return (
      <Router>

            <Switch>
              <Route path="/" exact component={ Home } />
              <Route path="/discover" component={ Discover } />
              <Route path="/howitworks" component={ HowItWorks } />
              <Route path="/create" component={ CreateClassAndHost } />
              <Route path="/profile" component={ Profile } />
              <Route path="/messages" component={ Messages } />
              <Route path="/settings" component={ Settings } />
              <Route path="/logout" component={ Logout } />
              <Route path="/hereisthemission" component={ HereIsTheMission } />
              <Route path="/createaclass" component={ CreateClass } />
              <Route path="/createahost" component={ CreateHost } />
              <Route path="/successfull" component={ SuccessfullSubmission } />
              <Route path="*" component={ NoPages } />
            </Switch>

      </Router>
    );
  }

export default App;

and the associated css App.css
.page-container {
    position: relative;
    min-height: 90vh;
}

.content-wrap {
    padding-bottom: 2.5rem;
}

.footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 2.5rem;
}

and the content is done in a separate file and loaded through the /create navlink
but it's look like the opport
Below are my content file:

import React from 'react';
import TextContents from '../assets/translations/TextContents';
import BlueButton from '../components/materialdesign/BlueButton';
import './CreateClassAndHost.js';

class CreateClassAndHost extends React.Component {

    render() {

        const CreateAClass =

{TextContents.BeATeacher}

{TextContents.BeATeacherDesc}

                <BlueButton textSize="13" link_href="/createaclass" text={TextContents.BeATeacherBtn} />

;

        const CreateAHost =

{TextContents.HostAClass}

{TextContents.HostAClassDesc}

                <BlueButton textSize="13" link_href="/createahost" text={TextContents.HostAClassBtn} />

;
        return (

{TextContents.CreateClassOrHostTitle}

                    {CreateAClass}
                    {CreateAHost}

        );
    }

}

export default CreateClassAndHost;

and the associatedc css:
.container {
    width: 650px;
    position: absolute;
    display: flex;
    text-align: center;
    margin: auto;
    top:30%;
    bottom: 0;
    left: 0;
    right: 0;
}

.section {
    display: inline-block;
}
.tile {
    position: relative;
    left: 12px;
    top: 80px;
    text-align: center;
    width: 200px;
    height: 250px;
    background-color: #ffffff;
}

.title {
    font-family: Fredoka One;
    font-size: 50px;
    color: #333333;
}

.subtitle {
    font-family: Source Sans Pro;
    font-weight: bold;
    font-size: 30px;
    line-height: 0.7;
    color: #333333;
    letter-spacing: -0.6px;

}

.text {
    font-family: Source Sans Pro;
    font-size: 20px;
    line-height: 1.6;
    color: #616161;
    width: 280px;
    height: 85px;
}

.button {
    position: relative;
    left: 0px;
    top: 50px;
}

Any idea?

A:

.main-container{
  height:100vh;
}

.header{
  background-color:#000;
  color:#fff;
  padding:10px;
}

.footer{
position:absolute;
bottom:0;
text-align:center;
}

.footer-menu{
padding:10px;
background-color:yellow;
width:100vw;
}

    Heading1
    Heading2

        Footer

A: You can achieve this using flex-box. keep your html structure like below, and use below css

note : main should have height equal to screen height

body,html{
  height :100%;
}

.main{
  display :flex;
  flex-direction:column;
  justify-content:space-between;
  height:100%;
}

.page-container{
  overflow:auto;
}

          <Switch>
          <Route path="/" exact component={ Home } />
          <Route path="/discover" component={ Discover } />
          <Route path="/howitworks" component={ HowItWorks } />
          <Route path="/create" component={ CreateClassAndHost } />
          <Route path="/profile" component={ Profile } />
          <Route path="/messages" component={ Messages } />
          <Route path="/settings" component={ Settings } />
          <Route path="/logout" component={ Logout } />
          <Route path="/hereisthemission" component={ HereIsTheMission } />
          <Route path="/createaclass" component={ CreateClass } />
          <Route path="/createahost" component={ CreateHost } />
          <Route path="/successfull" component={ SuccessfullSubmission } />
          <Route path="*" component={ NoPages } />
          </Switch>


text:
Q: Getting "PKIX path building failed" error while running my selenium client code inside docker container I am connecting to selenium grid to run my selenium tests. The client code is dockerized using the below dockerfile
FROM gradle:7.2.0-jdk8
COPY src /home/app/src
COPY build.gradle /home/app
COPY settings.gradle /home/app
COPY Dockerfile /home/app
ADD ssl.crt /usr/local/share/ca-certificates/ssl.crt
RUN update-ca-certificates
WORKDIR /home/app
EXPOSE 80
ENTRYPOINT ["gradle", "--info", "clean", "test","-Denvironment=stagging","-Dtags=envr:stagging","-Dcucumber.options=--tags @envr=stagging" ]

Now When I run the container I get error "Grid URL could not be reached: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.
Now if I run the same gradle command(EntryPoint) from my java workspace it all works fine. So probably some networking issue which I am not able to understand.
Queestions:

*

*Why is it not connecting the hub(Selenium grid)?

*Do I need chromeDriver,Xvnc etc in the client image to run my tests?

A: I had to convert the crt file to der format first
openssl x509 -in ssl.crt -out ssl.pem
openssl x509 -in ssl.pem -inform pem -out ssl.der -outform der

Then,I got passed the issue through by adding the following lines in my dockerfile. Additionally I had to expose port 40000 as my zalenium containers are running on port 40000
FROM gradle:7.2.0-jdk8

COPY src /home/app/src
COPY build.gradle /home/app
COPY settings.gradle /home/app
COPY Dockerfile /home/app
ADD ssl.der /home/app/ssl.der
RUN \
keytool -importcert -alias startssl -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file /home/app/ssl.der -noprompt
WORKDIR /home/app
EXPOSE 40000
ENTRYPOINT ["gradle", "--info", "clean", "test","-Denvironment=stagging","-Dtags=envr:stagging","-Dcucumber.options=--tags @envr=stagging" ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ionic 2/3 - appending custom component(s) on runtime click event This question is between Ionic 2 and Angular 4.
I have a requirement which is more like a page builder of predefined ionic 2 custom components on click or any event trigger.
How do I go about this? All my research isn't getting me there.
Thanks

A: WORKED LIKE CHARM
I finally found it. I needed to use the componentFactoryResolver.
Thanks to https://blog.thecodecampus.de/angular-2-dynamically-render-components/
The above link kickstarted my goal. The key difference in my case was that my PAGE is lazyloaded and all my components are lazyloaded. So therefore, page.module.ts needed to have the childcomponent.module.ts added at imports: [] and the childcomponent.ts needs to be added at the entryComponent: []. The rest is grabbing and dumping. See below:
PAGE ngMODULE
import { ChildComponent } from './../../../components/child/child';
import { ChildComponentModule } from '../../../components/child/child.module';
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { LessonBuilderPage } from './lesson-builder'; //hosting page

@NgModule({
  declarations: [
    LessonBuilderPage
  ],
  imports: [
    IonicPageModule.forChild(LessonBuilderPage),
    ChildComponentModule
  ],
  exports: [
    LessonBuilderPage
  ],
  entryComponents:[
    ChildComponent
  ]
})
export class LessonBuilderPageModule {}

PAGE.ts
import { ChildComponent } from './../../../components/child/child';
import { Component,ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { NavController, NavParams, IonicPage } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-lesson-builder',
  templateUrl: 'lesson-builder.html',
})
export class LessonBuilderPage {
  @ViewChild('menucontainer', {read: ViewContainerRef}) menucontainer: ViewContainerRef;
  constructor(public navCtrl: NavController, public navParams: NavParams, private componentFactoryResolver: ComponentFactoryResolver) {

  }
  addcomponent(){
    const childComponent_var = this.componentFactoryResolver.resolveComponentFactory(childComponent);
    this.menucontainer.createComponent(childComponent_var);

  }

  ionViewDidLoad() {
  }

}

PAGE.html
<ion-content #pagecontent padding>
    <div #menucontainer>

    </div>
    <button (click)="addcomponent()" ion-button full>Add component</button>
</ion-content>


text:
Q: Can I sell my version of Ubuntu? I wanna customize Ubuntu mini CD and sell it to companies (make unique Ubuntu version). Is it legal? I mean we will do absolutely different system, but making it from mini cd.
Yeah, I really have FOSS spirit, and I want to share Linux and make it popular. But for live I need money, so I thought I can make different versions of Ubuntu with my DE and some unique things for each company. So that will be ideal job for me.

A: Well you definitely can! Read:Licensing
But try to keep up the FOSS Spirit, BTW!


text:
Q: Trying to re-direct users to specific page based on an ACF variable I have a case where I have an ACF variable that is stored within a users profile and based on that variables state I need to redirect to one of two pages once the user logs in. This is just a true or false value that will represent if a user has logged in before.
I have tried using wp_redirect to do this and it does sort of work but seems to run excruciatingly slow and sometimes will briefly get stuck in a loop of redirecting to the same page it's already on several times in a row.
As an example something like this is roughly what I have
function redirect_to_welcome() {
    $acf_user_id = get_current_user_id();
    $acf_User = "user_$acf_user_id";
    $has_user_previously_logged_in = get_field('has_this_user_logged_in_before', $acf_User);

    if(is_user_logged_in() && $has_user_previously_logged_in == true && is_page('welcome')){
        wp_redirect( home_url());
        exit;
   }elseif(is_user_logged_in() && $has_user_previously_logged_in == false && !is_page('welcome')){
        wp_redirect('welcome');
        exit;
   }

I also have another redirect happening that redirects the user to the login page if they are not logged in, while allowing for some page exceptions from an array.

add_action( 'template_redirect', 'redirect_if_user_not_logged_in' );
function redirect_if_user_not_logged_in() {
    global $unrestricted_pages;
    if ( !is_page($unrestricted_pages) && get_post_type() != 'groups' && ! is_user_logged_in() ) {
        wp_redirect( wp_login_url());
         exit;
   }
}

I am sure this is not the best way of going about this but it is what I have come up with so far.


text:
Q: Windows batch For loop not working on one server, working on other I've got a Windows 2008 Server (non-R2); I was trying to modify an attribute (/AppPool/maxProcesses) based on a list of application pools.
So I did this:
set appcmd=c:\Windows\system32\inetsrv\appcmd.exe
for /f %p in (c:\apppools.txt) do @%appcmd% set apppool %p /processmodel.maxProcesses:2

No output. Also, this was all interactive, not a batch file.
Usually, it should display the AppPools, and the fact that it's setting the attribute, or an error, in case of typos.
I then went on to verify why wouldn't it output
for /f %p in (c:\apppools.txt) do @echo %p

Nothing again.
I go to another Windows 2008 (they are actually sysprepped, so considered to be identical. Both commands work!
Has anyone seen anything like this, or at least similar?
I was thinking this server might need its sleep (a reboot) but that might only be possible over the weekend, since it is a server.
Thanks for any suggestions,

A: If you are running this from inside a batch file, you will need to escape the % in your for loop variable with another %.
for /f %%p in (c:\apppools.txt) do @echo %%p

edit
Sorry, I just noticed now that you said it was interactive and not batch.

A: It could be that the file is hidden on one system and not the other, or if it is hidden on both, that hidden files are processed differently on the 2 systems.
Try using a combination of the comments already provided.
for /f "delims=" %p in ('type c:\apppools.txt') do @echo %p


text:
Q: Magento advanced profiles export - Prepend URL to IMAGE path Just a couple of weeks into Magento, managed to get going with the Advanced Export Profiles (Very Handy), What I would like to do is Prepend a url value to one of the output columns, specifically the image url.  I would like to append the url to the beginning of the path output.
Can anyone assist?
<action type="catalog/convert_adapter_product" method="load">
    <var name="store"><![CDATA[0]]></var>
    <var name="filter/price/from"><![CDATA[0.01]]></var>
    <var name="filter/price/to"><![CDATA[999999]]></var>
    <var name="filter/visibility"><![CDATA[4]]></var>
    <var name="filter/status"><![CDATA[1]]></var>
</action>

<action type="catalog/convert_parser_product" method="unparse">
    <var name="store"><![CDATA[0]]></var>
    <var name="url_field"><![CDATA[0]]></var>
</action>

<action type="dataflow/convert_mapper_column" method="map">
    <var name="map">
        <map name="name"><![CDATA[ItemTitle]]></map>
        <map name="upc"><![CDATA[EANBarCode]]></map>
        <map name="description"><![CDATA[ItemTextDescription]]></map>
        <map name="sku"><![CDATA[SKU]]></map>
        <map name="qty"><![CDATA[StockLevel]]></map>
        <map name="price"><![CDATA[CostPrice]]></map>
        <map name="manufacturer"><![CDATA[Brand]]></map>
        <map name="ebaycategory1"><![CDATA[eBayCategory1]]></map>
        <map name="ebaycategory2"><![CDATA[eBayCategory2]]></map>
        <map name="image"><![CDATA[Image1]]></map>
        <map name="description"><![CDATA[ListingDescription]]></map>
        <map name="name"><![CDATA[ListingTitle]]></map>
        <map name="msrp"><![CDATA[OriginalRetailPrice]]></map>
        <map name="conditionnote"><![CDATA[SellerNotes]]></map>
    </var>
    <var name="_only_specified">true</var>
</action>

<action type="dataflow/convert_parser_csv" method="unparse">
    <var name="delimiter"><![CDATA[,]]></var>
    <var name="enclose"><![CDATA["]]></var>
    <var name="fieldnames">true</var>
</action>

<action type="dataflow/convert_adapter_io" method="save">
    <var name="type">file</var>
    <var name="path">var/export</var>
    <var name="filename"><![CDATA[testing123.csv]]></var>
</action>

A: In the class Mage_Dataflow_Model_Convert_Mapper_Column looking at the method map, you have only 2 vars right now: map and _only_specified.
What you need to do is override this class and this method and add something like this at line 125, after var is set:
if ($this->getVar('prepend') && is_array($this->getVar('prepend'))) {
        $prepend = $this->getVar('prepend');
} else {
        $prepend = array();
}

Now you have a new variable prepend that you can use for the batch data like this - at line 138 in the same class you have:
$newRow = array();
foreach ($attributesToSelect as $field => $mapField) {
        $newRow[$mapField] = isset($row[$field]) ? $row[$field] : null;
}

Change this into:
$newRow = array();
foreach ($attributesToSelect as $field => $mapField) {
        $prepend = isset($prepend[$field]) ? $prepend[$field] : '';
        $newRow[$mapField] = isset($row[$field]) ? $prepend . $row[$field] : null;
}

Now in your xml that you posted above, you can add a prepend variable like this:
<action type="dataflow/convert_mapper_column" method="map">
<var name="prepend">
    <map name="image"><![CDATA[http://example.com/]]></map>

I haven't tested this, but that's how I would try it first. Also didn't add the part about how you can override this model class, since I think that there are plenty examples out there.

A: I just registered, so I can not make a Comment on the Answer of Emi. I want to thank him, because he is right, but there is one small piece of Code you have to change too. Here is my solution in short.
I've also made a more detailed blog-entry in my private blog: https://www.timoschindler.de/vollstaendige-urls-in-dataflow-exportierten-csv-dateien-von-magento/ Unfortunately it is in German ;). If you have any Problems, just let me know and I can translate it.
First I added the file app/code/local/Mage/Dataflow/Model/Convert/Mapper/MyColumn.php
<?php
class Mage_Dataflow_Model_Convert_Mapper_MyColumn extends Mage_Dataflow_Model_Convert_Mapper_Column
{
public function map()
{
    $batchModel  = $this->getBatchModel();
    $batchExport = $this->getBatchExportModel();

    $batchExportIds = $batchExport
        ->setBatchId($this->getBatchModel()->getId())
        ->getIdCollection();

    $onlySpecified = (bool)$this->getVar('_only_specified') === true;

    if (!$onlySpecified) {
        foreach ($batchExportIds as $batchExportId) {
            $batchExport->load($batchExportId);
            $batchModel->parseFieldList($batchExport->getBatchData());
        }

        return $this;
    }

    if ($this->getVar('map') && is_array($this->getVar('map'))) {
        $attributesToSelect = $this->getVar('map');
    }
    else {
        $attributesToSelect = array();
    }
    if ($this->getVar('prepend') && is_array($this->getVar('prepend'))) {
            $prepend = $this->getVar('prepend');
    } else {
            $prepend = array();
    }
    if (!$attributesToSelect) {
        $this->getBatchExportModel()
            ->setBatchId($this->getBatchModel()->getId())
            ->deleteCollection();

        throw new Exception(Mage::helper('dataflow')->__('Error in field mapping: field list for mapping is not defined.'));
    }

    foreach ($batchExportIds as $batchExportId) {
        $batchExport = $this->getBatchExportModel()->load($batchExportId);
        $row = $batchExport->getBatchData();

        $newRow = array();
        foreach ($attributesToSelect as $field => $mapField) {
            $prepend_2 = isset($prepend[$field]) ? $prepend[$field] : '';
            $newRow[$mapField] = isset($row[$field]) ? $prepend_2 . $row[$field] : null;
        }

        $batchExport->setBatchData($newRow)
            ->setStatus(2)
            ->save();
        $this->getBatchModel()->parseFieldList($batchExport->getBatchData());
    }

    return $this;
}
}

then I copied app/code/core/Mage/Dataflow/Model/Convert/Profile/Collection.php to app/code/local/Mage/Dataflow/Model/Convert/Profile/Collection.php and changed one if in the code:
/** @var $varNode Varien_Simplexml_Element */
       foreach ($actionNode->var as $key => $varNode) {
           if ($varNode['name'] == 'map') {
               $mapData = array();
               foreach ($varNode->map as $mapNode) {
                   $mapData[(string)$mapNode['name']] = (string)$mapNode;
               }
               $container->setVar((string)$varNode['name'], $mapData);
           }  else {

Thats all! A simple Dataflow XML now looks like:
<action type="dataflow/convert_mapper_myColumn" method="map">
    <var name="map">
        <map name="sku"><![CDATA[Artikelnummer]]></map>
        <map name="name"><![CDATA[Artikelbezeichnung]]></map>
        <map name="image"><![CDATA[image]]></map>
    </var>
    <var name="prepend">
        <map name="image"><![CDATA[https://www.bier-kaufen.de/media/catalog/product]]></map>
    </var>
    <var name="_only_specified">true</var>
</action>

A: I'v developed a simple module to solve the issue. Just install it and append/prepend whatever you want. Here is the link http://bkielbasa.pl/magento-advanced-profiles-export-prepend-url-image-path/
It does not edit any core files.

A: If anyone want this variation, I took kabanek's solution and extended it to added a constant column variation. This way we can export information straight into a template that need fields not in the database.
In Convert.php changed
if ($varNode['name'] == 'map' || $varNode['name'] == 'prepend' || $varNode['name'] == 'append' ) {

to
if ($varNode['name'] == 'map' || $varNode['name'] == 'prepend' || $varNode['name'] == 'append' || $varNode['name'] == 'const') {

Then in Column.php added:
if ($this->getVar('const') && is_array($this->getVar('const'))) {
$constCol = $this->getVar('const');
} else {
$constCol = array();
}

and changed:
$newRow[$mapField] = isset($row[$field]) ? ($prependText . $row[$field] . $appendText) : null;

to
$constText = isset($constCol[$field]) ? $constCol[$field] : null;
$newRow[$mapField] = isset($row[$field]) ? ($prependText . $row[$field] . $appendText) : $constText;


text:
Q: Swap div and contents on click Been trying to swap 2 divs. When the button is clicked #profeditclick1, #profswitch1 should swap with #hideedit1. At the moment when the button is clicked all the divs just disappear. Thank for your help or guidance.
HTML:

Edit

jQuery:
 $("#profeditclick1").click(function(e) {
        e.preventDefault();
        var content = $(this).html();
        $('#profswitch1').replaceWith('
' + content + '
');
      });

UPDATE
Next attempt although doesnt seem to work. i have taken of the display:none and tried to hide it:
$("#hideedit1").hide();
$("#profeditclick1").click(function(e) {
    e.preventDefault();
    var content = $(this).html();
    $('#profswitch1').replaceWith('
' + content + '
');
    $("#hideedit1").show();
});

A: I think this may help you. I have added some modification in your HTML.
Please check it and change it as you need.

    jQuery('#hideedit1').hide();
    jQuery('#profeditclick1').click(function(){
      jQuery(this).hide();
      jQuery('#hideedit1').show();
    });

    jQuery('#hideedit1 #save_edit').click(function(){
      jQuery('#hideedit1').hide();
      jQuery('#profeditclick1').show();
    });

Edit

   EDIT PROFILE CONTENT  <button id="save_edit">Save</button>


text:
Q: A question about the assumption of a problem regarding squared conditional expectation I have the following problem regarding an inequality of conditional expectation.
Given that $X$ a R.V. such that $E|X|< \infty$ and $B_1 \subset B_2 \subset \mathcal{F}$ are sigma-algebras. Show that
$$
E(X - E(X|B_1))^2 \geq E(X - E(X|B_2))^2.
$$
This is quite obvious to prove if we have $E|X|^2 < \infty$ since we can use the definition of conditional expectation for square integrable R.V. My question is does this also hold for the integrable assumption of $X$ provided in this question? I think it can run into the trouble of doing things like $\infty - \infty$ which is problematic and I feel like the assumption for this problem is lacking. Thank you!


text:
Q: How can I redesign a high-frequency, high-voltage power supply causing EMI around the home? How can I redesign a high frequency, high voltage, power supply causing EMI around the home?
I've been messing around with electronics for some time, and while I have briefly produced an arc or two, my setup hasn't been something I can just plug-n-play. This time around it isn't much different, but I want to keep this setup assembled as there have been brief occasions having high voltage would have been helpful.
The fear/problem I'm having is the high frequency (around 100 kHz) of the arc is interfering with, and in one case ruining, electronics nearby. Sometimes my monitor flashes, my mouse stops working, my T12 soldering iron freezes and occasionally the display on my power supply reads numbers not yet discovered (it is weird).
The worst was my DSO shell oscilloscope even when it was not in any way electrically connected to this circuit (just in the general vicinity of the arc); it is now constantly and permanently reading a maximum voltage. It is broken, which isn't too big of a deal considering that they cost like 30 bucks, but I don't want this to happen again so.
I work on electronics in my room, so I can't exactly cover everything in tin foil.  What can I do to my circuit that could stop it from interfering?
I've tried grounding the secondary and primary of this CRTV transformer and that may have helped, but it didn't fix it.
I don't know what to do. I may have reached the limits of doing electronics in my room, but I want to see what others would do because Google is pretty bad at returning helpful results once you enter "high voltage" as a search term.
Here is the circuit in question:

A: A high voltage arc will emit a lot of interference in any case, and there is not much that can be done about that without removing the arc.
But there is another source of interference in the flyback driving circuit.
The schematic in the question is missing a few basic elements that are used to reduce noise emitted:

*

*Decoupling capacitors for the power supply. When placed close to the transformer and MOSFET, these reduce the length of the high-current loop on the primary side. This in turn reduces the emissions from it.

*Common mode choke for the power supply input cable. This can either be a ferrite core that is clamped around the power cable, or a small coil/transformer installed on the PCB. This reduces the emission and propagation of high-frequency noise through the long power supply cabling.

*RC snubber for the flyback transformer. This dissipates high-frequency oscillations that result from the switching. 100 kHz itself is quite low frequency and doesn't couple easily from and to short cables, but the fast switching action has much higher frequency components also.
Overall this application is similar to plasma balls which are used for decoration. They emit enough noise to be heard on radio receivers, but do not cause damage to nearby equipment.

A: You have designed a powerful source of wideband electromagnetic interference and the only way to tame it easily is to put the whole thing in a metal screened Faraday cage. The size of holes in the screen needs to be 1mm or slightly less. So, a rather fine copper mesh.
I'm basing this recommendation on the fact that even rather small arcs - like a powerful universal motor's commutator arcing - can easily wreck 5GHz ISM band WiFi. So you'd want screening that goes 2-3x higher in frequency than what's needed for a microwave oven door that only needs to be effective up to 2.4GHz.
Otherwise, you'd need to design active arc current slew rate control networks, and that's not easy without proper instrumentation. You'd need to measure high voltages and fast changing currents with a wideband oscilloscope. That gets expensive really quickly if you don't have the ability to design your own instrumentation (wideband HV probe, for example).
If you don't plan on making a Faraday cage, then you should immediately stop using your circuit as it's probably heard by radio receivers for several blocks around, and you may be interfering with professional communications. The level at which you transmit makes your device an intentional, unlicensed wideband transmitter and is not legal to operate.
You'd probably be less likely to cause trouble doing this work in a rural environment "in the middle of nowhere". But rural areas are also more likely to depend on broadcast AM radio and your device will cause much trouble on broadcast band. So I'm afraid there is no easy way to just keep doing what you're doing. A Faraday cage with no wires passing through it, ie. internally powered from battery/power bank, is the only simple solution that is within your level of knowledge at the moment (this of course will change as you learn, but we're dealing with it right now).

A: The only certain way to stop this thing from causing nuisance or worse to you and others is to switch it off and leave it off.


text:
Q: Code optimisation removing duplicates in VB I'm looking to optimise my code. Specifically this process

*

*Calculate a group of locations (basically squares on a grid)

*Have a list of all the locations that have been calculated

*Then I go through all these locations, 1 at a time.

The issue I'm having is removing or not including duplicate locations in the list. I've tried having a list of integers (integers to represent the location) but it's still very slow. To give you an idea of the numbers: I'm talking at least 15,000 different location calculations and around 1,000,000 possible locations.
Any help on this would be much appreciated!

A: Here is how I remove duplicates from an string array, perhaps it will be of help to you:
  Dim OneDimensionalTable(1000) As String

  ....

  OneDimensionalTable = RemoveDuplicates(OneDimensionalTable)

  .....

 Private Function RemoveDuplicates(ByVal items As String()) As String()

    Dim noDupsArrList As New ArrayList()
    For i As Integer = 0 To items.Length - 1
        If Not noDupsArrList.Contains(items(i).Trim()) Then
            noDupsArrList.Add(items(i).Trim())
        End If
    Next

    Dim uniqueItems As String() = New String(noDupsArrList.Count - 1) {}
    noDupsArrList.CopyTo(uniqueItems)
    Return uniqueItems

End Function


text:
Q: Sharepoint: SPFile.OpenBinary() , doesn't open file in binary I,m try to open SPFile in binary format:
SPFolder Folder = web.GetFolder(item.Attachments.UrlPrefix);
            foreach (SPFile File in Folder.Files)
            {

                byte[] CopyFile = File.OpenBinary();

            }

but the result byte [1]=0, what i'm doing wrong?

A: The code you have posted should work just fine.  Are you sure the file in question isn't just a single byte file?


text:
Q: How would I call a function from another component in react native? How would I call a function from another component?
App.js
<Button onPress={movePopUpCard()}></Button>
<PopUpCard/>

PopUpCard.js
const movePopUpCard = () => {
   //Code to update popUpCardX
}

<Animated.View style={[
    {transform: [{scale: scale}, {translateX: popUpCardX}]},
    {position: 'absolute'}
]}>
</Animated.View>

A: By using ref and forwardRef you can achieve this.
snack ex: https://snack.expo.io/@udayhunter/frisky-pretzels
App.js
import React,{useRef,useEffect} from 'react';
import { Text, View, StyleSheet } from 'react-native';
import PopUp from './PopUpCard'

const App =(props)=> {

const childRef = useRef(null)

  return (
    <View style={styles.container}>
    <PopUp ref={childRef}/>

    <Text
    onPress = {()=>{
    childRef.current.updateXvalue(10)
    }}
    >Press me</Text>

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },

});

export default App

popUp.js
import React,{useState,useImperativeHandle,useEffect,forwardRef} from 'react'
import {View,Text,StyleSheet,Animated} from 'react-native'

const PopUp = (props,ref) => {
    const [xValue, setXvalue] = useState(10)

   const updateXvalue = (x)=>{
      setXvalue(prev=> prev+x)

    }

  useImperativeHandle(ref, () => ({
    updateXvalue
  }));

  return(
    <Animated.View style = {[styles.mainView,{transform:[{translateX:xValue}]}]}>
    </Animated.View>
  )
}

const styles = StyleSheet.create({
  mainView : {
    height:100,
    width:100,
    backgroundColor:'red'
  }
})

export default forwardRef(PopUp)

A: If you are using a functional component you have to use forwardRef to add reference to the component and useImperativeHandle to implement the method which you want to access through reference here is an example. Here I am calling bounce method which increases the scale of the component:
Snack: https://snack.expo.io/@ashwith00/adequate-salsa
Code:
App.js
export default function App() {
  const boxRef = React.useRef();
  return (
    <View style={styles.container}>
      <AnimatedBox ref={boxRef} />
      <Button title="Bounce" onPress={() => boxRef.current.bounce()} />
    </View>
  );
}

AnimatedBox.js
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
import { View, Animated } from 'react-native';

export default forwardRef((props, ref) => {
  const scale = useRef(new Animated.Value(1)).current;
  useImperativeHandle(
    ref,
    () => ({
      bounce: () => {
        Animated.timing(scale, {
          toValue: 1.5,
          duration: 300,
        }).start(({ finished }) => {
          if (finished) {
            Animated.timing(scale, {
              toValue: 1,
              duration: 300,
            }).start();
          }
        });
      },
    }),
    []
  );
  return (
    <Animated.View
      style={{
        width: 100,
        height: 100,
        backgroundColor: 'red',
        transform: [{scale}]
      }}
    />
  );
});

A: move the function movePopUpCard to app.js
and pass in app.js pass it in
<PopUpCard movePopUpCard={(params) => movePopUpCard(params)}/>

you can call the function from PopUpCard component by this.props.movePopUpCard(params)
you can also pass params if requrired


text:
Q: Text in matrix does not fit in one line I am trying to put variables in my document but it cannot fit in one row and goes somewhere out of the page... I tried some different things, like \begin{split} or \begin{align} or just "\\" but it doesn't seem to work... Any other ideas?
\documentclass[paper=a4,fontsize=11pt,twoside=semi,usegeometry]{scrreprt}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{microtype}

\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{newtxtext,newtxmath}
\usepackage{graphicx}

\usepackage{blindtext}
\usepackage{fancyhdr}
\usepackage{tocloft}

\usepackage{ragged2e}

\addtokomafont{disposition}{\rmfamily}

\RedeclareSectionCommand[
  beforeskip=-1sp,
  afterskip=.5cm,
  font=\Huge
]{chapter}

\begin{document}

\pagestyle{fancy}
\fancyhf{}
\fancyhead[CE,CO]{\leftmark}
\fancyfoot[LE,RO]{\thepage}

\renewcommand{\headrulewidth}{2pt}
\renewcommand{\footrulewidth}{1pt}

\chapter{chapter}
\normalsize
\setlength{\parindent}{0pt}

\begin{equation}
 y = \left\{\begin{matrix}
 & 1 & \text{\text{if curve $c \in C$ applies cant size $k \in K$ and speed $s \in S$ and curve $c+1 \in C$ applies cant size $p \in K$ and speed $q \in S$}}\\
 & 0 & \text{Otherwise}
\end{matrix}\right.
\end{equation}

A:
\documentclass[paper=a4,fontsize=11pt,twoside=semi,usegeometry]{scrreprt}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{microtype}
\usepackage{amsmath,amsfonts,amsthm,amssymb}
\usepackage{newtxtext,newtxmath}
\usepackage{graphicx}
\usepackage{blindtext}
\usepackage{fancyhdr}
\usepackage{tocloft}
\usepackage{ragged2e}
\addtokomafont{disposition}{\rmfamily}
\RedeclareSectionCommand[
  beforeskip=-1sp,
  afterskip=.5cm,
  font=\Huge
]{chapter}
\begin{document}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[CE,CO]{\leftmark}
\fancyfoot[LE,RO]{\thepage}
\renewcommand{\headrulewidth}{2pt}
\renewcommand{\footrulewidth}{1pt}
\chapter{chapter}
\normalsize
\setlength{\parindent}{0pt}
\begin{equation}
 y = \left\{\begin{matrix}
 & 1 & \text{\text{if curve $c \in C$ applies cant size $k \in K$ and speed $s \in S$ and curve $c+1 \in C$ applies cant size $p \in K$ and speed $q \in S$}}\\
 & 0 & \text{Otherwise}
\end{matrix}\right.
\end{equation}
\begin{equation}
 y = \left\{\begin{array}{lp{10cm}}
 1 & if curve $c \in C$ applies cant size $k \in K$ and speed $s \in S$ and curve $c+1 \in C$ applies cant size $p \in K$ and speed $q \in S$ \\
 0 & \text{Otherwise}
\end{array}\right.
\end{equation}
\end{document}


text:
Q: Footer text in datagrid dont apply the changes in code behind I have a datagrid with a text footer, and wanted to change the text in this footer when change selection in dropdownlist, but this change is not visible on the client(browser). I've been doing some tests and if i use the databinding() method datagrid is updated, and the text is correct.
My question is how to force the table to be drawn with the new changes. I think what the databinding() method  is redrawing the datagrid, in the browser.


text:
Q: I can't request array data This is the buidForm
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('categorie', EntityType::class, [
        // This field shows all the categories
        'placeholder' => 'Choisissez une option',
        'class'    => Categorie::class,
        'mapped' => false,
        'multiple' => true
        ]);
}

And this the controller
$form = $this->createForm(RechercheCandidatType::class, null);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $categories = $request->request->get('recherche_candidat_categorie');
      foreach ($categories as $categorie) {
            dump($categorie);
        }
}

return $this->render("test.html.twig",['form' => $form->createView()]);

And this the TWIG

        {{ form_start(form,{'attr': {'novalidate': 'novalidate'}}) }}

            {{ form_errors(form) }}

                {{ form_row(form.categorie) }}

        {{ form_row(form._token) }}
        <button class="btn btn-success">Afficher</button>
        {{ form_end(form) }}

This is from Inspect element
 <form name="recherche_candidat" method="post" novalidate="novalidate">

Categorie<select id="recherche_candidat_categorie" name="recherche_candidat[categorie][]" required="required" class="form-control" multiple="multiple"><option value="1">Web</option><option value="2">Mobile</option></select>

            <input type="hidden" id="recherche_candidat__token" name="recherche_candidat[_token]" value="B25v0VqQWQbERl3c3_EsGkyiVZTvC8xn37szufreGmo" />
            <button class="btn btn-success">Afficher</button>
            </form>

The problem is after submitting, i can't receive the array data ($categories = null )

PS : recherche_candidat_categorie = ID of select form

A: You can't get data using id, you have to use the name, So instead of "recherche_candidat_categorie", use this
$request->request->get('recherche_candidat');


text:
Q: Error C2050 switch expression not integral So I'm wrestling with this particular snippet of code:
    scanf("%f", &x, &y);
    scanf("%c", &operator);

    switch (x)
    {
    case ('p') : x = lastNum;
        break;

    case ('q') : return(0);

    default: break;

And Visual Studio is throwing up Error 2050 as a result of it. Now, I understand why it's happening, since x in this case is a float and I'm trying to account for non-numerical input, but is there any way to fix this without resorting to some form of wizardry?
Edit
This is the entirety of my code, still broken but I think my snippet was kind of useless.
#pragma warning(disable: 4996)
#include <stdio.h>

int main()
{
float x, y, lastNum;
char operator;

while (1)
{
    scanf("%f %c %f", &x, &operator, &y);

    switch (operator)
    {
    case('+') : lastNum = x + y;
        printf("\nANS = ", "%f", x + y);
        break;

    case('-') : lastNum = x - y;
        printf("\nANS = ", "%f", x - y);

        break;

    case('*') : lastNum = x * y;
        printf("\nANS = ", "%f", x * y);

        break;

    case('/') : lastNum = x / y;
        printf("\nANS = ", "%f", x / y);

        break;

    }

}

}

A: So, based on your comments to another answer, I think I understand what you're trying to accomplish - the user has the option to enter floating point values or non-numeric values such as 'p' (to use a previous value) and 'q' (to quit), and you're trying to figure out how to account for both.
Using scanf( "%f", &x ); won't work, as it won't accept 'p' and 'q' as valid inputs; it will return a 0 for the matching failure, and x won't be updated.
Instead, you're going to have to read the input as text, test to see if the first character is either 'p', 'q', or a digit, and then process from there.  Assuming I've understood your intentions correctly, you'd want to do something like the following:
#include <stdlib.h> // for strtod

char input[SIZE]; // where SIZE is large enough to account for your largest
                  // possible floating point input, plus an optional sign,
                  // plus a newline, plus the 0 terminator.

/**
 * Read input as text
 */
if ( fgets( input, sizeof input, stdin ) )
{
  /**
   * Check for a newline character - if it isn't present, then the user
   * typed in a longer input than we're capable of handling.
   */
  char *newline = strchr( input, '\n' );
  if ( !newline )
  {
    fprintf( stderr, "input too long, try again\n" );
    return 0;
  }

  /**
   * Remove the trailing newline
   */
  *newline = 0;

  /**
   * Skip over any leading whitespace
   */
  char *p = input;
  while ( isspace( *p ) )
    p++;

  /**
   * If the first non-whitespace is a digit or a sign, process as
   * a numeric input
   */
  if ( isdigit( *p ) || *p == '+' || *p == '-' )
  {
    /**
     * Convert input to a floating point value, save to x
     */
    char *chk;
    x = (float) strtod( p, &chk ); // I'm assuming x is declared float

    /**
     * Make sure there wasn't any garbage at the end of the floating-point
     * input.
     */
    if ( !isspace( *chk ) && *chk != 0 )
    {
      fprintf( "%s is not a valid floating-point input\n", p );
      return 0;
    }
  }
  else if ( tolower(*p) == 'p' )
  {
    x = lastVal;
  }
  else if ( tolower(*p) == 'q' )
  {
    return 0;
  }
  else
  {
    fprintf( stderr, "Don't know what to do with %s\n", p );
    return 0;
  }
}
/**
 * process x
 */

Edit
If you're not allowed to use routines from stdlib.h, then the first thing you should do is slap your teacher for making this assignment harder than it needs to be.
Well, maybe not - that might affect your grade.
You can use sscanf instead of strtod to do the conversion, but the error checking is a bit less straightforward:
if ( isdigit( *p ) || *p == '+' || *p == '-' )
{
  char chk;
  int r = sscanf( p, "%f%c", &x, &chk );
  if ( r < 1 || ( r == 2 && !isspace( chk ) && chk != 0 ) )
  {
    // bad input, handle like above
  }
}

All of the *scanf functions will return the number of successful conversions and assignments.  Under normal circumstances, we expect to read 2 items - the floating point number and the trailing newline character.  If we read 2 items and chk is not a newline or a 0, then we had trailing bad input after the floating point number.  If we read less than one item, then we either had a matching failure (input wasn't a valid float) or had an error during the read.  Since we already checked for a leading digit before getting this far, we shouldn't get a total matching failure at this point, but I'm including the check for completeness' sake.
Edit of the Edit
Well, you're definitely not going to want to just paste all that into your code for a number of reasons.  I was mainly trying to show fairly robust ways of checking your input when it can take one of several forms.
The main thing to take away from all of this is the following:

*

*If the first thing on your input line can be either text or a numeric value, read and store it as a text string first.  You can use fgets() (which will read everything up to the newline, or until you've filled your target buffer, whichever comes first), or scanf( "%s", ... ) (which will read up to the next whitespace character);

*Check the first non-whitespace character of your input - if it's a sign or a digit, then you'll need to convert that input into a floating-point value.

*Read your operator and second floating point input.
Here's yet another method that's a bit less robust (this will replace the scanf( "%f %c %f", &x, &operator, &y ); in your updated code snippet above):
char xstr[SIZE]; // large enough to hold a single floating-point value as
                 // text, plus sign, plus terminator

/**
 * Read the first input up to the next whitespace character
 */
scanf( "%s", xstr );
if ( xstr[0] == 'p' )
{
  x = lastVal;
}
else if ( xstr[0] == 'q' )
{
  return 0;
}
else
{
 /**
  * Convert x to a float value
  */
 sscanf( xstr, "%f", &x );

 /**
  * Read the remainder of the input
  */
 scanf( " %c %f", &operator, &y );
}

and then switch on operator (this assumes your input can take the form of 12.3 + 4.56 and p + 7.89).  This is guaranteed not to use anything that isn't in stdio.h.
I realized that using fgets will read in the entire line of input, including your operator and second operand, so I changed the above to read just the first input.
You should check the return value of scanf (and sscanf) to make sure you actually read what you meant to before processing; I left it out of the above to make the code a little clearer.
The one thing I want to you to take away from this is that interactive I/O in C is a pain in the ass.

A: You can not have char in case when you are storing float value in your variable x.
If you want to store char value in x then change the scanf statement to this
    scanf(%c,&x)
otherwise you store float value in x and in CASE statement you write float value.

A: First of all, in your code,
 scanf("%f", &x, &y);

does not make any sense, as you're giving one format specifier and passing two arguments.
That said, regarding the error message, quoting C11 standard, chapter §6.8.4.2

The controlling expression of a switch statement shall have integer type.

so, you cannot use a float value as the controlling expression of the switch statement. However, from your following code snippet, we can see, you're using int value as the case statement, so you can surely make the controlling element as int.

A: You should make x as a char or int variable. You can't use a float number in a switch and compare to a char. Also, you should have:
scanf("%c %f", &x, &y);

Since you are receiving two values there.
You could use a different variable in this case instead of x:
case ('p') : x = lastNum;

If you want to save a number... Instead of using x for receiving this lastNum, you could create a different variable and use x only for the cases.


text:
Q: Joomla language switcher modification I tried to change a bit the displaying of may language switcher module. The idea is that to have my language option in a jquery select box and on change to retrieve the site to the selected language.
My problem is that is not outputting in the right way the default language and on selection the link is not build it on.
<?php
/**
 * @version     $Id: default.php 19022 2010-10-02 14:51:33Z infograf768 $
 * @package     Joomla.Site
 * @subpackage  mod_languages
 * @copyright   Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// no direct access
defined('_JEXEC') or die('Restricted access');
JHtml::_('stylesheet', 'mod_languages/template.css', array(), true);
$document = &JFactory::getDocument();
$document->addScript('jomres/javascript/jquery.ui.selectmenu.js');
$document->addScript('jomres/javascript/selectmenu.js');
?>

<select name="speedB" id="speedB"  onchange="Javascript: window.location.href='<?php echo $language->title;?>'">>

    <?php foreach($list as $language):?>

    <option value=" <?php echo $language->active ? 'lang-active' : '';?>">

       <?php echo $language->title;?>

<?php endforeach;?></option>

            </select>

A: The problem is in how the option tags are displayed. The value attribute should contain a value that will be sent back to the browser, and there's a selected attribute that determines which value will be sent back. Only the attribute which is selected will have its value sent back.
So you would need something like
<?php foreach($list as $language):?>
    <option value="<?php echo $language->title;?>" <?php echo $language->active ? 'selected' : '';?>
        <?php echo $language->title;?>
    </option>
<?php endforeach;?>

Note that I do not have Joomla available so I can't check which field of $language would be best to use in the option value attribute. There's probably something that provides a short name like en-GB or fr-FR


text:
Q: chrome mobile app fails because of gradle version I am fairly new to using cca for complex things and all my attempts fail with this error:
FAILURE: Build failed with an exception.

*

*Where:
Build file '/home/peterj/Documents/Projects/ChromeMobileApps/t2/platforms/android/build.gradle' line: 27

*What went wrong:
A problem occurred evaluating root project 'android'.

Failed to apply plugin [id 'android']
  Gradle version 1.10 is required. Current version is 2.2.1. If using the gradle wrapper, try editing the distributionUrl in /home/peterj/Documents/Projects/ChromeMobileApps/t2/gradle/wrapper/gradle-wrapper.properties to gradle-1.10-all.zip

I don't really know when did gradle updated but this is what I have installed with android:
Android SDK tools - 24
Android SDK platform tools 21
Android SDK build tools 19 (I have also tried with 21.1.1 - same error)
API 19 - SDK platform.
I do not see any way to downgrade the tools and plarform tools and I have also upgraded cordova and cca (with npm).
Am I missing something?

A: Updated build.gradle file
https://git-wip-us.apache.org/repos/asf?p=cordova-android.git;a=blob_plain;f=bin/templates/project/build.gradle;hb=f953e6a
buildscript {
    repositories {
        mavenCentral()
    }

    // Switch the Android Gradle plugin version requirement depending on the
    // installed version of Gradle. This dependency is documented at
    // http://tools.android.com/tech-docs/new-build-system/version-compatibility
    // and https://issues.apache.org/jira/browse/CB-8143
    if (gradle.gradleVersion >= "2.1") {
        dependencies {
            classpath 'com.android.tools.build:gradle:0.14.0+'
        }
    } else {
        dependencies {
            classpath 'com.android.tools.build:gradle:0.12.0+'
        }
    }
}


text:
Q: Trigger - Add to a date using a subquery (postgresql 9.2)
I'v 2 tables
Table 1 (extinguisher)

extinguisher_id (serial)
type_designation_extinguisher_type(text)
manufacturing_date (date)
life_date(date)

Table 2 (extinguisher_designation)

extinguihser_type(serial)
extinguisher_designation(text)
lifespan(int)

lifespan can take values like: 10 or 20 and it represents years
My objective is to do a trigger that will automatically populate table1.life_date based on the extinguisher_type using table2.
The problem is that lifespan is an int and can change.
The usual way to add year to a date is using
date + interval '10 year'
The problem is that I want a variable instead of the 10.
At this point i'v this:
CREATE OR REPLACE FUNCTION ext_life_span()

RETURNS trigger AS

$BODY$

DECLARE
new_date timestamptz;
manu_date char(10);
intervalo char(10);
BEGIN
IF (TG_OP = 'INSERT') THEN
intervalo := to_char((SELECT lifespan FROM extinguisher_type, extinguisher where type_designation = type_designation_extinguisher_type), '99999');
manu_date := to_char(New.manufacturing_date, 'YYYY-MM-DD');
new_date := (date 'manu_date' + integer 'intervalo' );
update extinguisher set life_date = new_date;
RETURN NULL;
ELSIF (TG_OP = 'UPDATE') THEN
IF new.manufacturing_date IS DISTINCT FROM old.manufacturing_date THEN
intervalo := to_char((SELECT lifespan FROM extinguisher_type, extinguisher where type_designation = type_designation_extinguisher_type), '99999');
manu_date := to_char(New.manufacturing_date, 'YYYY-MM-DD');
new_date := (date 'manu_date' + integer 'intervalo' );
update extinguisher set life_date = new_date;
END IF;
RETURN NULL;
END IF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION ext_life_span() OWNER TO postgres;

CREATE TRIGGER insert_lifespan
AFTER INSERT OR UPDATE OF manufacturing_date
ON "extinguisher"
FOR EACH ROW
EXECUTE PROCEDURE ext_life_span();

I'm getting an error: invalid input syntax for type date: "menu_date"
Am I doing the best approach? Is there an easier way to do it?

A: You can easily use a variable when doing something like this:
menu_date := menu_date + interval '1' year * num_years

Where num_years holds the number of years that should be added.
You get the error because date 'manu_date' is an incorrect date literal because the string (!) 'manu_dat' is not a valid date. The expression date 'xxxx' requires a date definition in ISO format e.g. date '2013-09-27'
Regarding your trigger:
The statement update extinguisher set life_date = new_date; will update all rows in the table extinguisher. I'm pretty sure that is not what you want. You are missing a where condition for the update.
You also cannot run an update on the table on which the trigger is fired. You simply assign the value to the new record.
I although I absolutely don't understand what you intend with your trigger, I think what you want is much simpler:
CREATE OR REPLACE FUNCTION ext_life_span()
  RETURNS trigger AS
$BODY$
DECLARE
    l_lifespan integer;
BEGIN

  -- note that this can fail, if type_designation is not unique!!!
  SELECT lifespan
    into l_lifespan
  FROM extinguisher_type
  WHERE type_designation = new.type_designation_extinguisher_type;

  new.life_date := new.manufacturing_date + interval '1' year * l_lifespan;

  RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;

Edit: depending on your data volumn, you could also get rid of the trigger and the life_date column alltogether and simply calculate that value "on-the-fly" using a view:
select ex.extinguisher_id,
       ex.manufacturing_date,
       ex.manufacturing_date + interval '1' year * ed.life_span as life_date
from extinguisher ex
  join extinguisher_designation ed
       -- I'm not sure I understand your data model correctly.
       -- you need to setup a proper FK here e.g. by using the generated ID
    on ed.extinguihser_type = ex.extinguihser_type

That way the value will always be up-to-date and you never need to worry about triggers.
In a relational database, values that can be derived from existing values should not be stored.


text:
Q: Orientation on boundary of a smooth open set Suppose $D$ is an open set in $\mathbb R^n$ with smooth boundary, $bD$, that is, for each $p \in bD$, there exist a smooth function $r$: from a open neighborhood $U$ of $p$ to $\mathbb R$ such that $U\bigcap bD=\left\{ x\in U:r\left(x\right)=0\right\} $ and $dr\neq0$ on $U\bigcap bD$. Now $bD$ is a submanifold $(n-1)$ dimension of $\mathbb R^n$.
My question is, how to define the orientation on $bD$? that is, which is smoothly non-vanishing (n-1) form on $bD$?
Can everybody help me or give me a textbook which mentions about it?
Thanks.

A: There's more than what you say. $dr\ne 0$ on $U\cap \partial D$, as well. (I see you just edited to include this.) If you choose your charts on $D$ so that $r>0$ on $U\cap D$, then you can easily glue all these $r$'s together with a partition of unity to get a globally defined smooth function $f$ defined on a neighborhood of $D$ with $f>0$ on $D$, $f=0$ on $\partial D$, and $df_p(v)<0$ for any outward-pointing normal vector at $p$. This then defines an orientation on $\partial D$. (If you want a nowhere-zero $(n-1)$-form on $\partial D$, take $\iota_{v} dx^1\wedge\dots\wedge dx^n$ for $v$ a smooth, nowhere-zero outward-pointing normal vector field, as given above.)
If you want to read about the Jordan-Brouwer Separation Theorem, which actually gives a stronger result (including orientability of any compact, smooth hypersurface in $\Bbb R^n$), see Guillemin and Pollack.


text:
Q: PCA change colours of clusters I want to change the colours of my clusters but maintain the shape.  habillage=iris$Species changes both colour and shape, what can to change only colours?
library("devtools")
install_github("kassambara/factoextra")
library("factoextra")
res.pca <- prcomp(iris[, -5],  scale = TRUE)
fviz_pca_ind(iris.pca,  geom="point",  pointsize = 1, habillage=iris$Species, addEllipses=TRUE, ellipse.level=0.95)

A: fviz_pca() works like ggplot plots, hence, for changing shapes you can use the aesthetic mappings of ggplot, e.g., for changing shapes. Concerning colors, the documentation called by ?fviz_pca_ind tells you that you can change colors via palette.
fviz_pca_ind(res.pca,  geom="point",  pointsize = 1, habillage=iris$Species, addEllipses=TRUE, ellipse.level=0.95
             , palette = c("green", "orange", "grey") #change colors
             ) +
             scale_shape_manual(values=c(2, 8, 11)) #change shapes


text:
Q: Exclude directory from WordPress htaccess AND redirect old .html files I have a WordPress install which is replacing an old website. The old (Movable Type) website had .html files which I want to redirect to their new equivalents. This works to redirect /foo.html to /foo/:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule (.+)\.html$ /$1/ [L,R=301]
</IfModule>

BUT I also want to exclude a few other directories, that contain old .html files from WordPress - so that they can still be accessed as before. I've seen from other answers that I can add the line marked below to WordPress's .htaccess statements to exclude a directory from its rewriting:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# NEW LINE:
RewriteCond %{REQUEST_URI} !^/(mydirectory|mydirectory/.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I have two questions:

*

*If I comment out that first block, that new line still doesn't let me access, say /mydirectory/foo.html - WP redirects to /missing/. I can't work out why.

*I'm not sure how to combine these two sets of rules. ie, Anything in /mydirectory/ is accessed as before, but all other URLs ending in .html should be rewritten to /filename/, and WP's other stuff works as normal.

A: Have it this way:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# NEW RULE to ignore rewriting for anything in mydirectory
RewriteRule ^mydirectory(/.*)?$ - [L,NC]

RewriteRule ^(.+?)\.html$ /$1/ [L,R=301,NC]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>


text:
Q: Redmine Icalendar export issue in mac I am facing some issues when try to install following plugin in mac os.
It is working fine in linux as well as in windows.
https://github.com/thegcat/redmine_ical
Steps I followed:
After copying plugin files in vendor/plugin folder. Redmine stops working and shows "We're sorry but something went wrong" error message.
I am using bitnami-redmine-1.4.7-2-osx-x86_64-installer.dmg and when I remove Gemfile and require dispatcher from init.rb It starts running but doesn't show Ical on calendar page.

A: After copying plugin file we need to run "bundle install" command from terminal.
In bitnami stack redmine after copying plugin file,
1) $cd install dir
2) $./use_redmine
3) $bash: cd root_dir
4) bundle install
This will work .

A: The accepted answer didn't work for me, but did help me one step.
I had to do the following to make it work succesfully:
cd installdir/apps/redmine/htdocs
bundle install --without development test postgresql sqlite --no-deployment
bundle install --without development test postgresql sqlite --deployment
ruby bin/rake redmine:plugins RAILS_ENV=production

This all in addition to (or actually from within) using the "use_redmine" bash from the install dir.
I've opted to go for the other ical plugin, that didn't require the patchfiles (https://github.com/buschmais/redmics)
https://docs.bitnami.com/installer/apps/redmine/#how-to-install-the-redmine-agile-plugin


text:
Q: Rmpi send/receive hanging? I am writing the code for a population MCMC. I will try to provide as much information I think could help, so please bear with me.
I am using tempered distributions and I want to perform exchange moves, i.e a moves that propose to swap the value of two chains.
What I have done (exchange happening in the master)
I had written this initially by

*

*letting each chain mutate for a specified number of iterations n.

*at every n-th iteration, I would send the slaves' results to the master and there attempt an exchange of parameters between chains.

*Then send updated values back to slaves and repeat the process.
What I want to achieve (exchange directly between slaves)
This is working fine, but I wanted to clean up my code and remove unnecessary communication between master and slave . That is, let the slaves communicate directly between them.
So  assuming I am spawning 10 slaves,

*

*at iteration n, I want  to let slave1-slave2, slave3-slave4, ...., slave9-slave10 communicate between them

*at iteration 2*n, I want to let slave2-slave3, slave4-slave5, ...slave8-slave9 communicate between them

and so on, so that I let samples travel through the temperature ladder.
The problem
And this is where I am facing a problem.
I think I am managing to send a value from one slave to another (my print statement "Succesfully sent" gets printed in the log files of the slaves that are sending) but this doesn't seem to be received (my "Succesfully received" statement doesn't get printed in the log of the partner slaves).
And the program just hangs. I think maybe I have caused a deadlock, but I am not sure what I have done wrong?
Could you please advise? I have used as guide this Parallel Tempering  R code
http://www.lindonslog.com/mathematics/parallel-tempering-r-rmpi/
Please see below my code
Many thanks!
Sofia
ind <- mpi.comm.rank()
oddFlag<-0   ### object to flag code suitable for odd/even numbered slaves.

for  (i in  1:TotalIter)  {
##### normal MCMC move (single chain mutation) -  logL.current

 if ( i%%exchangeInterval == 0 ){   ### every nth (right now 5th) iteration, attempt an exchange

message("\n\nAttempt an exchange move")
oddFlag<-oddFlag+1
exchange<-0
logL.partner<-0

  if (ind%%2 == oddFlag%%2) {  ###when oddFlag even , the following code concerns even-numbered slaves. When odd number, it concerns odd-numbered slaves.
  ind.partner<-ind+1

  if (0<ind.partner && ind.partner<(noChains+1)){
    message("This is the slave: ", ind, " and its partner is: ", ind.partner)
    message("The tag for receiving logL.partner is: ", ind.partner)
    logL.partner<-mpi.recv.Robj(source=ind.partner,tag=ind.partner)  #### receive the logL of partner
    message("Succesfully received")
    message("This is the logL.partner: ", logL.partner)
    exchanges.attempted<-exchanges.attempted+1

    if (runif(1)< min(1, exp((logL.partner - estimatorSelf)*(temper[ind] - temper[ind.partner] )))) {    ############# exp((chain2 - chain1)*(T1 - T2))
      message("I exchanged the values")
      exchange<-1
      print(exchange)
      exchanges.accepted<-exchanges.accepted+1
    }
    mpi.send.Robj(obj=exchange,dest=ind.partner,tag=15*ind)
  }

  if (exchange==1){
### exchange parameters  with mpi.send.Robj/mpi.recv.Robj functions
  }

} else {  ##### ###when oddFlag even , the following code concerns odd-numbered slaves. For oddFlag odd, it concerns even-numbered slaves.
  ind.partner<-ind-1

  if (0<ind.partner && ind.partner<(noChains+1)){
    message("This is the slave: ", ind, " and its partner is: ", ind.partner)
    message("The tag for sending logL.current is: ", ind)
    mpi.send.Robj(obj=logL.current,dest=ind.partner,tag=ind)  ### send logL to partner
    message("Succesfully sent")

    exchange<-mpi.recv.Robj(source=ind.partner, tag=15*ind.partner)
    message("I received the exchange message")
  }

  if (exchange==1){
 ### exchange parameters send/receive functions
   }
  }
 }
}

A: This seems very strange. To my knowledge the send and receive commands are locking so for the send to work without the receive to work strikes me as a bit odd. Have you tried the code on the guide? If you like I can send you the entire R-code just to see if it works on your system. If the code on the guide works then you can safely say that it isn't a problem with your MPI setup.
One thing you might try is for the receive command instead of using ind.partner you could use mpi.any.source() (i think is the correct one) which will accept a message of any tag. If this resolves your deadlock, it could be a problem with the tags (but by eye there doesn't seem anything wrong to me).
Another thing you might try is removing the "source=" and the "tag=" on the receive commands. I notice in my code that I don't have any there whilst I do for the send commands. Perhaps that was causing me too problems, but I can't quite remember. Let me know how it goes, I hope it all works out.


text:
Q: How can I place a UILabel below an UIImageView such that it is always evenly placed I have made a custom pop view which looks like this

I want to place the label of user name below the user image which is the rounded UIImageView in the given image
I want the user name to be placed evenly irrespective of the size of the text.
Like I want the name to appear like this

A: *

*Align the Label content to Center.

*Set a constraint from label to Image View. Horizontally center label to Image View.

A: As you are not using the storyboard, Below code will help you in setting the frame of label:-
UILabel *labelName;//This will be your label instance
CGFloat yAxis = 50;//This will be your image view's y axis + image view's height
[labelName setFrame:CGRectMake(0, yAxis, self.view.frame.size.width, self.view.frame.size.height)];
//Set the color/Font other properties of label as desired

[labelName setTextAlignment:NSTextAlignmentCenter];

A: Setting the constraint is the efficient solution.
Either you can follow the storyboard way as suggested by Mr.UB or the approach it by code way.I suggest you to use Masonry for setting the constraints if you wish to proceed by code.
And you can simply do:
[your-label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(imgView.mas_top); //with is an optional semantic filler
    make.mas_centerX.equalTo(imgView.mas_centerX);
}];


text:
Q: How to convert UTF-8 to ANSI csv file I'm actually generating csv files in php, works great but I have to use these csv files to use into Microsoft Dynamics AX and here's the problem.
Csv file that I generated gets "NUL" space on some columns and I have to pull off those spaces to get clean csv files and use it in Dynamics AX.
I saw when opening them into Notepad ++ that csv files are in UTF-8 BOM and I want to convert them to ANSI, when I make the conversion to ANSI in Notepad++, all NUL spaces disappear.
I tried different things saw on StackOverflow and it is with the iconv method that I obtained the better result but it is far from perfect and what I expect.
Here's the actual code :
fprintf($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
                for ( $a = 0 ; $a < count($tableau) ; $a++ ) {
                    foreach ( $tableau[$a] as $data ) {
                        fputcsv($fp, $data, ";", chr(0));
                    }
                }
                $fp=iconv("UTF-8", "Windows-1252//TRANSLIT//IGNORE", $fp);
                fclose($fp);
                echo json_encode(responseAjax(true));
            }

and I obtain these result :

I don't understand why it's only apply in one cell instead on working on every cells which contain "NUL" spaces.
I tried the mb_converting_encoding method with no great result.
Any other idea, method or advice will be welcome,
thanks

A: "NUL" is the name generally given to a binary value of 00000000, which has the same meaning in all ASCII-compatible encodings, which includes UTF-8, Windows-1252, and most things that could be given the vague label "ANSI". So character encoding is not relevant here.
You appear to be explicitly adding it with chr(0) - specifically as the "enclosure" argument to fputcsv, so it's being used in place of quote marks around strings with spaces or punctuation. The string "Avion" doesn't need enclosing, which is why it doesn't have any NULs around.
Let's add some comments to the code you've apparently copied without understanding:
// Output the three bytes known as the "UTF-8 BOM"
// - an invisible character used to help software guess that a file should be read as UTF-8
fprintf($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
// Loop over the data
for ( $a = 0 ; $a < count($tableau) ; $a++ ) {
    foreach ( $tableau[$a] as $data ) {
        // Output a row of CSV data with the built-in function fputcsv
        // $data is the array of data you want to output on this row
        // Use ';' as the separator between columns
        // Use chr(0) - a NUL byte - to "enclose" fields with spaces or punctuation
        // The default would be to use comma (',') and quotes ('"')
        // See the PHP manual at https://php.net/fputcsv for more details
        fputcsv($fp, $data, ";", chr(0));
    }
}

The character you use for the "enclosure" is entirely up to you; most systems will probably expect the default ", so you could use this:
fputcsv($fp, $data, ";");

Which is the same as this:
fputcsv($fp, $data, ";", '"');

The function doesn't support disabling the enclosure completely, but without it, CSV is fundamentally a very simple format - just combine the fields separated by some character, e.g. using implode:
fwrite($fp, implode(";", $data));

Character encoding is a completely separate issue. For that, you need to know two things:

*

*What encoding is your data in

*What encoding does the remote system want it in

If these don't match, you can use a function like iconv or mb_convert_encoding.
If your output is not UTF-8, you should also remove the line at the beginning of your code that outputs the UTF-8 BOM.
If your data is stored in UTF-8, and the remote system accepts data in UTF-8, you don't need to do anything here.


text:
Q: How to convert from data generator to tensorflow queue for multi gpu training. cifar10_multi_gpu_train.py sample I have a data generator for training a CNN and works fine. Now I want to speed up training on 2 GPUs (on 1 pc)  by following cifar10_multi_gpu_train.py. (https://www.tensorflow.org/programmers_guide/threading_and_queues)
Questions:
1) How to convert data generator to queue? Data item: (image file dir, output). Whole dataset: list of data items. Batch dataset: partial whole dataset. How to put it into a tensor like following:
  batch_queue = tf.contrib.slim.prefetch_queue.prefetch_queue(
        [images, labels], capacity=2 * FLAGS.num_gpus)

2) What is content of the queue?
1.a) The queue take whole dataset or single batch dataset?
1.b) It seems to me in cifar10 sample, the queue is 1 batch. But, how it cycle through all dataset?
1.c) If queue take whole dataset, what is the data in each thread of gpu? In such case, I am not sure I understand how concurrent GPU training is possible, as each dataset used to calculate loss and gradient depends on same model state. But, next loss+gradient of next dataset calucation is possible only after last one is done to modify the model weight.

A: One approach that might work is something like:

*

*Build lists
image_list = [("file%d" % i) for i in range(100)]
label_list = read_label_list_from_disk(path)

*convert image_list and label_list to tensors

*Producer
image_filename_queue, label_queue =
       tf.slice_input_producer([image_tensor, label_tensor], ..)

*Reader
reader =tf.WholeFileReader()
key, value = reader.read(image_filename_queue)
images = tf.image.decode_png(value)`

*Batching
image_batch, label_batch =
       tf.train.batch([images,labels_queue],batch_size=batch_size)

*Prefetching
batch_queue = tf.contrib.slim.prefetch_queue.prefetch_queue(
                  [image_batch, label_batch], capacity=2*gpus)

Hopefully, this explains the concept of the queue in Tensorflow as well.


text:
Q: Elegant way to recover R packages after a update Recently my package manager updated R automatically to the newest version 4.10 (well, i give the permission so is my fault), whenever this happens the packages from the older version are lost. But i was wondering if there is elegant way to recover all the packages from the older version.
If this is not possible, what is the best practice?
I'm familiar with the discussion in Painless way to install a new version of R?, but the discussion is how avoid this problem, and i'm new user of Ubuntu (version 20.04), so i'm still learning how manage packages.


text:
Q: Using max function to group max value by unique ID in QGIS I have been using the maximum function to group max value by unique "id";
maximum("Ni_ppm_1", group_by:="Hole_id")

The function pulls the maximum "Ni_ppm_1" value per unique "Hole-id".
Below is a snip of the dataset

Is it possible to get the function to pull out the "from" and "To" associated with the maximum Ni value?
The "From" / "To" is the depth of the sample.

A: You can use the maximum() function together with the array_agg() function to achieve this:
array_get(
    with_variable('max_ppm',
                  maximum("Ni_ppm_1", group_by:="Hole_id"),
                  array_agg(expression:="Ni_ppm_1"  || '-' || "From" || '-' || "To",
                            group_by:="Hole_id",
                            filter:="Ni_ppm_1"=@max_ppm)
                ),
    0)

in the first part the maximum will be assigned to the variable max_ppm and then the expression "Ni_ppm_1"  || '-' || "From" || '-' || "To" will be collected into an array with the same group_by and the filter Ni_ppm_1 = @max_ppm. The array_get() selects the first (and only) entry from the result array.

A: You can get the From value for the maximum "Ni_ppm_1" value per unique "Hole-id" with this expression:
attribute (
    get_feature (
        @layer,
        'Ni_ppm_1',
        maximum(
            "Ni_ppm_1",
            group_by:="Hole_id"
        )
    ),
    'From'
)

Replace 'From' in the second last line with 'To' to get the according To value. To get all these values (including your max value with the expression you provided) as output, there are different options - please specifiy for which one you'd like to get more information (if so):

*

*Concatenate, use pipes ||  to get a string with these values in the form [expression1] || [expression2] || [expression3] - add ', ' || after each || to separate the values with a comma+space.

*Create an array of these values.

*Create a map, thus a list of key:value pairs, comparable to Python dictionaries, see Wikipedia: Associative array


text:
Q: How do I redesign this code to avoid goto? Well, I have this problem because I started my journey with C# and I wrote a console calculator, but I used goto in it and I heard to not use it, but I have no clue what other instruction to use to make it work just how I want it to. I paste my code (it's not long) here, so maybe you can look at it and give me some tips. Thanks!
base:
        Console.WriteLine("First number");
        double first = double.Parse(Console.ReadLine());
        Console.WriteLine("Second number");
        double second = double.Parse(Console.ReadLine());

        Console.WriteLine("What operation do you want to perform? \n1 - addition \n2 - subtraction \n3 - multiplication \n4 - division");
        string choice = Console.ReadLine();
        if (choice == "1")
        {
            Console.WriteLine(first + second);
            Console.ReadLine();
        }
        if (choice == "2")
        {
            Console.WriteLine(first - second);
            Console.ReadLine();
        }
        if (choice == "3")
        {
            Console.WriteLine(first * second);
            Console.ReadLine();
        }

        else if (choice == "4" && second == 0)
        {
            Console.WriteLine(" Do not divide by zero");
        }
        if (choice == "4")
        {
            Console.WriteLine(first / second);
            Console.ReadLine();
        }

        Console.WriteLine("Next one? \n1 - Yes \n2 - No");
        string chc2 = Console.ReadLine();
        if (chc2 == "1")
        {
            goto base;
        }
        if  (chc2 == "2")
        {
            Console.WriteLine("Bye bye");
            Console.ReadKey();

        }

A: Use loops. Here's one common way:
while (true) {
    // do some stuff
    Console.WriteLine("Next one? \n1 - Yes \n2 - No");
    string chc2 = Console.ReadLine();
    if (chc2 == "1")
    {
        continue; // means go back to the top of the loop
    }
    if  (chc2 == "2")
    {
        Console.WriteLine("Bye bye");
        Console.ReadKey();
        break; // means break out of the loop
    }
}

A: Here is your code refactored and UX improved:
  string userInput;
  do
  {
    Console.WriteLine("Enter first number:");
    double operandFirst = double.Parse(Console.ReadLine());
    Console.WriteLine("Enter second number:");
    double operandSecond = double.Parse(Console.ReadLine());
    double? result = null;
    bool isValid = true;
    do
    {
      Console.WriteLine();
      Console.WriteLine("Select the operation you want to perform:");
      Console.WriteLine("1 - Addition");
      Console.WriteLine("2 - Subtraction");
      Console.WriteLine("3 - Multiplication");
      Console.WriteLine("4 - Division");
      userInput = Console.ReadLine();
      switch ( userInput )
      {
        case "1":
          result = operandFirst + operandSecond;
          break;
        case "2":
          result = operandFirst - operandSecond;
          break;
        case "3":
          result = operandFirst * operandSecond;
          break;
        case "4":
          if ( operandSecond == 0 )
            Console.WriteLine("Can't divide by zero.");
          else
            result = operandFirst / operandSecond;
          break;
        default:
          Console.WriteLine("Unknown selected operation.");
          isValid = false;
          break;
      }
    }
    while ( !isValid );
    if ( result.HasValue )
      Console.WriteLine("Result = " + result);
    Console.WriteLine();
    Console.WriteLine("Retry?");
    Console.WriteLine("1 - Yes");
    Console.WriteLine("2 - No");
    userInput = Console.ReadLine();
    Console.WriteLine();
  }
  while ( userInput != "2" );
  Console.WriteLine("Bye bye.");
  Console.WriteLine("Press a key to exit.");
  Console.ReadKey();


text:
Q: How to know if it was clicked on a graphics object I have encountered a problem. I have a mouse event.
  @Override
  public void mouseClicked(MouseEvent e){

  }

And it works fine. But I have shapes.
Rectangle r = new Rectangle();
r.setSize(50, 50);
r.setLocation(200, 200)
g2d.draw(r);

And when the mouse event is triggered I need something check if it was clicked on my rectangle. Not just anywhere on the screen.
if (e.ClickedOnRectangle) {
//Do stuff
}

Something like that. Any solutions?
How do check if my mouse was clicked on a AWT (graphics) object?

A: It depends.  If the Shapes are contained within the container that the mouse events are occurring then it should be a simple case of using the Shape#contains method
@Override
public void mouseClicked(MouseEvent e){
    if (rect.contains(e.getPoint()) {
        // Was clicked...
    }
}

Take a closer look at the Shape JavaDocs for more details


text:
Q: How to add additional column in pytest html report I need help regarding pytest html report customization. I need to print failed network request status code(By TestCase wise) in report so I did the below code. StatusCode column created successfully but not getting data in html report. also, test case-wise statuscode row does not appear in the report.
Conftest.py

@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.append(html.th('Statuscode'))

Conftest.py

@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.append(html.th('Statuscode'))

@pytest.mark.optionalhook
def pytest_html_result_table_row(report,cells):
    cells.append(html.td(report.statuscode))

def pytest_runtest_makereport(item):
    """
    Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    setattr(report, "duration_formatter", "%H:%M:%S.%f")
    extra = getattr(report, 'extra', [])
    statuscode = []

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_")+".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '

' % file_name
                extra.append(pytest_html.extras.html(html))

            for request in driver.requests:
                if url in request.url and request.response.status_code >=400 and request.response.status_code <= 512:
                            statuscode.append(request.response.status_code)

        print("*********Status codes************",statuscode)
        report.statuscode=statuscode
        report.extra = extra


text:
Q: HTML validations from javascript <input type="text" id="newFname" pattern="^[a-zA-z0-9 _-]{2,}$" required placeholder="First Name" />

<input type="text" id="newLname" pattern="^[a-zA-z0-9 _-]{2,}$" required placeholder="Last Name"/>

Is it possible to disable html validation on second input without modifying pattern or required attributes?

A: What you could do, put the inputs in separate forms and add the novalidate attribute to the second form.
Check this page for more information.


text:
Q: JSON Get the name of dynamically changing key with PHP I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
    "dynamic_key": [
        {
            "confidence": 0.99,
            "value": "thi is the answer"
        }
    ]
},
"msg_id": "1234532123"
}

I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
        $search_term = $obj->_text;
        $msg_id = $obj->msg_id;
    }

But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed @Dimi, solution. This is what I ended up with
$data=json_decode($json,true);

foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";

    foreach ($data['entities'] as $keys){
        $conf = $keys[0]['confidence'];
        $answer = $keys[0]['value'];
        echo "conf: $conf, answ: $answer";
    }
}

A: Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities )    {
    echo $key.PHP_EOL;
    foreach ( $entities as $entity) {
        echo $entity->confidence.PHP_EOL;
    }
}

A: Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php

$json='{
"_text": "this is a test",
"entities": {
    "dynamic_key": [
        {
            "confidence": 0.99,
            "value": "thi is the answer"
        }
    ]
},
"msg_id": "1234532123"
}';

$data=json_decode($json,true);

foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);

}

A: If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];

Or shorter:
$confidence = current($array['entities'])['confidence'];

You can probably use reset, current and maybe array_pop etc.


text:
Q: tomcat 5.5.20 on geoserver 2.3 I know it is curious, but I want to run GeoServer 2.3.0 on Tomcat 5.5.20. When I deploy the war file it deploys successful but I can't start the GeoServer.
Message:
FAIL - Application at context path /geoserver_2.3.0 could not be started
Unfortunately I must use Tomcat 5.5 and until GeoServer 2.1.4 I can deploy and start fine.
You know how can I solve this or you have any experience.

A: I recall that geoserver 2.3 wants java 1.6 up, maybe your tomcat is using an older version.


text:
Q: l e t t e r s p a c i n g with soul/soulutf8 I use  l e t t e r s p a c i n g  provided by soul/soulutf8 to emphasize words.
But

*

*If I try to copy a spaced word from the pdf-file, then I get "w o r d" instead of "word".

*Also the search for "word" in pdf-file does not return the spaced word.

Is there a trick to fix this problem?

A: The problem is solved, thanks to Steven B. Segletes:
\documentclass{article}
\usepackage{accsupp}
\usepackage{soulutf8}

\newcommand\an[1]{%
    \BeginAccSupp{method=escape,ActualText={\detokenize{#1}}}%
      \so{#1}%
    \EndAccSupp{}%
}

\def\emph{\an}

\begin{document}
Try to copy this \emph{word} --- you will see ``word'', but not ``\emph{word}''.
\end{document}

A: You've already found a satisfactory solution by (1) using accsupp and also (2) reducing the tracking (=intraword spacing) from a whopping 0.25em (\textso's default) to 0.1em. (In my experience, no. (2) by itself can solve the search and copy issue with most PDF readers.)
In addition, I would like to suggest abandoning soul(utf8) in favor of the superior letterspacing tool from pkg microtype (available separately as pkg letterspace). Particularly if you have to deal with long portions of text, indexing commands, or the like.
soulutf8, despite the recent updates and the Unicode compatibility, still suffers from some limitations of the old soul package. \textso interacts poorly with some other macros. Of the more common ones, using \index or \cite in the argument aborts compilation, while using \mbox or math mode breaks the letterspacing functionality (examples below). There are workarounds, but they can get pretty ugly: in the last example, you'd need to "close" and "reopen" \textso every time, which in turn makes for too short interword spaces.
letterspace handles these cases easily, besides being more flexible in choosing the amount of letterspacing (case by case or globally). And of course, it can be combined with accsupp as in Steven Segletes' and your approach.

\documentclass{article}

\usepackage{letterspace}                % or microtype
\usepackage{soulutf8}

\begin{document}

\textso{triangle $ABC$} (\verb|\textlso|)

\textls[250]{triangle $ABC$} (\verb|\textls|)

\bigskip

\textls{foo \mbox{bar} \index{baz}baz (\cite{mybook})}
(\verb|\textls|, mbox index and cite succeed)

\textls[250]{foo bar baz} (\verb|\textls|)

%\textso{foo bar \index{baz}baz} (\verb|\textlso|)          % doesn't compile!
%\textso{foo bar baz \cite{mybook}} (\verb|\textlso|)       % doesn't compile!

\textso{foo \mbox{bar} \protect\index{baz}baz (\protect\cite{mybook})}
(\verb|\textlso|, mbox index and cite prevent letterspacing)

\textso{foo} \mbox{\textso{bar}} \index{baz}\textso{baz} (\cite{mybook})
(\verb|\textlso|, requires some contorsions, messes up interword spaces)

\end{document}


text:
Q: Feature Toggles vs Feature Branches What are "Feature Toggles" and "Feature Branches" and what's the difference between them?
What are the pros and cons? Why is one better than the other?
I found some articles on Google regarding this, and I tend to be in the "Feature Toggles" camp, but I'm not convinced that "Feature Toggles" is the better choice in all the cases.

A: Feature toggles are methodology used in a Continuous Integration/Continuous Delivery (CI/CD) chain (Agile/Kanban project methodology). Basically, you send new features to production in a disabled state, then in an admin console turn the feature on (or off if you discover it's broken).
Feature branches can be part of a release methodology and integrated into a continuous integration chain. You can develop in a feature branch, deploy the branch to DEV/QA, get certification, merge the feature branch to trunk, then push the trunk to SIT/UAT/PROD environments.
There are pros and cons associated with this approach. Feature toggling requires very strict discipline as broken/dark code is making it to production. This is great for startups and shops where management knows how to pull this off and has system automation tools in place (Chef/Puppet/cfengine, etc.) Google, Facebook, LinkedIn, WordPress all deploy to production environments using feature toggling and system automation.
There are some prerequisite "techs" to do feature toggling properly: Continuous Delivery/Deployment, Continuous Integration, Automated Unit Testing, Automated Integration Testing, Automated Stress/Performance Testing, System Automation. If you don't have these in place, consider a simpler release strategy (e.g. feature branching.)

A:
Feature toggling requires very strict discipline as broke/dark code is
  making it to production.

I agree Electrawn, I've been using feature branching along 6 years, because in our case, we haven't the pre requirements.
Also is important to understand that the "Toogle Strategy" transfers the effort spent in Feature Branches Strategy( Merging ) to another moment.
http://martinfowler.com/bliki/FeatureToggle.html

It's very important to retire the toggles once the pending features have bedded down in production.
  This involves removing the definitions on the configuration file and all the code that uses them.
  Otherwise you will get a pile of toggles that nobody can remember how to use. In one memorable example I heard of,
  it required making a special recompilation of the linux kernel to handle enough command line switches.

Note:  Following the SCM principles if anybody open and edit a file it could be broken code.
So, In my perspective I don't believe in a "better choice in all the cases", because it depends on the culture of your team and if u have the test cover.
Well it is a very polemic question.
I still prefer Feature Branches Strategy in my case. Keeping the SCM best practices and planning the roadmap, the merge process tends to be a easy way.
During these year, i heard a lot of people complains about merge process, but in much cases the problem of merge is the same in my experience, "The communication fails" :)
Sorry for unprecise answer, but i think there are some humans aspects around this subject of better choice in SCM.

A: I discuss this in depth on my blog: http://geekswithblogs.net/Optikal/archive/2013/02/10/152069.aspx
In short, feature branches will give you better isolation, but require you to deal with the pain of deferred integration, and merges.  Toggles give you continuous integration, but require you to design/implement your code in such a way that supports toggles, and introduce the risk that unfinished feature code could negatively affect production.
You can use both branches and toggles together (they aren't mutually exclusive).  As far as deciding which one to use in each scenario, my thoughts are that toggles should be the default choice unless the following are true:

*

*hard to hide the functionality behind a toggle

*has a potential impact on an area of the application that doesn't have thorough tests

If either of those conditions are true, I would probably use a feature branch instead of toggle.


text:
Q: Why do hard drives display a size lower than the true value?
Possible Duplicate:
Why is the effective hard drive size lower than the actual size?

For example, I have a 250 GB hard drive and when I add up all the partitions (and there are no hidden partitions), it comes out to 232 GB. I know that this is normal, but I was curious as to why, so I googled around a bit and have came across two theories.
One said this happens because the hard drive manufacturers use 103 to define a kilobyte (1000 bytes) while windows uses 210 (1024 bytes).
The other theory said that

1 GB = 1024 MB = 1024 * 1024 KB.

Therefore:

1024 * 1024 * 232 = 243,269,632 ~= 250GB.

Which theory is true? Or is there a different reason that is the correct reason?

A: The whole point is in prefixes. Standard SI prefixes increase by 10^3. So we have kilo which is 1000 (10^3), then we have mega which is 1000000 (10^6) and so on. For some reason that prefixes are being incorrectly used by computer scientists to represent 2^10 (which is 1024).
To solve the problem, new set of prefixes was introduced whose step is 2^10. So now we have one kibibyte (KiB) which is 1024 bytes, one mebibyte (MiB) which is 1048576 (2^20) bytes and so on.
Unfortunately, these new unambiguous prefixes have not been adopted by Microsoft and Apple, so operating systems made by them are still spreading confusion.
So to cut the long story short, hard drive manufacturers are correct, but their interpretation of mega and giga is different than one commonly used in computer science.
Here's a nice Wikipedia article on that.

A: It is how GB is defined. The difference between how the manufacturer markets it and how the OS reads it is based on different criteria, exactly as you mentioned in your question. If you look closely on the boxes for most major brands they will indeed add a disclaimer that states that they measure a gigabyte by 1,000,000,000 bytes, not 1,073,741,824 bytes as the OS does.
The wikipedia article for gigabyte goes over this in detail. You can also see the lawsuit against WD for this.

A: As well as the difference between binary and decimal powers, when you prepare a disk for storing data, a percentage of the disk is taken up with the information needed to make this all happen - it's a bit like finding that a '250 page' book is actually 246 pages + 4 pages for the preface and index.


text:
Q: Network programming achieving nowhere near benchmark I've been doing some network programming using Java and C. So far I've only been able to achieve network speeds of around 15 MegaBytes/sec using different techniques and seemingly regardless of message size over loopback, remote networking also yields approximately the same speed.
Despite this I have used iperf to benchmark the network speed and it achieves 1.6 GigaBytes/sec. This is obviously a significant improvement. Does anyone have any ideas how I can achieve this speed in practical programming?

A: First off, the numbers you give for iperf don't sound right.
1.6Gigabytes/sec = 12.8Gigabits/s.  That is beyond the 10Gigabit ethernet standard.
Perhaps you'd like to redo the numbers.
If on the other hand you have Gigabit ethernet then I would expect anything from 60-100 Megabytes/sec
The main factor under windows is the transmit and receive buffers.  If you increase those you'll see a dramatic increase in performance.
I'm not too sure how you do that in Java though.
Under C it's done like this (e.g. 1MegaByte buffer):
int sndbuf_size = 1048575;
result = setsockopt(thesocket, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, sizeof(int));
if (result != -1){
   socklen_t optlen = sizeof(sndbuf_size);
   if (getsockopt(native_socket, SOL_SOCKET, SO_RCVBUF, &sndbuf_size, &optlen) != -1){
        printf("  SO_SNDBUF: %d bytes\n", sndbuf_size);
   }
} else {
   printf("Error setting socket opt SO_SNDBUF (%d)\n", errno);
}

Make sure you call this for both send and receive buffers before you call listen or connect.
Note: if you call setsockopt with a value larger than the max, it won't fail.  To find out how big it really is after the call you have to call getsockopt with the same option.
EDIT: The other bottleneck could be your protocol or the disk.  However, if you're simply transmitting files through a socket with very little overhead like an HTTP server you should consider using the TransmitFile API under Windows or sendfile if you're using Linux.
sendfile() copies data between one file descriptor and another. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read(2) and write(2), which would require transferring data to and from user space.
The TransmitFile function uses the operating system's cache manager to retrieve the file data, and provide high-performance file data transfer over sockets.

A: Warning: Bad ASCII art follows!
If your network pattern looks like the following, you'll never get really great speeds:
REQ   REQ   REQ   REQ   REQ
   RSP   RSP   RSP   RSP

What will get you some excellent speed is if you can achieve this:
REQ-A REQ-B REQ-C REQ-D REQ-E
     RSP-A RSP-B RSP-C RSP-D RSP-E

Several things can lock you into the first pattern. A single-threaded, single-state process. A multithreaded process with badly done locking.
You can get to the second pattern if you use asynchronous, multiple state networking or if you use really well done multithreading (or multiple processes).
You should try to avoid using a new TCP session per request/response if you can.  As each TCP session seeks its best rate it causes a mix of network overload and underutilization. Some new network protocols like SCTP are better. HTTP protocol options like pipelining are good as well.

A: Are you sure you're getting 1.6 Giga Bytes per second? That works out as 13 Gbps. Unless you're sitting on a core network switch with multiple optical links (and are somehow managing to generate that much traffic) I think there might be something wrong in your numbers somewhere.