text:
Q: Add custom input outside the form In admin/some_item.rb form is rendered. I don't know how to add my custom input so that it wouldn't submit with that form.
I found a lot of suggestions like 'use render' or 'use content do' - in both cases exception was thrown: undefined method render/content
admin/some_item.rb
...
form do |f|
  inputs 'some name' do
    input :name
    input: amount
  end
  actions
end

//here i want to add my input

A: It looks like you want to add a second form beneath the default form that ActiveAdmin creates. To do this, you'll want to take complete control of how the form should render and behave.
You'll want to render the form using a partial, and insert a second form beneath the default one:
# admin/some_item.rb
form partial: 'form'

<!-- views/admin/some_item/_form.html.erb -->

<!-- This will be the default form that posts to the path ActiveAdmin expects -->
= semantic_form_for [:admin, @some_item], builder: ActiveAdmin::FormBuilder do |f|
  = f.inputs "Details" do
    = f.input :name
    = f.input :amount
    = f.actions

<!-- Add any number of additional forms with custom end-points. -->
<!-- You'll need to set up the end-points yourself. -->

Here's the relevant official documentation: https://activeadmin.info/5-forms.html#partials
The second form will probably be submitting to a custom active admin action - the documentation for this can be found here: https://activeadmin.info/8-custom-actions.html


text:
Q: Vue – pass variable from child template to App.vue I read up on passing variables from child to parent using $emit but I can't fully figure it out yet.
In App.vue I have a <header/> component for the page header containing a button which controls the mobile navigation's visibility. On click it changes its class:
<button @click="toggleMobileNavigation" :class="isOpen ? 'is-open' : 'is-closed'">

The <header/>'s js:
export default {
  data() {
    return {
      isOpen: false,
    };
  },
  methods: {
    toggleMobileNavigation() {
      if(!this.isOpen) {
        this.isOpen = true;
      } else {
        this.isOpen = false;
      }
      this.$emit(this.isOpen)
    }
  }
}

The App.vue:
<Header />
<main id="main" tabindex="-1" class="main" :class="isOpen">

This obviously this doesn't work and I can't figure out what the right way is to catch the $emit.
Thanks for any tips!

A: I would say you are on the right track, this child needs to emit some event to alert its parent of an important change.
But instead of doing this in your Header component:
      this.$emit(this.isOpen)

Supply an event name:
      this.$emit('opened', this.isOpen)
      // or:
      if (this.isOpen) {
          this.$emit('opened');
      } else {
          this.$emit('closed');
      }

The way you catch this event in the parent component (App.vue) should be:
<Header @opened="handleOpenedEvent">  // will call method handleOpenedEvent
// alternatively:
<Header @opened="menuStatus = $event"> // $event contains data you supply as second argument to your this.$emit(name, ...) call

// @[eventname] is one way of doing it, v-on is the same:
<Header v-on:opened="handleEvent">

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIDeviceRGBColor isEqualToString:]: unrecognized selector Can someone tell me what exactly is that about?
I have table and inside the tableCell I have a pickerview and some textfields in other cells.
When i'm scrolling the table up and down 8-10 times app crashes and gives me this error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIDeviceRGBColor isEqualToString:]: unrecognized selector sent to instance 0x5834850'

A: Short answer: it is trying to call -isEqualToString: on an instance of UIDeviceRGBColor, which is doesn't respond to it.
Long answer: you're either asking for the wrong object at some point, or quite possibly trying to access an object that has been released, but who's pointer has not been set to nil. Sometimes when this happens you'll get a straight crash as the memory in the new location isn't a proper object. Sometimes a new object takes its place. The best way to find out is to turn on Zombies.
This is a good overview of how to use Zombies: http://iosdevelopertips.com/debugging/tracking-down-exc_bad_access-errors-with-nszombieenabled.html
You may start seeing messages saying "-[NSCFString isEqualToString:] message sent to deallocated instance". If so then this is a memory management problem and you need to double check your retains & releases. If you don't get this message then you are likely calling the wrong method and so getting the wrong object back.


text:
Q: white screen coming while navigating between different pages I am working on jQuery mobile +phonegap(cordova-1.9) app for windows phone7. This is multiple HTml pages app. when I navigate from one html page to another html page a white screen is firstly come and then second page is loaded. Which look bad. I search various forms and find that
.ui-page
{
-msie-backface-visibility: hidden;//because IE has msie engine(not very much sure)
-webkit-backface-visibility: hidden;

}

I use this code is in my css file. but this is not working. Please tell me where I am wrong.I need that work only for windows phone 7. Thanks


text:
Q: MS ACCESS/VBA - Using a form filter in docmd.runsql update query I have a subform that the client is using the dropdown filter list on to search through 40k records.
I need to use the filter they selected in a line of code to update the select flag in the temporary table for only filtered records so they can append them to another table which acts as the list they are compiling. The recordset still has all 40k records so I need to just select what is displayed on the screen.

How can I use the filter in the code easily without doing a ton of instr and mid and manipulation? This is the filter in code:
([sfmJobSearch].[VerticalMarket] In ("AR - Amusement & Recreation","CO - Commercial","GO - Government"))
but I need it more like [verticalmarket] like "''AR - Amusement & Recreation''" (except with all the options not just one)
Any help would be great!

A: Do the following
1. in the table that is the subforms record source make  field property, a lookup, list box, with the option of allowing multiple values set to yes.

*Then create an insert query to move data into the temporary table

*the insert query will be like this
INSERT INTO Table3 ( field1 )
SELECT Table2.Field1.Value
FROM Table2;
4  That will solve it, once the records as been moved into the temporary table,you can then use the values in the temporary table to update any other value in another table.

*Place all the queries into a macro in the order that you want them to run.

*I will suggest you have a delete query to delete all values in the temporary table first.before running the queries in 3.
The delete query should be the first query in the macro.


text:
Q: Eclipse doesn't find my already running Android emulators Configuration
Os: OSX
IDE: Eclipse Juno
I don't know why but when I try to run again my Android app, the "Android Device Chooser" frame opens but my emulators are not shown in "Choose a running Android device" section. What should I do ?

A: Goto the DDMS view and try resetting the ADB as shown---

A: *

*Please check the required API levels of the application and than on the device.

*Try to run following commands in terminal that will renew the adb server state :
adb kill-server
adb start-server

*You can try to use adb over the wifi and than no cables will needed.


text:
Q: Unable to Parametrize Using TestNG in Selenium I am new to selenium and trying to parameterize username and password field using testing. This script only opens the URL for me and does nothing more. Can someone help me out here and let me know the appropriate way of achieving this?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

 public class Testcase1 {

  WebDriver driver=new FirefoxDriver ();
  driver.get("URL");
 // driver.manage().timeouts().pageLoadTimeout(60,TimeUnit.SECONDS);

@Test
@Parameters({"sUsername","sPassword"})
public  void login()

{

    WebElement objUsername = driver.findElement(By.xpath("//input[@placeholder='Username']"));
    objUsername.sendKeys("sUsername");

    WebElement objPassword = driver.findElement(By.xpath("//input[contains(@placeholder,'Password')]"));
    objPassword.sendKeys("sPassword");

    WebElement objLogin = driver.findElement(By.xpath("//span[contains(text(),'Login')]"));
    objLogin.click();

    if (driver.findElement(By.xpath("//a[.='LOGOUT']")).isDisplayed())
            {
        System.out.print("Test Case is Passed");
            }
    else
        System.out.print("Test Case is Failed");
            }

}

XML:
import java.util.concurrent.TimeUnit;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Smoke">
  <test name="Testcase1">
    <parameter name="sUsername" value="testuser"></parameter>
  <parameter name="sPassword" value="123"></parameter>
  <classes>
        <class name="org.param.testcases.Testcase1">
        </class>
    </classes>

    </test> <!-- Test -->
</suite> <!-- Suite -->

A: remove the import statement from xml and try again.

A: You need make following changes :
first :change    public void login() to public void login(String userName, String password)
and then :
objUsername.sendKeys("sUsername");  to   objUsername.sendKeys(userName);
objPassword.sendKeys("sPassword");  to   objPassword.sendKeys(password);


text:
Q: using a specific node ID to call a template file The standard template for a node in Drupal is node.tpl.php
It's possible to call a different template for a content-type, like 'newsitem'. You will call it like this :  node-newsitem.tpl.php.
I was wondering if there's a way to call a specific Node ID? node-34.tpl.php does not work.
Thanks

A: For Drupal 7 use this template name (34 - is node ID):
node--34.tpl.php

And don't forget to clear your cache! More information on drupal.org

A: In your theme's template.php put the following at the top of theme_preprocess_node():
$vars['template_files'][] = 'node-'. $vars['node']->nid;
So if your theme is called "myTheme", you might have the following:
function myTheme_preprocess_node(&$vars){
    $vars['template_files'][] = 'node-'. $vars['node']->nid;
}

A: I have this working as we speak.  In Drupal 6, my front page is node 5.  It uses

page-node-5.tpl.php

If it's not loading, consider clearing cache's or rebuilding your theme registry.

A: That naming convention will work, just not by default. Assuming this is Drupal 6, try adding the following code to your theme's template.php:
/**
* Override or insert variables into the node templates.
*
* @param $vars
*   An array of variables to pass to the theme template.
* @param $hook
*   The name of the template being rendered ("node" in this case.)
*/
function yourthemename_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  $vars['template_file'] = 'node-'. $node->nid;
}

Make sure you don't try to redeclare yourthemename_preprocess_node()--that is, if it already exists in your theme's template.php, just add the $node and $vars['template_file'] lines to it.


text:
Q: Mechanical Soup: Complex logins I am trying to create a python script with mechanicalsoup to login to verizon.com.
The login page itself loads just fine. The problem I am facing is the response after submitting my login. Verizon has a "please wait" loading screen after submitting credentials. So, when I print out the response to the login attempt, I am not greeted with my user dashboard or 2FA input field. I am instead only seeing the content of the "please wait" page when I print out the response. Is there a workaround for this without using something more robust like selenium?
Code:
import mechanicalsoup
import time

browser = mechanicalsoup.StatefulBrowser()
browser.set_user_agent('Mozilla/5.0')
browser.open("https://secure.verizon.com/vzauth/UI/Login")

browser.select_form('form[action="https://secure.verizon.com/vzauth/UI/Login"]')
browser.form.print_summary()
browser["IDToken1"] = "bobjohnson"
browser["IDToken2"] = "bobjohnson123"
resp = browser.submit_selected()
time.sleep(3)
print(resp.text)


text:
Q: How can I reduce the size of a linear model saved by a Shiny app? I'm trying to create a shiny app that allows me to fit linear models, display informations about them, and then save them.
I'm facing an issue : when I save a model, it takes a huge place. Here is a simplified code :
library(shiny)
library(ggplot2)

ui <- shinyUI(fluidPage(
    titlePanel("Save linear Model"),

    sidebarLayout(
      sidebarPanel(
        actionButton("save","SAVE !")
      ),

      mainPanel(
       textOutput("saved")
      )
    )
))

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

  load("donnees/new/V283/V283_complete.RData")

  observeEvent(input$save,{

    lm.fit<-lm(price~.,data=diamonds)
    save(lm.fit, file="question-x-validated/my-model.RData")
    output$saved<-renderText("Saved")

  })

})

shinyApp(ui = ui, server = server)

In fact, the more objects I create/load in my app, the bigger my saved model is. For exemple, the object I load with :
load("donnees/new/V283/V283_complete.RData")

is 275.1MB. If I save my lm.fit after loading it, my rdata file is 36.9Mb. If I save my lm.fit without loading it, my file is 13Mb.
If I save my lm.fit directly from R (without using my shiny app), the file is
6,57Mb
As suggested in this link, it might be an environment issue. But it seems to me that the fact I'm using shiny is adding some difficulties, as none of the technique suggested by the above link worked in my case.
I also tried using the saveRDS function. And also replaced :
lm.fit<-lm(price~.,data=diamonds)

by
assign("lm.fit",lm(price~.,data=diamonds),envir=globalenv())

It changes the file size, but It never gets as little as 6.57Mb.
As in my real code, I import really big data sets, my real models gets really huge (more than 500Mb), and It makes my Shiny App really slow when it loads/saves these models.
I would really appreciate any help you can provide.
EDIT :
It seems my issue comes from the "terms" element of my model, as if I do :
lm.fit<-lm.fit[1:11]

prior to saving my model, my file is 5.92Mb ! But as you know, the "terms" element is needed to use predict(). And only doing :
attr(lm.fit$terms,".Environment") = c()

does not work.
Also, funny thing :
lm.fit$terms<-NULL and lm.fit<-lm.fit[-12] does not change anything while lm.fit<-lm.fit[1:11]
does.

A: Check out this great post for some methods/info on reducing the size of the fat on glm/lm objects.
I use this method, which I took from the above.


text:
Q: MySQL SELECT/JOIN query cause deadlocks on production DB Following SQL query cause deadlocks on production MySQL DB on a Wordpress site with heavy load.
    SELECT
        lessons.ID AS lesson_id,
        resultmeta.meta_value AS status,
        lessons.post_title AS title,
        lessons.post_name AS slug,
        count(resultmeta.meta_value) AS nr_of_results
    FROM
        mv_posts AS lessons
    LEFT JOIN
        mv_posts AS results
    ON
        results.post_parent = lessons.ID AND
        results.post_type = 'we_result' AND
        results.post_author IN($students_string)
    LEFT JOIN
        mv_postmeta AS resultmeta
    ON
        results.ID = resultmeta.post_id AND
        resultmeta.meta_key = 'we_result_status_code'AND
        results.post_author IN($students_string)
    WHERE
        lessons.post_type = 'we_lesson' AND
        lessons.post_status = 'publish' AND
        lessons.ID IN($lessons_id)
    GROUP BY
        lessons.ID,
        resultmeta.meta_value;

With exactly the same DB on a test environment the query is executed in 0.005 seconds. The mv_postmeta table has over 3 million rows and the mv_post has over 1 million rows.
Probably concurrent INSERTS cause this problem and maybe a DB cache overload.
I tried to do READ COMMITED through wordpress wp_query with no success.
Do anyone have a tip for this? The dealocks shuts down the site for around 2 minutes.


text:
Q: Hibernate do not insert child object I am having the following Entities
@Entity
@Table(name = "school")
public class School {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "sch_id", unique = true, nullable = false)
    private Integer schoolId;

    ...
}

@Entity
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "stu_id", unique = true, nullable = false)
    private Integer studentId;

    ...

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "school_id", referencedColumnName = "sch_id", insertable = false, updatable = false, nullable = false)
    @JsonIgnore
    private School school;
}

Now when I am saving a new student object, the generated insert query for the student table does not contain the field 'school_id'.
SessionFactory.getCurrentSession().saveOrUpdate(student),

how can I include 'school_id' to the insert query. Please note I do not want to insert/update the school object. I just set schoolId in the school object and it is set into the students school object.


text:
Q: Python, lxml - access text I m currently a bit out of ideas, and I really hope that you can give me a hint:
Its probably best to explain my question with a small piece of sample code:
from lxml import etree
from io import StringIO

testStr = "text0text1

item1

item2

text2sib"
parser = etree.HTMLParser()
# generate html tree
htmlTree   = etree.parse(StringIO(testStr), parser)
print(etree.tostring(htmlTree, pretty_print=True).decode("utf-8"))
bElem = htmlTree.getroot().find("body/b")
print(".text only contains the first part: "+bElem.text+ " (which makes sense in some way)")
for text in bElem.itertext():
    print(text)

Output:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

    text0text1

item1

item2

text2sib

.text only contains the first part: text0 (which makes sense in some way)
text0
text1
item1
item2
text2
sib

My Question:
I would like to access "text2" directly, or get a list of all text parts, only including the ones that can be found in the parent tag.
So far I only found itertext(), which does display "text2".
Is there any other way I could retrieve "text2"?
Now you might be asking why I need this:
Basically itertext() is pretty much already doing what I want:

*

*Create a list, that contains all text found in an element's children

*However, I want to process tables and lists that are encountered with
a different function (which subsequently creates a list structure
like this: ["text0 text1",["item1","item2"],"text2"] or for a table (1. Row with 1 Column, 2.
Row with 2 Columns): ["1. row, 1 col",["2. row, 1. col","2. row, 2.
col"]])

Maybe I m taking a completely wrong approach?

A: You could just reimplement itertext() function and insert special handlers for ul, table if necessary:
from lxml import html

def itertext(root, handlers=dict(ul=lambda el: (list(el.itertext()),
                                                el.tail))):
    if root.text:
        yield root.text
    for el in root:
        yield from handlers.get(el.tag, itertext)(el)
    if root.tail:
        yield root.tail

print(list(itertext(html.fromstring(
                "text0text1

item1
"
                "
item2

text2sib"))))

Output
['text0', 'text1', ['item1', 'item2'], 'text2', 'sib']

Note: yield from X could be replaced by for x in X: yield x on older than Python 3.3 versions.
To join adjacent strings:
def joinadj(iterable, join=' '.join):
    adj = []
    for item in iterable:
        if isinstance(item, str):
            adj.append(item) # save for later
        else:
            if adj: # yield items accumulated so far
                yield join(adj)
                del adj[:] # remove yielded items
            yield item # not a string, yield as is

    if adj: # yield the rest
        yield join(adj)

print(list(joinadj(itertext(html.fromstring(
                "text0text1

item1
"
                "
item2

text2sib")))))

Output
['text0 text1', ['item1', 'item2'], 'text2 sib']

To allow tables, nested list in
 the handler should call itertext() recursively:
def ul_handler(el):
    yield list(itertext(el, with_tail=False))
    if el.tail:
        yield el.tail

def itertext(root, handlers=dict(ul=ul_handler), with_tail=True):
    if root.text:
        yield root.text
    for el in root:
        yield from handlers.get(el.tag, itertext)(el)
    if with_tail and root.tail:
        yield root.tail

print(list(joinadj(itertext(html.fromstring(
                    "text0text1

item1
"
                    "
item2

sub1
sub2

"
                    "text2sib")))))

Output
['text0 text1', ['item1', 'item2', ['sub1', 'sub2']], 'text2 sib']


text:
Q: My server was reported to hoster abuse to perform ddos attacks. What should I do? I do not see anything suspicious on the server (no netstat connections to remote 80 port), but I'm not a professional server admin (I'm a hardcore software developer). Please do not write obvious comments (hire a professional person/company) - we'll consider that after this issue is resolved. Server is running under Windows Server 2008 R2. What tools should I use to analyze this situation?
This is not an exact duplicate of multiple "what should I do if my server is hacked" as I basically need to provide evidence that my server is clean.
Basic security measures were taken since the beginning (windows firewall on, windows update pataches applied, Clamwin up and running).

A: Our ex-hosting company gave us a bad IP address when we got a new server. They then turned around and accused us of spamming because the IP address was in a spammer blacklist somewhere on the web. After a lot of wasted time we found that it was actually a previous customer of theirs had done done the spamming from that IP address. Make them prove to you what happened, when it happened, who reported it etc. AFAIK anyone can report an ip address to most of these sites without much proof

A: You can never be sure your system isn't compromised.  You can only implement reasonable security and integrity for your system based on the importance of system uptime, reliability, integrity etc.   You can't reasonably be asked to secure your system without the know how.

A:
Please do not write obvious comments (hire a professional
  person/company) - we'll consider that after this issue is resolved.

I'm sorry to say that you are not managing that security incident the right way then.
If there's a fire in your house, are you waiting for it to extinguish itself before calling the fire-fighters?
If you have nobody in staff that can handle that type of incident, then you should get help from external resources that can manage security breach.

A: Ask your ISP to produce logs showing your server's involvement in the incident (a suspicious traffic graph, for example, generated by data from your ISP's routers or switches).  If they can produce such evidence, your system is suspect.
If your machine was in fact involved in a DoS attack and you didn't initiate such action yourself your machine is almost certainly compromised.  If your system is compromised the best advice you will get is to blow it away, as in How do I deal with a compromised server? or any of the other questions similar to it.
For determining if your system was hacked, remember that you cannot rely on any tools installed on the system, and that a good attacker will leave no obvious trails (except possibly odd traffic, noted by an external system).  If you have any suspicion that your system was compromised, it is still compromised until it is rebuilt with known clean media and software.

A: Just because your server isn't executing a DDoS attack now doesn't mean it hasn't done so earlier, and it certainly doesn't mean that your server isn't hacked.
If the DC has traffic logs showing your server participating in an attack, then that should be all the evidence you need. Getting a copy of the logs might help you to determine what's wrong with your server -- pay particular attention to timing.
This isn't a job for someone with average admin training. Tracking this stuff down can be hard and requires you to use every trick you know and a lot of tricks you don't. You may be looking for a very tiny needle in a very large haystack. Even experienced admins have trouble with this sort of stuff.


text:
Q: A question about the continuity from above property of measure In my text book, the "continuity from above" of a measure is stated as the following.

$μ(A_k )→μ(A)$ if $μ(A_k )<+∞$ for some $k$ and $A_k↘A$, then

The following is the proof provided by the text book.

Without loss of generality, we assume $μ(A_1 )<+∞$. Then $μ(A_k )<+∞$ for all $k$.
$A_1=A+(A_1-A_2 )+(A_2-A_3 )+⋯$ where $A,A_1-A_2,A_2-A_3,…$ are disjoint. It is clear that $A_1-A_2,A_2-A_3,…$ are disjoint. $A$ and any of $A_1-A_2,A_2-A_3,…$ are disjoint because $A⊆A_k  ∀k$, thus $x∈A⇒x∉A_k-A_{k+1}$ since $x$ is both a member of $A_k$ and $A_{k+1}$.
Now $μ(A_1 )=μ(A)+μ(A_1-A_2 )+μ(A_2-A_3 )+μ(A_3-A_4 )+⋯=μ(A)+μ(A_1 )-μ(A_2)+μ(A_2 )-μ(A_3)+μ(A_3 )-μ(A_4)+⋯$
The terms in the middle can cancel out, therefore $μ(A_1 )=μ(A)+μ(A_1 )-\lim_{k→∞}μ(A_k)$, thus $μ(A)=\lim_{k→∞}μ(A_k)$.

The text book then explains that $μ(A_k )<+∞$ is necessary, for example, let $A_k$ be the complement of the ball centered at 0 with radius $k = 1,2,3,...$, then every ball has Lebesgue measure $+\infty$ and hence $\lim_{k→∞}μ(A_k)=+\infty$, but $A_k↘\emptyset$ and the measure of an empty set is zero.
I have a problem with the proof. It seems perfectly OK to me even if every $μ(A_k )=+∞$. I am not sure what is wrong with the proof when $μ(A_k )=+∞$ for all $k$.
I am not sure but my thinking is that things like $-\mu(A_2)+\mu(A_2)$ still seems to be $0$ even if $μ(A_2 )=+∞$ so the terms in the middle still cancel out?
And then we can still arrive at $μ(A_1 )=μ(A)+μ(A_1 )-\lim_{k→∞}μ(A_k)$?
And then the left-hand side $\mu(A_1)$ can still cancel the right-hand side $\mu(A_1)$?
Hope someone can help. Thank you!

A: When $\mu(A_k) =  \infty$ you cannot cancel out the terms in the middle since $\infty - \infty$ makes no sense.


text:
Q: Call to a member function View() on null My IF in this method forward to view variable $this->session['stCeneo'].
public function onCheckoutPostDispatch(\Enlight_Event_EventArgs $args)
    {
        $this->subject = $args->getSubject();

   if ('finish' === $this->subject->Request()->getActionName()) {
            $this->saveRequestToSession();

            $view = $subject->View(); //error?
            $view->assign('stCeneo', $this->session['stCeneo']); //error?

        }

$this->session['stCeneo'] is implemented in saveRequestToSession().
private function saveRequestToSession()
{
    if ($this->subject->Request()->getParam('stOpineo') !== null) {
        $this->session['stOpineo'] = $this->subject->Request()->getParam('stOpineo') ? true : false;
    }

    if ($this->subject->Request()->getParam('stCeneo') !== null) {
        $this->session['stCeneo'] = $this->subject->Request()->getParam('stCeneo') ? true : false;
    }
}

SO I don't know, why I have a error in my line commented:

Uncaught Error: Call to a member function View() on null

A: Okay, I resolved this problem. I write:
$this->subject->View()->assign('stCeneo', $this->session['stCeneo']);


text:
Q: form submitting only with one field I have this code to enter data and check all fields are correct. The validation works well but if i just input in last name field and click submit, the form submits and it shows username/email already registered and if i leave the last name field blank the form does not submits. What i want is the form should only submit when all the fields are entered correctly
<?php
include'connect.php';
require_once './config.php';
// define variables and set to empty values
$nameErr = $emailErr = $lnameErr = $fnameErr = $passErr = "";
$name = $email = $lname = $fname = $pass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
 $nameErr = "Username is required";
} else {
 $name = ($_POST["username"]);
 if (!preg_match("/^[a-zA-Z][a-zA-Z0-9-_\.]{5,30}$/",$name)) {
  $nameErr = "6 to 30 characters,alphanumeric, underscore & dots only";
}
}

 if (empty($_POST["email"])) {
 $emailErr = "Email is required";
 } else {
 $email = ($_POST["email"]);
 // check if e-mail address is well-formed
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
   $emailErr = "Invalid email address";
 }
 }

 if (empty($_POST["password"])) {
 $passErr = "Password is required";
 }else {
 $pass = ($_POST["password"]);
 if (!preg_match("/(?=^.{8,30}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/",$pass)) {
  $passErr = "Alphanumeric, Upper & Lower Case & Special Charcters required";
 }
 }

 if (empty($_POST["fname"])) {
 $fnameErr = "First Name is required";
 } else {
  $fname = ($_POST["fname"]);
  if (!preg_match("/^[a-zA-Z]{3,30}$/",$fname)) {
  $fnameErr = "3 to 30 characters, aplphabets only";
 }
 }
 if (empty($_POST["lname"])) {
 $lnameErr = "Last Name is required";
 } else {
 $lname = ($_POST["lname"]);
 if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
  $lnameErr = "3 to 30 characters, aplphabets only";
 }

else{
if (isset($_POST["sub"])) {
 $fname = trim($_POST["fname"]);
 $lname = trim($_POST["lname"]);
 $name = trim($_POST["username"]);
 $pass = trim($_POST["password"]);
 $email = trim($_POST["email"]);
 $sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";
 try {
 $stmt = $DB->prepare($sql);
 $stmt->bindValue(":email_id", $email);
 $stmt->bindValue(":username_id", $name);
 $stmt->execute();
 $result = $stmt->fetchAll();

 if ($result[0]["count"] > 0) {
  echo"
E-mail or Username Already Registered
";
 } else {
  $sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
  $stmt = $DB->prepare($sql);
  $stmt->bindValue(":fname", $fname);
  $stmt->bindValue(":lname", $lname);
  $stmt->bindValue(":name", $name);
  $stmt->bindValue(":pass", md5($pass));
  $stmt->bindValue(":email", $email);
  $stmt->execute();
  $result = $stmt->rowCount();

  if ($result > 0) {
  require_once "PHPMailerAutoload.php";
$lastID = $DB->lastInsertId();

$message = '
<title>Message</title>

';
$message .= '
Hello!
';

$message .= "";

// php mailer code starts
$mail = new PHPMailer(true);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 // sets the prefix to the servier
$mail->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port = 587;                   // set the SMTP port for the GMAIL server
$mail->Username = 'example@example.com';
$mail->Password = 'Password';
$mail->SetFrom('example@example.com', 'Name');
$mail->AddAddress($email);
$mail->Subject = trim("Verification");
$mail->MsgHTML($message);

try {
$mail->send();
header('Location: welcome.php');
}
catch (Exception $ex) {
$msg = $ex->getMessage();
$msgType = "warning";
}
} else {
$msg = "Failed to create User";
$msgType = "warning";
}
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
}
}
}
?>

<form id="defaultForm" action="html.php" method="post">
First Name
<input type="text" name="fname"><?php echo $fnameErr;?>

Last Name
<input type="text" name="lname"><?php echo $lnameErr;?>

Username
<input type="text" name="username"><?php echo $nameErr;?>

E-mail
<input type="text" name="email"><?php echo $emailErr;?>

Password
<input type="password" name="password"><?php echo $passErr;?>

<button type="submit" name="sub">Submit!</button>

A: First off... i'll like to implore you to indent your code... Looking at your code, the problem is tied to your lastname variable as the submission logic itself is inside this scope.
Currently your code looks like this
 if (empty($_POST["lname"])) {
  $lnameErr = "Last Name is required";
 }
else {
    $lname = ($_POST["lname"]);
   if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
    $lnameErr = "3 to 30 characters, aplphabets only";
   }
   else{
  if (isset($_POST["sub"])) {
    //Submission logic here
    }
  }
}

Take out the submission logic from the lastname block and try this
 if (empty($_POST["lname"])) {
  $lnameErr = "Last Name is required";
 }
else {
    $lname = ($_POST["lname"]);
   if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
    $lnameErr = "3 to 30 characters, aplphabets only";
   }
}

if(empty($lnameErr) && empty($otherError) && empty($anotherError))
{
    //Move Submission logic here
}
else {
   //Display errors
}

Your new code should look like this
<?php
include'connect.php';
require_once './config.php';
// define variables and set to empty values
$nameErr = $emailErr = $lnameErr = $fnameErr = $passErr = "";
$name = $email = $lname = $fname = $pass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["username"])) {
    $nameErr = "Username is required";
  }
  else {
   $name = ($_POST["username"]);
   if (!preg_match("/^[a-zA-Z][a-zA-Z0-9-_\.]{5,30}$/",$name)) {
      $nameErr = "6 to 30 characters,alphanumeric, underscore & dots only";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  }
  else {
   $email = ($_POST["email"]);
   // check if e-mail address is well-formed
   if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     $emailErr = "Invalid email address";
   }
  }
  if (empty($_POST["password"])) {
    $passErr = "Password is required";
  }
  else {
   $pass = ($_POST["password"]);
   if (!preg_match("/(?=^.{8,30}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/",$pass)) {
    $passErr = "Alphanumeric, Upper & Lower Case & Special Charcters required";
   }
  }

  if (empty($_POST["fname"])) {
    $fnameErr = "First Name is required";
  }
  else {
    $fname = ($_POST["fname"]);
    if (!preg_match("/^[a-zA-Z]{3,30}$/",$fname)) {
    $fnameErr = "3 to 30 characters, aplphabets only";
   }
  }

  if (empty($_POST["lname"])) {
    $lnameErr = "Last Name is required";
  }
  else {
    $lname = ($_POST["lname"]);
    if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
      $lnameErr = "3 to 30 characters, aplphabets only";
    }
  }

  if(empty($lnameErr) && empty($otherError) && empty($anotherError) && isset($_POST["sub"]))
  {
      //Move Submission logic here
       $fname = trim($_POST["fname"]);
       $lname = trim($_POST["lname"]);
       $name = trim($_POST["username"]);
       $pass = trim($_POST["password"]);
       $email = trim($_POST["email"]);
       $sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";
       try {
         $stmt = $DB->prepare($sql);
         $stmt->bindValue(":email_id", $email);
         $stmt->bindValue(":username_id", $name);
         $stmt->execute();
         $result = $stmt->fetchAll();

        if ($result[0]["count"] > 0) {
          echo"
E-mail or Username Already Registered
";
        } else {
            $sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":fname", $fname);
            $stmt->bindValue(":lname", $lname);
            $stmt->bindValue(":name", $name);
            $stmt->bindValue(":pass", md5($pass));
            $stmt->bindValue(":email", $email);
            $stmt->execute();
            $result = $stmt->rowCount();

            if ($result > 0) {
              require_once "PHPMailerAutoload.php";
              $lastID = $DB->lastInsertId();
              $message = '
              <title>Message</title>

              ';
              $message .= '
Hello!
';

              $message .= "";

              // php mailer code starts
              $mail = new PHPMailer(true);
              $mail->IsSMTP(); // telling the class to use SMTP
              $mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
              $mail->SMTPAuth = true;                  // enable SMTP authentication
              $mail->SMTPSecure = "tls";                 // sets the prefix to the servier
              $mail->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
              $mail->Port = 587;                   // set the SMTP port for the GMAIL server
              $mail->Username = 'example@example.com';
              $mail->Password = 'Password';
              $mail->SetFrom('example@example.com', 'Name');
              $mail->AddAddress($email);
              $mail->Subject = trim("Verification");
              $mail->MsgHTML($message);

              try {
                $mail->send();
                header('Location: welcome.php');
              }
              catch (Exception $ex) {
                $msg = $ex->getMessage();
                $msgType = "warning";
              }
            }
            else {
              $msg = "Failed to create User";
              $msgType = "warning";
            }
          }
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
  }
  else {
     //Display errors
  }

}
?>

<form id="defaultForm" action="html.php" method="post">
First Name
<input type="text" name="fname"><?php echo $fnameErr;?>

Last Name
<input type="text" name="lname"><?php echo $lnameErr;?>

Username
<input type="text" name="username"><?php echo $nameErr;?>

E-mail
<input type="text" name="email"><?php echo $emailErr;?>

Password
<input type="password" name="password"><?php echo $passErr;?>

<button type="submit" name="sub">Submit!</button>

Hope this helps...


text:
Q: Allow access to certain ports on the server, via only one of the server IP addresses I'm trying to allow access to certain ports on the server, via only one of the server IP addresses.
So for example if the server has two IP addresses:
1.1.1.1
1.1.1.2
I only want for example ports 25, 26 to be accessible via 1.1.1.2. I'm not trying to prevent any external IP addresses from accessing the ports, just trying to make sure that they can only access the ports on a certain IP address on the server.
I've been trying to write this using iptables, but I've so far been unsuccessful - I was wondering if anyone could help?

A: Assuming you have no existing rules for those 2 ports or any blanket accept rules, then these lines below are a good example.
These 2 lines will block access to port 25 and 26 on port 1.1.1.1. Assuming that the default policy is to accept packets.
iptables -A INPUT -p tcp --dport 25 -d 1.1.1.1 -j REJECT
iptables -A INPUT -p tcp --dport 26 -d 1.1.1.1 -j REJECT

Normally though, I would have the default policy on reject or drop and then explicitly allow the 2 ports on the second IP address.
iptables -P INPUT REJECT
iptables -A INPUT -p tcp --dport 25 -d 1.1.1.2 -j ACCEPT
iptables -A INPUT -p tcp --dport 26 -d 1.1.1.2 -j ACCEPT


text:
Q: How to use tf.dataset for making predictions? I feel that using using tf.dataset is very intransparent how and why stuff works. I just hang out here and wonder how to make predictions now that I have a model using again a tf.dataset. It is so easy to use numpy arrays.
If I use a tf.dataset in tf.keras.predict(), how does this model know what is the data data to use as input and what are the labels? Because I have labels in my data where I want to do predictions... I don't understand the way of using and understand the inner working.
Thanks for enlightment.
EDIT:
Also since I need this for a custom callback I wonder if the output of predict with a datsset is aligned with the labels of the origin data structure? How could I extract the labels from the dataset of which I did predictions?
Edit:
I have scores of predict:
   scores=bert_model.predict(test)

where test is a tf.datsaet which ahs 4 column with names. I actually don't know how to display a datset. I just can iterate with take(). Then the 1. element look like this:
({'input_ids': <tf.Tensor: shape=(15,), dtype=int32, numpy=
array([    3, 18414,  1169,    50, 18382,   239, 26972,     4, 11909,
         333,    30,  4445, 26918,   144,     4])>, 'token_type_ids': <tf.Tensor: shape=(15,), dtype=int32, numpy=array([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1])>, 'attention_mask': <tf.Tensor: shape=(15,), dtype=int32, numpy=array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])>}, <tf.Tensor: shape=(), dtype=int64, numpy=0>)

I just see that the last element has no key name? this is the label key.
So I think that internally the label key is ignored? Hopefully?
The first 3 keys should be used for predictions.
Also, Is the order of the result predictions the same as of the dataset used? Such that I can extract the labels from the dataset and do custom evaluation with the scores?


text:
Q: Create Batch Apex I'm having trouble creating a BATC apex. I need to make a condition in the start method
If the record type of opportunity equals donation executes a query if the record type = membership runs another query
global Database.QueryLocator start(Database.BatchableContext BC){
   ;

// if (r.DeveloperName.equals('Donation')){
 /*   return Database.getQueryLocator([
                SELECT Id, (...) Where Amount__c > 50
           else {
           */
            return Database.getQueryLocator([
                SELECT  Name, (....) Where Amount__c < 50

           ]);

But that doesn't result. Can anyone help?

A: Use this method like this:
String batchQuery;

if (r.DeveloperName.equals('Donation'))
{
    batchQuery = 'SELECT id FROM... Amount < 50';
}
else
{
     batchQuery = 'SELECT id FROM... Amount > 50';
}

return Database.getQueryLocator(batchQuery);

A: I always generate my queries for batches outside the batch - makes it easier to set, especially for testing...
So you have a batch class like this:
global class myBatchClass implements Database.Batchable<sObject> {

public String query;

global database.querylocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}

And then I invoke it like this:
myBatchClass thisBatch = new myBatchClass();

String batchQuery;

if (r.DeveloperName.equals('Donation') ) {
    batchQuery = 'SELECT id FROM... Amount < 50';
}
else  {
    batchQuery = 'SELECT id FROM... Amount > 50';
}

kwBatch.query = batchQuery;
database.executebatch(thisBatch);


text:
Q: DatePicker does not allow to choose October dates Problem is really weird.
On click of textbox, calender appears. If i choose sep/nov date any month except October, works fine with validation.
But if I select 1-10 to 31-10 then error appears, Please enter valid date.
I am not typing myself or setting anything.
Bellow my html code.

Select date (optional):

      <input id="istartDate" class="form-control" type="text" placeholder="Start date">

Find below jquery code.
$('#istartDate').datepicker({
    dateFormat: 'yy-mm-dd',
    prevText: '',
    nextText: ''
});


text:
Q: type '_InternalLinkedHashMap' is not a subtype of type 'BannerModel' every time i get that error and idk why?
class HomeModel {
  late bool status;
  late DataHomeModel data;

  HomeModel.fromjson(Map<String, dynamic> json) {
    status = json['status'];
    data = DataHomeModel.fromjson(json['data']);
  }
}

class DataHomeModel {
  List<BannerModel> banners = [];
  List<ProductModel> products = [];
  DataHomeModel.fromjson(Map<String, dynamic> json) {
    json['banners'].forEach((element) {
      banners.add(element);
    });
    json['products'].forEach((element) {
      products.add(element);
    });
  }
}

class BannerModel {
  int? id;
  String? image;
  BannerModel.fromjson(Map<String, dynamic> json) {
    id = json['id'];
    image = json['image'];
  }
}

class ProductModel {
  late int id;
  late dynamic price;
  late dynamic oldprice;
  late dynamic discount;
  late String name;
  late String image;
  late bool infavourite;
  late bool incart;

  ProductModel.fromjson(Map<String, dynamic> json) {
    id = json['id'];
    price = json['price'];
    discount = json['discount'];
    oldprice = json['old_price'];
    image = json['image'];
    name = json['name'];
    incart = json['in_cart'];
    infavourite = json['in_favourites'];
  }
}

A: The error most likely comes from the following class while you try to convert the elements to BannerModel elements.
class DataHomeModel {
  List<BannerModel> banners = [];
  List<ProductModel> products = [];
  DataHomeModel.fromjson(Map<String, dynamic> json) {
    json['banners'].forEach((element) {
      banners.add(element);
    });
    json['products'].forEach((element) {
      products.add(element);
    });
  }
}

At the line above code, you do not convert the items into the models that you need. So you need to fix that.
class DataHomeModel {
  List<BannerModel> banners = [];
  List<ProductModel> products = [];
  DataHomeModel.fromjson(Map<String, dynamic> json) {
    json['banners'].forEach((element) {
      banners.add(BannerModel.fromJson(element));
    });
    json['products'].forEach((element) {
      products.add(ProductModel.fromJson(element));
    });
  }
}


text:
Q: What does "Thin Pool" in docker mean? I guess this should be pretty elementary but I've tried to google it and I've read the docker documentation. However, I still can't grasp what exactly does "Thin Pool" mean and the role it plays in the docker world.

A: Short story:
A thin pool is a storage source that provides on-demand allocation for storage space. It is more or less similar to virtual memory, which provides full address space to every process.
Long story:
Fat Provisioning
The traditional storage allocation method is called "fat" or "thick" provisioning.
For example, a user claims to use 10G storage space. Fat provisioning then reserves 10G physical storage space for this user even though he/she only uses 1% of it. No one else can use this reserved space.
Thin Provisioning
Thin provisioning provides a mechanism of on-demand storage allocation, which allows a user to claim more storage space than has been physically reserved for that user.
In other words, it enables over-allocation for storage space. Think about RAM's over-commit feature.
Thin Pool
Thin pool is a conceptional term which stands for the backing storage source used by thin provisioning. Thin provisioning allocates virtual chunks of storage from thin pool, while fat provisioning allocates physical blocks of storage from the traditional storage pool.
Thin Pool in Docker
The Docker Engine can be configured to use Device Mapper as its storage driver. This is where you deal with thin provisioning. According to Docker's documentation:

Production hosts using the devicemapper storage driver must use direct-lvm mode. This mode uses block devices to create the thin pool.

Two different spaces of thin pool need to be taken care of: the Metadata space (which stores pointers) and the Data space (which stores the real data). At the very beginning, all the pointers in Metadata space point to no real chunks in the pool. No chunk in data space is really allocated until a write request arrives. This is nothing new if you are familiar with
the virtual memory mechanism.
Let's take a look at the output of docker info:
Data Space Used: 11.8 MB
Data Space Total: 107.4 GB
Data Space Available: 7.44 GB
Metadata Space Used: 581.6 kB
Metadata Space Total: 2.147 GB
Metadata Space Available: 2.147 GB
Thin Pool Minimum Free Space: 10.74 GB

Here, the only confusing one is the Thin Pool Minimum Free Space. What does it stand for?
It specifies the min free space in GB in a thin pool required for a new device creation to succeed. This check applies to both free data space as well as free metadata space.
Container creation (during docker pull or docker run) fails if free space in thin pool is less than the value in Thin Pool Minimum Free Space. Insufficient space requires either adding more storage into thin pool or clearing up unused images.

Links:

*

*Thin provisioning Wikipedia page

*lvmthin Linux man page

*The Device Mapper


text:
Q: Quit current dialog if user wants to stop I am using multiple dialogs. Some use formbuilder, some use a ResultAfter method for custom prompting of values. I want a method to check incomming messages on exit words like stop, quit etc.
I thought the StartAsync function would be a good start. Seeing all dialogs are forwarded from my RootDialog I have implemented this in the RootDialog:
    public override async Task StartAsync(IDialogContext context)
    {
        string[] stopStrings = { "quit", "cancel", "exit" };
        var msg = context.Activity.AsMessageActivity().Text;
        if (stopStrings.Any(msg.Contains))
        {
            await context.PostAsync("You cancelled.");
            context.Done(true);
        }
        else
        {
            context.Wait(this.MessageReceived);
        }
    }

When I ask the bot to "stop" it succesfully tells me I cancelled. But on the next message I send I get this error:
Exception thrown: 'System.Collections.Generic.KeyNotFoundException'

At this line in my MessageController:
await Conversation.SendAsync(activity, () => new RootDialog());

Now I am not sure what key is not found, and why it sends me this. Help is appreciated!

A: Generally, when someone wants to accomplish something like this such as a keyword to cancel they use scorables.  Scorables are global message handlers so if a keyword you set triggers one it gets handled before firing off your normal dialog flow.  There are some great resources out there for scorables like this blog or this video should get you started.
I wasn't actually able to reproduce this error, but here are some tips and thoughts. I don't think I have ever seen someone put logic in StartAsync and act as they would expect it to.  I wasn't able to figure out why you are overriding it the way you are when i was trying your code. The logic should be in MessageReceivedAsync.  Try moving your logic into the MessageReceivedAsync method. Another thing to try if you absolutely want to do it this way it to replace context.Done(true) with just context.Wait(this.MessageReceivedAsync); since you are in the RootDialog anyways, messages will just be routed there from the messages controller and you do not need to manually manipulate the dialog stack, although I do not know the structure of your project so I could be wrong.


text:
Q: SQL Query - Are they the same? I have two Queries here that will generate the same result.
Which do you think is better or maybe they are totally the same.
Query 1
SELECT
    ISNULL(col_1, col_2) AS col_1
FROM table_1
INNER JOIN table_2 ON table_2.col = ISNULL(col_1, col_2)

Or Query 2
WITH cte_table_1 AS
(
    SELECT
         ISNULL(col_1, col_2) AS col_1
    FROM table_1
)

SELECT
    cte_table_1.*
FROM cte_table_1
INNER JOIN table_2 ON table_2.col = col_1

A: It is not easy to predict this.
In general: SQL-Server is not a procedural engine working down statements, one after the other, as you've set this in your code. You tell SQL-Server what you want, and the engine will decide, what is the best way to achieve this. And this is done pretty well! This may vary from one call to the next depending on statistics, parallel actions, usage of memory, CPU or HD.
Even if it looks like this, the CTE is not handled like a table. Queries with multiple CTEs look like Oh, pick this result, than fetch these, now let's call these rows and now go into the main query! But the engine might decide for a completely different order of execution.
In your simple case I'd assume, that the engine is smart enough to see, that your queries are the same structurally.
Check the execution plans to see further details.
Update
You say: if they have the same EP result then we can say that its up to the user which is better to them as what is preferable to them?
Why should your users think about the internal structure of a query at all? It depends on so many factors you cannot control! You cannot even be sure, that the next call will be the same as the one before...
My strong advise is: Do not even try to out-smart the engine! Thousands of hours were spent into its algorithms... You should rather think about things like readability and maintenance...

A: *

*A CTE is essentially just a disposable view. It will pretty much never make a query any faster than just putting the CTE code into a FROM clause as a table expression.

*You have to use ISNULL(col_1, col_2) instead of ISNULL(col_1, col_2, col_1)

*The first query is a better choice because a simple query with one join has a better performance than using CTE

*Read more on CTE Here

A: ISNULL requires 2 argumnets
COALESCE we can pass multiple arguments
First query is better comparing to performance  because it is simple inner join but second query is some what not considered


text:
Q: How to update values of a dictionary in a json file? I'm trying to add user info to a nested dictionary within a json file. Here's the code.
import json

dictionary = {'name': 'Tony Stark', 'attributes': ['genius', 'billionaire', 'playboy', 'philanthropist']}

with open('info.json', 'a+') as file:
    json.dump(dictionary, file)

The info.json file
{'marvel': [
        {'name': 'Bill Gates', 'attributes': ['philanthropist', 'programmer']}
    ]
}

Now, I am unable to dump the dictionary as a value for marvel which is a list. I'm trying to make it dynamic, adding Tony Stark's info to the json file.
Please help me with that, thanks.

A: Alternative:
import json

dictionary = {'name': 'Tony Stark', 'attributes': ['genius', 'billionaire', 'playboy', 'philanthropist']}

def write_json(data, filename='file.json'):
    # function to add to JSON
    with open(filename,'w') as f:
        json.dump(data, f, indent=4)

with open('file.json') as json_file:
    data = json.load(json_file)
    data['marvel'].append(dictionary) # appending data to Marvel

write_json(data)

Edited as per observation of juanpa.arrivillaga


text:
Q: Linking two hardware serial ports I have two micro-controllers which are connected to my computer(ubuntu 12.04) through serial-USB cables.
One of the controllers (ttyUSB0) is programmed such that it sends data serially and another (ttyAMC0) is programmed to receive data serially.
So please any one could guide on achieving a link(send the data available at ttyUSB0 to ttyAMC0 ) between these two hardware ports.
Thanks in advance.

A: Well, the obvious way is to connect the two ports to each other, using a serial cable, without the two USB/serial adapters. Since you're not doing that, I presume its because you want the computer to do something—for example, this would be a reasonably common setup for reverse-engineering the protocol between the two devices.
Snooper is a program for just that: forward data between two serial ports, monitoring the communication.

A: Not sure if this is going to help... but I found this:
https://superuser.com/questions/403331/how-do-i-link-two-serial-ports-in-gnu-linux
It suggest the use of socat with a link to this page:
http://technostuff.blogspot.be/2008/10/some-useful-socat-commands.html
The command is on top:

socat /dev/ttyS0,raw,echo=0,crnl /dev/ttyS1,raw,echo=0,crnl


text:
Q: Device admin app for rooted android
We have our own rooted hardware device with android OS 7.0

We are building an app for that device. We have to restrict the users to performing some of the actions who will purchase that device. Here are the list of actions We want user to be restricted to perform on the device through the app.

*

*Stop installing/uninstalling any other apps from OS.

*On/off wifi

*Pair Bluetooth

*Change wallpaper

Basic idea behind is to make an app which will be the system app and will restrict user from the things mentioned above.
Is this possible to make such app? Looking for help in any of the above tasks. Thanks

A: Shor answer: NO.
Here is why;
The Android operation System is based on permissions, and no app can restrict that actions even with the users' permission. The reason for this is because of the Android App Layer that provides all the capabilities you described above.
The only way you can do such thing is to Customize the ROM of the CellPhone. In this case, you can override the functions that allow the user to use such services.


text:
Q: Potential buffer overflow when using realpath() in C I am reading this link related to secure coding in C. It contains the following paragraph:

In C and C++ programming languages, some functions take string as
input. Examples include realpath(), syslog() and getopt(). When such
functions are injected with an extensive amount of input buffer, a
buffer overflow attack can take place. As such, a good coder will
establish the greatest possible length of such input string required
for a particular program and shorten input strings appropriately prior
to invoking the realpath(), syslog() and getopt() functions.

Taking realpath() as example, the function signature is:
char *realpath(const char *path, char *resolved_path);

Based on the function signature, when someone calls this, they would have allocated and filled in the memory for the path argument. If the memory size allocated for the resolved_path result is not large enough, it may cause overflow. Is this analysis correct ? I'm not sure why the link I gave above says buffer overflow due to extensive amount of input buffer.


text:
Q: Uninstalling Android Studio I have gone through all of the previous threads, including all of the suggestions in the Completely Uninstall Android Studio thread, about uninstalling Android Studio and followed their directions and nothing helps. I installed Android Studio with the Standard installation but for a tutorial I'm following I need a Custom installation. I tried deleting the /android-studio folder along with the hidden /.android folder in my home directory and then re-extracting the folder from the original .zip file from here however every time I re-run the studio.sh file from my terminal it immediately restarts as was without re-installing. I have tried
sudo apt-get remove android-studio

and it tells me it cannot find the package. I've also tried every possible answer I've found so far including installing ubuntu-make and ppa:purge and nothing works. I can't even search for android studio in my task manager bar. I'm working on Ubuntu 16.04.

A: If you installed android studio using snap installation,then using this command
snap remove android-studio

will remove android studio

A: For me (gnome-ubuntu 17.04) this got rid of all android-studio installations I could see:
rm ~/.local/share/applications/androidstudio.desktop
sudo rm -rf /opt/androsudoid-studio/
rm -rf ~/.android/
rm -rf ~/.AndroidStudio2.1/
rm -rf ~/.AndroidStudio2.3/
rm -rf ~/Android
sudo rm -rf /opt/android-studio-ide-143.2790544-linux.zip
rm -rf ~/.gradle

Note: for you the build- and version numbers are probably different.
After that I could do a clean re-install and  finally got a clean, working android studio.

A: sudo snap abort --last=install
In my Case it worked well


text:
Q: Leaked GCP API Keys Your app contains exposed Google Cloud Platform (GCP) API keys. Please see this Google Help Center article for details enter image description here
I have used API_KEY="my_api_key" in gradle.properties file and added buildConfigField("String", "API_KEY", API_KEY) to app/gradle file and define
private static final String API_KEY = BuildConfig.API_KEY; to activity class and initiliized on create method Places.initialize(this, API_KEY);
I have tried to concate string also but same issue.
I restricted my API also in google console by adding SHA keys for both debug and release but still the same issue


text:
Q: Keep data on update using *ngFor Angular+2 I have breaking-news.component.ts and inside it I'm reading an API that returned breaking news, and I'm push the news using:
this.data = this.data || [];

this.response.news.forEach(news => {
this.data.push(news);
});

And breaking-news.component.html

            <mat-card>
                <mat-card-header>
...
...
...

{{news.text}}

...
...
...
              </mat-card-actions>
            </mat-card>

The news is perfectly displayed in my page using *ngFor, but the problem is when any updates come to the API it will not appear until I refresh the page, so the data array will not push the new data until the API called again by refreshing the page.

A: Some of your code seems to run outside Angulars zone, this is the reason Android doesn't recognize it needs to run change detection.
You can explicitely run code inside Angulars zone
constructor(private zone:NgZone) {}

foo() {
  this.zone.run(() => {
    this.data = this.data || [];

    this.response.news.forEach(news => {
      this.data.push(news);
    });
  });
}

but it would probably be better to figure out (and if possible fix) why your code runs outside the zone in the first place.


text:
Q: how to fetch data from database using dynamic mysql query by date range how to use date range function in this dynamic query for fetch data from database like fetch data from database from date  to date.
unset($sql);

    if ($stationFilter) {
        $sql[] = " STATION_NETWORK = '$stationFilter' ";
    }
    if ($verticalFilter) {
        $sql[] = " VERTICAL = '$verticalFilter' ";
    }

    $query = "SELECT * FROM $tableName";

    if (!empty($sql)) {
        $query .= ' WHERE ' . implode(' AND ', $sql);
    }

    echo $query;

A: Try following query to get dates between the range:
SELECT  * FROM    tableName WHERE   From_date >= '2019-01-03' AND  To_date   <= '2016-01-09'

Add

AND

condition to after
$query .= ' WHERE ' . implode(' AND ', $sql). 'AND From_date >= '2019-01-03' AND
    To_date   <= '2016-01-09'';

A: You can do it like below code
unset($sql);

if ($stationFilter) {
    $sql[] = " STATION_NETWORK = '$stationFilter' ";
}
if ($verticalFilter) {
    $sql[] = " VERTICAL = '$verticalFilter' ";
}
if (isset($start_date) && isset($end_date)) {
    $sql[] = " created_at between '".$start_date."' and '".$end_date."'";
}

$query = "SELECT * FROM $tableName";

if (!empty($sql)) {
    $query .= ' WHERE ' . implode(' AND ', $sql);
}

echo $query;

Hope it will help you.


text:
Q: Trying to Run Incremental Load Pipeline But failing Hi I have setup a simple pipeline that basically run each day and copies data between last day and the current day, my pipeline is failing and am not sure why, below is the attached code that I have been using can anyone help me why there is an error whenever I try to run this? my source is oracle and destination is Azure datawarehouse.
Code:
{
    "name": "Copy_sgd",
    "type": "Copy",
    "dependsOn": [],
    "policy": {
        "timeout": "7.00:00:00",
        "retry": 0,
        "retryIntervalInSeconds": 30,
        "secureOutput": false,
        "secureInput": false
    },
    "userProperties": [
        {
            "name": "Source",
            "value": "\"COMPANY_1_RPT\".\"V7261_0059_GL_DETAIL_VIEW\""
        },
        {
            "name": "Destination",
            "value": "[COMPANY_1_RPT].[V7261_0059_GL_DETAIL_VIEW]"
        }
    ],
    "typeProperties": {
        "source": {
            "type": "OracleSource",
            "oracleReaderQuery": {
                "value": "select * from \"COMPANY_1_RPT\".\"V7261_0059_GL_DETAIL_VIEW\" \nwhere \"GLPOSTINGDATE\" >= TO_DATE('@{formatDateTime(pipeline().parameters.windowStart, 'yyyy-MM-dd HH:mm' )}', 'YYYY-MM-DD HH24:MI') \nAND \"GLPOSTINGDATE\" < TO_DATE('@{formatDateTime(pipeline().parameters.windowEnd, 'yyyy-MM-dd HH:mm' )}', 'YYYY-MM-DD HH24:MI')",
                "type": "Expression"
            },
            "partitionOption": "None"
        },
        "sink": {
            "type": "SqlDWSink",
            "allowPolyBase": false,
            "preCopyScript": {
                "value": "delete * from \"COMPANY_1_RPT\".\"V7261_0059_GL_DETAIL_VIEW\" \nwhere \"GLPOSTINGDATE\" >= TO_DATE('@{formatDateTime(pipeline().parameters.windowStart, 'yyyy-MM-dd HH:mm' )}', 'YYYY-MM-DD HH24:MI') \nAND \"GLPOSTINGDATE\" < TO_DATE('@{formatDateTime(pipeline().parameters.windowEnd, 'yyyy-MM-dd HH:mm' )}', 'YYYY-MM-DD HH24:MI')",
                "type": "Expression"
            }
        },
        "enableStaging": true,
        "stagingSettings": {
            "linkedServiceName": {
                "referenceName": "adfv2logs",
                "type": "LinkedServiceReference"
            },
            "path": "adf-v2-logs"
        },
        "enableSkipIncompatibleRow": true,
        "redirectIncompatibleRowSettings": {
            "linkedServiceName": {
                "referenceName": "adfv2logs",
                "type": "LinkedServiceReference"
            },
            "path": "adf-v2-logs"
        },
        "translator": {
            "type": "TabularTranslator",
            "mappings": [
                {
                    "source": {
                        "name": "SOURCENAME",
                        "type": "String"
                    },
                    "sink": {
                        "name": "SOURCENAME",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "VENDNAMEIDX",
                        "type": "Decimal"
                    },
                    "sink": {
                        "name": "VENDNAMEIDX",
                        "type": "Decimal"
                    }
                },
                {
                    "source": {
                        "name": "VENDORID",
                        "type": "String"
                    },
                    "sink": {
                        "name": "VENDORID",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "VENDORNAME",
                        "type": "String"
                    },
                    "sink": {
                        "name": "VENDORNAME",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "NAME_DESCR",
                        "type": "String"
                    },
                    "sink": {
                        "name": "NAME_DESCR",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "NUM",
                        "type": "String"
                    },
                    "sink": {
                        "name": "NUM",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "DESCRIPTION",
                        "type": "String"
                    },
                    "sink": {
                        "name": "DESCRIPTION",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "DEBITAMT",
                        "type": "Double"
                    },
                    "sink": {
                        "name": "DEBITAMT",
                        "type": "Single"
                    }
                },
                {
                    "source": {
                        "name": "CREDITAMT",
                        "type": "Double"
                    },
                    "sink": {
                        "name": "CREDITAMT",
                        "type": "Single"
                    }
                },
                {
                    "source": {
                        "name": "AMT",
                        "type": "Double"
                    },
                    "sink": {
                        "name": "AMT",
                        "type": "Single"
                    }
                },
                {
                    "source": {
                        "name": "ACRUCASHTYPE",
                        "type": "String"
                    },
                    "sink": {
                        "name": "ACRUCASHTYPE",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "DEPTIDX",
                        "type": "Decimal"
                    },
                    "sink": {
                        "name": "DEPTIDX",
                        "type": "Decimal"
                    }
                },
                {
                    "source": {
                        "name": "DEPARTMENTID",
                        "type": "String"
                    },
                    "sink": {
                        "name": "DEPARTMENTID",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "DEPARTMENTNAME",
                        "type": "String"
                    },
                    "sink": {
                        "name": "DEPARTMENTNAME",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "ACCTIDX",
                        "type": "Decimal"
                    },
                    "sink": {
                        "name": "ACCTIDX",
                        "type": "Decimal"
                    }
                },
                {
                    "source": {
                        "name": "GLACCOUNTID",
                        "type": "String"
                    },
                    "sink": {
                        "name": "GLACCOUNTID",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "GLACCOUNTNAME",
                        "type": "String"
                    },
                    "sink": {
                        "name": "GLACCOUNTNAME",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "GLACCOUNTTYPE",
                        "type": "String"
                    },
                    "sink": {
                        "name": "GLACCOUNTTYPE",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "COSTCENTERIDX",
                        "type": "Decimal"
                    },
                    "sink": {
                        "name": "COSTCENTERIDX",
                        "type": "Decimal"
                    }
                },
                {
                    "source": {
                        "name": "COSTCENTERID",
                        "type": "String"
                    },
                    "sink": {
                        "name": "COSTCENTERID",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "COSTCENTERNAME",
                        "type": "String"
                    },
                    "sink": {
                        "name": "COSTCENTERNAME",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "CACMTY",
                        "type": "String"
                    },
                    "sink": {
                        "name": "CACMTY",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "CACROPRANCH",
                        "type": "String"
                    },
                    "sink": {
                        "name": "CACROPRANCH",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "PHASEIDX",
                        "type": "Decimal"
                    },
                    "sink": {
                        "name": "PHASEIDX",
                        "type": "Decimal"
                    }
                },
                {
                    "source": {
                        "name": "PHASEID",
                        "type": "String"
                    },
                    "sink": {
                        "name": "PHASEID",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "PHASENAME",
                        "type": "String"
                    },
                    "sink": {
                        "name": "PHASENAME",
                        "type": "String"
                    }
                },
                {
                    "source": {
                        "name": "GLPOSTINGDATE",
                        "type": "DateTime"
                    },
                    "sink": {
                        "name": "GLPOSTINGDATE",
                        "type": "DateTime"
                    }
                },
                {
                    "source": {
                        "name": "SOURCEIDX",
                        "type": "Decimal"
                    },
                    "sink": {
                        "name": "SOURCEIDX",
                        "type": "Decimal"
                    }
                },
                {
                    "source": {
                        "name": "SOURCEID",
                        "type": "String"
                    },
                    "sink": {
                        "name": "SOURCEID",
                        "type": "String"
                    }
                }
            ]
        }
    },
    "inputs": [
        {
            "referenceName": "SourceDataset_sgd",
            "type": "DatasetReference"
        }
    ],
    "outputs": [
        {
            "referenceName": "DestinationDataset_sgd",
            "type": "DatasetReference"
        }
    ]
}

Error
{
    "errorCode": "2200",
    "message": "ErrorCode=FailedDbOperation,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=A database operation failed with the following error: 'Parse error at line: 1, column: 8: Incorrect syntax near '*'.',Source=,''Type=System.Data.SqlClient.SqlException,Message=Parse error at line: 1, column: 8: Incorrect syntax near '*'.,Source=.Net SqlClient Data Provider,SqlErrorNumber=103010,Class=16,ErrorCode=-2146232060,State=1,Errors=[{Class=16,Number=103010,State=1,Message=Parse error at line: 1, column: 8: Incorrect syntax near '*'.,},],'",
    "failureType": "UserError",
    "target": "Copy_sgd"
}

A: This is clearly a syntax error in your query. I almost always solve this kind of issue with these steps:
1- Run your pipeline
2- When it fails, check the input of the copy activity, one of its values will be the exact query that the pipeline is building. Copy that.
3- Try running that query manually over the database, it will probably have a syntax error.
4- Fix the syntax in the query, then try replicating that fix in the pipeline.
And you should be good to go! If you need further help, post here and I'll try to help you.
Hope this helped!

A: Since you mentioned that the sink here is SQL , I am sure that the below syntax is wrong
"value": "delete * from XXXXX
It should be
"value": "delete from XXXXX .


text:
Q: Generate random values for golange I need a random password generator for a project, I need to make 10 of them. I found this function (random), but when I run it in a loop, it generates the same passwords. I don't know what's the problem.
func main() {

    for i := 0; i < 10; i++ {
        a := random()
        fmt.Println(a)
    }
}

func random() string {
    rand.Seed(time.Now().UnixNano())
    chars := []rune("abcdefghijklmnopqrstuvwxyz" + "0123456789")
    length := 10
    var b strings.Builder
    for i := 0; i < length; i++ {
        b.WriteRune(chars[rand.Intn(len(chars))])
    }
    str := b.String()
    return str
}

A: Adapting your example code and refactoring it a bit:
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rp := newRandPass(rand.New(rand.NewSource(time.Now().UnixNano())), 10, 10)
    fmt.Println(rp.passwords())
}

type RandPass struct {
    r   *rand.Rand
    num int
    len int
}

func newRandPass(r *rand.Rand, num, len int) *RandPass {
    return &RandPass{r, num, len}
}

func (r *RandPass) passwords() []string {
    chars := []rune("abcdefghijklmnopqrstuvwxyz" + "0123456789")
    passwords := make([]string, r.num)
    for i := 0; i < r.num; i++ {
        s := make([]rune, r.len)
        for j := 0; j < r.len; j++ {
            s[j] = chars[r.r.Intn(len(chars))]
        }
        passwords[i] = string(s)
    }
    return passwords
}

*

*

$ go run .
[rt97kzwjwe 5ziim05exh 40dfly93et v5tga5bwv9 avf2p2dpjx hsz4lca0jv 8r7bvvtu5l 9byf3mjq6r sdr2mpo54g cjx4mq6c0t]


text:
Q: WIX Custom Action Execution failed I have created a setup to execute scripts on database. But when i tried to run the setup i have got the following error which i have fetched out from logs.
Doing action: VerifyConnection Action 12:03:17: VerifyConnection.
Action start 12:03:17: VerifyConnection. MSI (c) (38:E0)
[12:03:17:739]: Invoking remote custom action. DLL: C:\Users\adityak\AppData\Local\Temp\MSI4F99.tmp, Entrypoint: VerifyConnection MSI (c) (38:A4) [12:03:17:741]: Cloaking enabled. MSI (c) (38:A4)
[12:03:17:741]: Attempting to enable all disabled privileges before calling Install on Server MSI (c) (38:A4)
[12:03:17:742]: Connected to service for CA interface. MSI (c) (38:54)
[12:03:17:788]: Note: 1: 1723 2: VerifyConnection 3: VerifyConnection 4: C:\Users\adityak\AppData\Local\Temp\MSI4F99.tmp  Error 1723. There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor.  Action VerifyConnection, entry: VerifyConnection, library: C:\Users\adityak\AppData\Local\Temp\MSI4F99.tmp  MSI (c) (38:54)
[12:03:19:186]: Product: CRMnext -- Error 1723. There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor.  Action VerifyConnection, entry: VerifyConnection, library: C:\Users\adityak\AppData\Local\Temp\MSI4F99.tmp

Action ended 12:03:19: VerifyConnection. Return value 3.
DEBUG: Error 2896:  Executing action VerifyConnection failed

Any Idea how to resolve this issue???

A: *

*Make sure your action has the correct signature; especially the method needs to be "public" and "static", i.e. something along the lines of "public static ActionResult doSomething(Session session)"

*Mark the mehtod with the "CustomAction" attribute, so it gets exported

*When dealing with multiple custom actions implemented in one dll, make sure you are not running into a known MakeSfxCA bug (cf. http://wixtoolset.org/issues/4502/ or Adding a new Custom Action to a project prevents an existing Custom Action from being run)


text:
Q: What's ground? Is it the point defined as 0 V of potential or voltage? If the latter, is it because we measure its voltage with respect to itself? I have some questions regarding the definition of ground that some people use. One question leads to the other so I've organized them below.
Some people say that "ground is the point/node defined as 0 V". Is this definition correct? If no, what is your definition of ground? If it's correct, keep reading. If they mean 0 V of electric potential, then just clarify me this and I have no further questions. But if they mean 0 V of voltage, then I have two thoughts:

*

*The definition of ground ("the
point defined as 0 V of voltage") is meaningless because voltage is the difference
between the (electrostatic) potential of two points, yet in the definition of ground,
they aren't specifying with respect to which point the ground has 0 volts. An example of
this is like saying "I'm 10 cm taller" without comparing yourself to anyone; that phrase
has no meaning. If you agree with me, do you have a more
precise definition of ground? If you disagree, please explain why.

*Ground is 0 V not because we define it like so, but because we
measure its voltage with respect to itself. If that's true, then the definition of ground
(point defined as 0 V of voltage) should be changed, since any point/node has 0 V when
you measure its voltage with respect to itself. So in a strict sense, according to the
definition of ground, all points/nodes are grounds! If you agree with me, do you have a more
precise definition of ground? If you disagree, please explain why.
Note: this question is not the same as mine, because they asked about the ground in circuit simulators (which is just a reference node when performing nodal analysis to solve the circuit) and about ground symbols. My question is about the conceptual definition of ground.

Edit Sep./22/2021
The following image helps clarify the structure of my questions. (I'm adding it in case someone reads these questions in the future.)

I think that what The Photon defined as ground (the node with respect to which we measure the nodal voltages), should actually be the definition of reference node, and that we should define ground as the node/point/region in space defined as zero potential (not zero voltage because that doesn't make sense, as I said above), besides the other uses of ground in electricity (ground of planet Earth as in where we stand, to ground as a verb to connect something to Earth ground, ground busbar, ground rod, ground/grounding wire, neutral/grounded wire, ground loop, the different ground symbols, etc.)

A: I think the term we use for the zero volt point in a circuit should really  be called "reference point" or "Common", rather than "Ground", but this misuse of the term "Ground" is so deeply embedded in electronics that we're stuck with it.
The point we call "Ground" in a circuit simulator, in your battery-powered circuit on a breadboard, or in a car, is simply the point we choose to call Zero Volts, and will use as a reference when measuring voltages elsewhere in the circuit.  It has no magic properties, and is no different than any other point in the circuit except that we've chosen to call it "zero volts".
In a circuit I might decide to call the negative terminal of the battery "Ground", while in the same circuit you might call the positive terminal of the battery "Ground".  Both decisions are equally valid, but we'd get confused while discussing the circuit with each other.
In some systems, like AC power distribution, and some radio antenna systems, "Ground" does really mean "A connection to the Earth".

A: There is no one definition of 'Ground'.
'Ground' is an over-used word that gets used to label several related but subtly different concepts.
The best way perhaps to think about it is in an operational or contextual way. That is 'if you want to do thing, then is something like ground useful to you here, and if so, how should it be defined?' The definition of 'ground' is the answer to that question.
a) If you want to refer to all the voltages in a circuit, is it useful to pick one of them, and define it as 0 V?
Absolutely.
b) If you have a circuit, and want to do (a), does it matter which point you choose to define as 0 V?
Yes and no. If you have a battery driven circuit operating at DC with no external connections, then it doesn't matter which terminal you define as 0 V. However, the circuit topology may treat one connection as common to many components, and it will be easier to design and analyse the circuit if that conductor is chosen to be ground.
If you have inputs and outputs referred to that common conductor, then you'd be making life difficult for yourself if you chose any other node as ground, but the circuit would still work regardless.
If it's an RF circuit, then the existence of a very common conductor means that things like stray capacitances are not equal to/from all nodes, but that the capacitance of any node will tend to be dominated by that to the common node. Here, you do need to choose that as ground, and connect it to the case, because with some RF designs, the strays have to be as designed in order for the thing to work.

So in a strict sense, according to the definition of ground, all points/nodes are grounds!

Are capable of being called ground, but cannot all be grounds at the same time. Once you've chosen one as ground, then the others, by definition, cease to be.
Both potential, and potential difference, are measured in volts. However, potential is also often called voltage. Don't let the plethora of names confuse you to what is actually being measured or referred to.
In much the same way, an altitude, and a difference of altitudes, are both measured in metres. A metre is very definitely a distance between two things. But how often do you hear a mountain being referred to like this? 'Everest is 8848 metres'. The altitude that's marked on a map is usually above a datum of mean sea level, just as those 132 kV powerlines are measured with respect to the large brown conductor the pylons are built on. However, if you're climbing a summit, the datum your legs care about is the height of your base camp. It depends what you want to use the potential or the potential difference for, for where you base it or how you describe it.

A:
Ground is 0 V not because we define it like so, but because we measure its voltage with respect to itself.

Ground is the point we choose to measure all voltages in the circuit with reference to.

So in a strict sense, according to the definition of ground, all points/nodes are grounds!

No, because we didn't choose them as the reference for measuring other voltages.
On a different day, we might choose some other node as the reference. That doesn't mean those nodes are the reference today.
As a comparison, just because any player on a soccer team is capable of acting as captain on any given day doesn't mean that all of them are captain today.


text:
Q: React JSX  tag population I am trying to populate an options tag with string values from an array with the following function:
render: function(){
  var array = ['yes','no'];
  var opts = array.map(function(name){return <option>name</option>});
    return(

      <select>{opts}</select>

      );
 }

The problem is that I receive
<option>name</option>
<option>name</option>

But I need
<option>yes</option>
<option>no</option>

Any ideas how to do that?

A: Wrap name into {}

var App = React.createClass({
  render: function(){
    var array = ['yes','no'];
    var opts  = array.map(function(name){
      return <option>{ name }</option>
    });

    return

      <select>{opts}</select>

  }
});

ReactDOM.render(<App />, document.getElementById('container'))


text:
Q: Using Wordpress with Apache behind an nginx reverse proxy I hope you can help me solving my issue.
I am running ngninx on a dedicated Server as a reverse proxy. My WordPress Application is on another VM, which is running apache2 as a Websever. Everything is working fine until I use "permalinks" in WordPress. I am receiving:
"The requested URL /contact-us/ was not found on this server."
Here is my config on nginx:
server {
        listen          443;
        ssl         on;
        server_name     foo.com;

        access_log  /var/log/nginx/foo.access.log;
        error_log   /var/log/nginx/foo.error.log;

        ssl_certificate           /etc/nginx/ssl-certificates/foo.de.crt;
        ssl_certificate_key       /etc/nginx/ssl-certificates/foo.de.key;

        ssl_protocols        SSLv3 TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers RC4:HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
        keepalive_timeout    60;
        ssl_session_cache    shared:SSL:10m;
        ssl_session_timeout  10m;

        location / {
            proxy_pass  https://111.111.111.111;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            proxy_set_header        Host            $host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        }

}
server {
    listen      80;
    server_name     foo.com;

    add_header Strict-Transport-Security max-age=2592000;
    rewrite ^/.*$ https://$host$request_uri? permanent;
}

I don't know the reason why I can't use permalinks. Anyone facing the same Problem?
Thanks in Advanced!

A: You're missing your Wordpress rewrite rules.
It's probably confusing because, in Apache, Wordpresss automatically generates the rewrite rules in .htaccess. It does not do the same in nginx environments.
Pay special attention to the Wordpress documentation on nginx and configuration directives referencing HTTP rewrite rules, the "includes" directives for segmenting configuration and the specific Wordpress rewrite rules that need to be present for pretty permalinks to work properly.
Without knowing a lot about your operating system, site/network or setup, I hesitate to copy and paste code without context. This section of the documentation is pretty thorough, and should provide what you're looking for.


text:
Q: relation between toValue and inputRange in animation In animation,what is the relation with toValue and inputRange?
 this.step1 = new Animated.Value(0);

 Animated.timing(this.buttonBottom,{
    toValue : 140,
    duration : 2000,
    easing : Easing.back(),
  }).start();
  const step1x = this.step1.interpolate({
    inputRange : [0,1],
    outputRange : [0,90],
  })

In this case,what is the defferences in case inputRange[0,1] and inputRange[0,2].
inputRange and toValue must be equal?


text:
Q: Angular chart doesn't show in my page I followed all the tutorial, included all the js and css necessary, the html is according to the tutorial and the chart created in my js doesn't show in my page.
Css and JS:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="js/angular-chart.js"></script>
<script src="js/angular-chart.min.js"></script>
<script src="js/bootstrap.min.js"></script>

ng-app and ng-controller:
<body class="container-full" ng-app="comando">

<div id=D12 class="col-md-12" ng-controller="fchart">
                <canvas id="line" class="chart chart-line" chart-data="data" chart-labels="labels" chart-legend="true" chart-series="series"
                    chart-click="onClick">
                </canvas>
            </div>

script.js:
var app = angular.module('comando', ["chart.js"]);

app.controller("fchart", function ($scope) {

    $scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
    $scope.series = ['Series A', 'Series B'];
    $scope.data = [
        [65, 59, 80, 81, 56, 55, 40],
        [28, 48, 40, 19, 86, 27, 90]
    ];
    $scope.onClick = function (points, evt) {
        console.log(points, evt);
    };
});

I have no idea whatelse i can do. I aprecciate the help........

A: There is an issue according to the github repo.
The solution is:

*

*Upgrade the angular-chart.js library to latest version by uninstalling the current version and reinstalling the new version. Assuming you are using bower otherwise, remove the references to both the Chart.js library and the angular-chart.js library and then add the v 2.x of Chart.js and v 1.0.0-alpha6 of  angular-chart.js to your project and add the references in your html file
bower install angular-chart.js#1.0.0-alpha6 --save

*In your controller, add a reference to store chart Options
$scope.chartOptions={
      legend: { display: true, position: 'bottom' }
    };

*If you are utilizing the legend feature, In your HTML file make the changes to the directive as follows
Remove the chart-legend attribute and replace with chart-options="chartOptions"
Example
<canvas id="line" class="chart chart-line" chart-data="data" chart-labels="labels" chart-legend="true" chart-series="series"
                chart-click="onClick">
            </canvas>

Becomes
<canvas id="line" class="chart chart-line" chart-data="data" chart-labels="labels" chart-options="chartOptions" chart-series="series"
                chart-click="onClick">
            </canvas>


text:
Q: Get Duplicates and Update Column in Different Table SQL I have two tables:
Poems:
---------------------------------------------------
|  id  |        poem        |        author       |
---------------------------------------------------
|   1  |   Blah blah Hey    |       Jane Doe      |
---------------------------------------------------
|   1  |   Yo yo Hey Bla    |       Jane Doe      |
---------------------------------------------------

Authors:
-----------------------------
|  id  |        name        |
-----------------------------
|   0  |                    |
-----------------------------

I want to remove the duplicates from the poems table and populate the newly created authors table. Ideally, I'd like to then update the authors (or create a new authors_id) column in poems table with author.id
I know that the following code shows me the duplicates,
SELECT author, COUNT(*)
FROM poem
GROUP BY author
HAVING
    COUNT(*) > 1

But how do I add them to the author.names column?
Also, will this code help me with the next part?
ALTER TABLE poem
     ADD COLUMN author_id serial,
     ADD CONSTRAINT author_id FOREIGN KEY (id) REFERENCES author (id) MATCH FULL;

Any ideas?

A: Try inserting from a select statement. For example like this:
    insert into Authors (id, author)
    select distinct id, author
    from Poems

A: To get a unique ID, you can use Postgres' distinct on operator:
insert into Authors (id, author)
select distinct on (id) id, author
from Poems
order by id

This will pick the first ID from the poems table for each author. Another alternative is to setup the poems table with a serial column:
If you have setup the id column as a serial column you shouldn't supply the value in the first place, just use:
insert into Authors (author)
select distinct author
from Poems;

By not specifying the id column, it will be populated automatically (if it is defined as serial)
But this:

ALTER TABLE poem
      ADD COLUMN author_id serial,
      ADD CONSTRAINT author_id FOREIGN KEY (id) REFERENCES author (id) MATCH FULL;

doesn't make sense. If you define the column as serial it will be incremented automatically each time you insert a row that doesn't specify a value for the column. How is that going to reference the id column of the authors table? I can't image any situation where it makes sense to define foreign key column as a serial
Once you have populated the authors table you do need to add an author_id column to the poem table, but it should not be a serial column:
ALTER TABLE poem
   ADD COLUMN author_id integer,
   ADD FOREIGN KEY (author_id) REFERENCES author (id);

Once you have that you can run an update:
update poem
  set author_id = author.id
from author
where author.name = poem.author;

After that you can drop the poem.author table.
SQLFiddle example: http://sqlfiddle.com/#!15/79b13/1


text: Q: NSPredicate with SortDiscriptor Currently I am trying to use NSFetchResultsController and I am using a predicate to fetch those results. Is there a possibility rather than using sort descriptor, to get the results sorted based on the predicate query using the keys in the array?


text:
Q: Css - Select with a background image and padding of selection (IE) I have a problem with select input to be properly displayed on Internet Explorer, though it works well on Firefox, Safari and Chrome.
Selection text goes all the way down to the left and should have 60px of left padding as on chrome, safari and firefox.
Please test it on the jsfiddle that I prepared. Could you help please?
HTML
<div id="form-selector">
<select name='someinput' id='someinput' class="form-control img-input">
<option value="" selected="selected">1</option>
<option value="">2</option>
</select>
</div>

CSS:
#form-selector select {
  overflow: -moz-hidden-unscrollable;
  width: 100%;
  height: 35px;
  background:#fff;
  margin-bottom:14px;
  font-size: 14px;
  color:#000000;
  -webkit-appearance: menulist;
}

// Firefox Fix
@-moz-document url-prefix() {
#form-selector select {
   text-indent: 30px;
} }

.img-input {
background:url(http://placehold.it/60x30) no-repeat left center #ffffff !important;
  padding-left:60px; }

JS FIDDLE
https://jsfiddle.net/nitadesign/02uj91gp/15/

A: @Nita I had no issues with
・Safari
・Chrome
・Opera
・IE 10
but I had issues with Firefox
try adding this to your code
#form-selector select {
    padding-left: 60px;
}

and by the way you can download safari for windows
EDIT
solution for Safari can be seen here
Padding doesn't work on select tags in Safari