text:
Q: Conflito de jQuery Estou tendo um conflito de jQuery. Eu uso um Admin, onde tem diversos recursos prontos. Precisei adicionar um autocomplete
Quando depois que terminei percebi que o menu não estava mais abrindo...rsrs
Esse é do menu e todo o Admin
<script src="assets/js/jquery-ui-1.10.3.custom.min.js"></script>

Esse é do autocomplete
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

Código do Autocomplete
$(function() {
    var availableTags = [
        <?php do { ?>
        {label: '<?php echo $row_rsOrigem['rsocial']; ?> - <?php echo $row_rsOrigem['cpf_cnpj']; ?>', value: '<?php echo $row_rsOrigem['cpf_cnpj']; ?>'},
        <?php } while ($row_rsOrigem = mysql_fetch_assoc($rsOrigem));?>
    ];

    $(".origemCPF").autocomplete({
        source: availableTags
    });
});

É possível usar os dois, sem ter problemas entre eles?

A: Tente usar jQuery.noConflict().
var $jQuery = jQuery.noConflict();

$jQuery(document).ready(function() {
  $jQuery("#ad").fadeIn("slow");
  $jQuery("#close").click(function () {
    $jQuery("#ad").fadeOut("slow");
  });
});

A: Você já tentou tirar um, testar e depois tira o outro e testar?? Pq pelo que estou vendo os dois são a mesma versão.
Tenta fazer o seguinte: Tire um e veja que o vai parar de funcionar, depois tire o outro e veja o que parou.
Muito provavelmente o jquery-ui-1.10.3.custom.min.js deve ter sofrido alguma alteração.
Se for possível mande o conflito que esta gerando.


text:
Q: WSDL generated files I've created a Web Application (with JSP) that uses a SOAP server endpoint to do some operations. I use gradle to automate the build. My problem is that when I run WebApp, it does not find the WSDL generated classes (and I've specified them in build.gradle).
My source files of servlet are in /src/main/java/servlets and generated WSDL files are in /src-gen/main/java/todo_soap.
Here my WebApp build.gradle:
    buildscript {
    repositories {
        jcenter()
    mavenCentral()
    }

    dependencies {
        classpath (group: 'com.sahlbach.gradle', name: 'gradle-jetty-eclipse-plugin', version: '1.9.+')
    classpath 'org.gradle.jacobo.plugins:gradle-wsdl-plugin:1.7.6'
    classpath 'org.gradle.jacobo.plugins:gradle-jaxb-plugin:1.3.4'
    }
}

apply plugin: 'com.github.jacobono.wsdl'
apply plugin: 'com.github.jacobono.jaxb'

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jettyEclipse'
apply plugin: 'eclipse'
apply plugin: 'eclipse-wtp'

repositories {
   mavenCentral()
}

dependencies {
   providedCompile 'javax.servlet:javax.servlet-api:3.0.1'
   compile 'com.google.code.gson:gson:2.3'
   jaxws "com.sun.xml.ws:jaxws-rt:2.2.8"
   jaxws "com.sun.xml.ws:jaxws-tools:2.2.8"
}

//
// See the documentation of this plugin at
// https://github.com/jacobono/gradle-wsdl-plugin
//

wsdl {
  wsdlFolder = "src/main/wsdl"
  wsimport {
    sourceDestinationDirectory = "src-gen/main/java"
    wsdlLocation = "http://localhost.com:8081/toDoSOAP?wsdl"
  }
}

sourceSets.main.java.srcDirs += wsdl.wsimport.sourceDestinationDirectory
compileJava.dependsOn wsimport

//
// Required by XJC because toDoSOAP.xsd is a file
//

System.setProperty('javax.xml.accessExternalSchema', 'all')

My full project here

A: I've just tested your code. Below is an example of the missing info that Martijn Courteaux requests:
/Users/javier/Downloads/Lab1-master/ToDo_SOAP_WebApp-ws/src/main/java/servlets/ToDoAddServlet.java:39: error: cannot find symbol
        ToDoWebServiceService twss = new ToDoWebServiceService();
        ^
symbol:   class ToDoWebServiceService
location: class ToDoAddServlet

The reason of the error is that you forgot to add import todo_soap.*; in the file ToDoAddServlet.java. If you look at src-gen\main\java you can see that the generated code belongs to the package todo_soap.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate product measure of off-diagonal set Let

*

*$(E,\mathcal E)$ be a measurable space

*$\mu_i$ be a probability measure on $(E,\mathcal E)$

*$\lambda:=\mu_1+\mu_2$ and $$f_i:=\frac{{\rm d}\mu_i}{{\rm d}\lambda}$$

*$Q$ denote the measure with density $\min(f_1,f_2)$ with respect to $\lambda$ and $$\nu_i:=\mu_i-Q$$

Let $\Delta:=\left\{(x,x):x\in E\right\}$. How can we show that $(v_1\otimes\nu_2)(\Delta^c)=\nu_1(E)\nu_2(E)$?

For simplicity, let $B:=\Delta^c=\left\{(x,y)\in E^2:x\ne y\right\}$ and $$B_y:=\left\{x\in E:(x,y)\in B\right\}=E\setminus\left\{y\right\}\;\;\;\text{for }y\in E.$$ We should have $$(\nu_1\otimes\nu_2)(B)=\int\nu_1(B_y)\nu_2({\rm d}y)=(\nu_1(E)-\nu_1(\left\{y\right\}))\nu_2(E)\tag1.$$ So, the conclusion would follow if $\nu_1(\left\{y\right\})=0$. But why should that be the case?

A: Let us write $f_1\wedge f_2$ for $\min\{f_1,f_2\}$. What we are required to prove is that $ (\nu_1 \otimes \nu_2)(\Delta)=0$. You can write the left side as $\int \int_{\{x\}} (f_2- (f_2\wedge f_1) (y))d\lambda(y) [f_1(x)- (f_2(x)\wedge f_1(x))]d\lambda (x)=0$. Note that if $f_2(x)- (f_2(x)\wedge f_1(x))>0$ then $f_2(x) >f_1(x)$ and hence  $(f_1- (f_2\wedge f_1) (x))=0$. This makes the double integral $0$.


text:
Q: Matplotlib plot legend shows markers twice The legend in my plot shows the marker icon twice in the legend

The code that produced this plot is given below
import pandas as pd
import random
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

N = 15

colors = cm.rainbow(np.linspace(0, 1, N))

df = []

for i in range(N):
    s = 'NAME %d' % i
    df.append(dict(x=random.random(), y=random.random(), name=s))

df = pd.DataFrame(df)
c = 0
labels = []

fig, ax = plt.subplots(figsize=(12,12))
for name, group in df.groupby('name'):

    x = group['x'].values[0]
    y = group['y'].values[0]

    color = colors[c]
    c += 1

    ax.plot(x, y, color=color, marker='o', linestyle='', label=name)

    labels.append(name)

handels, _ = ax.get_legend_handles_labels()
ax.legend(handels, labels)

Why is this happening?
My actual df has multiple entries for each name so that's why I do a groupby.  Is there something I'm missing here?

A: you can either set plt.legend(loc=...,numpoints =1) directly or create a style sheet and set legend.numpoints     : 1
If you use a linux system: place your stylesheets in ~/.config/matplotlib/stylelib/ you can use them with plt.style.use([your_style_sheet]). Additionally, you can e.g. make one sheet for the colors etc. and one for the size:  plt.style.use([my_colors,half_column_latex])


text:
Q: Prove Sequence of Functions Converges in Measure Let's consider a sequence of functions $f_n:[a,b] \rightarrow \mathbb{R}, f_n(x)=e^{-n|1-sin(x)|}$.  Show that $f_n$ converges to $f=0$ in measure.
Attempt/Thoughts:
To prove $f_n$ converges to $f=0$ in measure, I have to show that for every $\epsilon >0$,  $\mu (x:|e^{-n|1-sin(x)|}| \geq \epsilon) \rightarrow 0$ as $n \rightarrow \infty$.  This is clear to me pictorially as seen when we graph the sequence of functions, as n gets larger and larger, the set of $x$ for which $f_n(x)$ is positive grows smaller and smaller.  The peak grows narrower and narrower.  Thus for me, it is clear pictorially that $\mu (x:|f_n(x)-f(x)| \geq \epsilon) \rightarrow 0$ as $n \rightarrow \infty$.
exactly sure how to prove this formally, any
However, I'm not exactly sure how to prove this formally/ where to begin.
I do know that $0 \leq |e^{-n|1-sin(x)|}|=|\frac{1}{e^{n|1-sin(x)|}}| \leq |1|$, but this doesn't show convergence in measure.  Any help would be much appreciated, thanks.

A: Why don't you just observe that $f_n \to 0 $ except at a finite number of points (the points where $\sin \, x =1$) and almost everywhere convergence implies convergence in measure.


text:
Q: Imported external jar but still get "Cannot be resolved" errors I imported the external jar under Modulepath, following this guide. but im missing some if compared with those 2 in the guide. Could it be the reason why im still getting these errors? If thats the case, how can i get those or where can i download individually and import it?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class First {

    public static void main(String[] args) {
        // declaration and instantiation of objects/variables
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\limje\\JenAutomation\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

    // Launch website
        driver.navigate().to("http://www.google.com/");

        // Click on the search text box and send value
        driver.findElement(By.id("lst-ib")).sendKeys("javatpoint tutorials");

        // Click on the search button
        driver.findElement(By.name("btnK")).click();

    }

}

A: You are facing this issue because you need to fix your buld class path.
Once you add your jar files using Right Click on project --> Properties --> Click on apply and close

*Remove all imports from your project and hover over on a code  WebDriver driver = new ChromeDriver(); and click fix project setup. Once done then again hover over on Webdriver and import libraries into your solution.

*Finally your project looks like below and you havee to run your application as an java application


text:
Q: SharePoint 2007 - InfoPath form library not allowing new items I am in a very strange situation,  and have been working with Microsoft Support on the same.  With not much results.
We had a site in SharePoint 2007 with a InfoPath form library,  we had migrated this site to SharePoint 2013 and everything has been working perfectly.
This library currently have 4896 forms in it,  When i try to add another form in this library I get an error saying

form can not be submitted,  the site can not be found

When i delete few items from the existing library I am able to add new forms (exactly the same number of forms).  I have also created a new empty library by saving existing library as template.  And I am able to save the forms in the new library without any issues.
Notice the icon difference between the library that was migrated (v2) and the new library that was created by saving the same library as template (v3).

We have disabled threshold for this library,  increased quota for the site and increased threshold for the web application,  none of it is allow me to save any new form to the old library.
We also uploaded more number of forms in the new library (v3) and i am able to upload there without any issue.
I looked at the size and we had more data in (v3)

We are trying to identify if we had any hard limit in the SP2007 Form Libraries that is preventing us from uploading new forms.
I even tried exporting the (v2) forms and importing it onto (v3),  however looks like we do not have any option of importing forms onto a different library.
Any suggestions/information on the form library limit?  Please help

A: We resolved this issue ourselves,  it had nothing to do with InfoPath library size limit or anything else.
Our form used to create new items using an ID,   which was calculated based on the existing number of items.
Once of the user had created a draft version of InfoPath form and which as some id,  since the form was never checked-in,  all the new forms used to get the same ID and were not able to save data. Once we checked-in the files everything started working.
The biggest problems have easiest solutions... :)
But this is something to keep in mind,  error messages were taking us to all the wrong directions...


text:
Q: How to rewrite template function to allow code reuse Consider the following template recursion function. Its purpose is to create a vector containing all values in the enum class EnumClassName for which its associated predicate function bool xxx<N>() returns true.
template <EnumClassName N = EnumClassName::LAST_ENUM_VALUE>
std::vector<EnumClassName> xxx_stuff()
{
    std::vector<EnumClassName> v = xxx_stuff<EnumClassName(static_cast<int>(N) - 1)>();

    if (xxx<N>()) {
        v.emplace_back(N);
    }
    return v;
}

with the recursion base case:
template <> std::vector<EnumClassName> xxx_stuff<EnumClassName::FIRST_ENUM_VALUE>()
{
    return {};
}

Now assume there are 10 of these functions where the only thing that differs is the xxx name. I.e. we have the functions alpha_stuff with a corresponding predicate function alpha<N>, beta_stuff with a corresponding predicate function beta<N>, etc etc.
Is there any way to not duplicate the above function 10 times, where the only difference is the replacement of xxx with alpha, beta etc in each duplicate?
I am not able to just loop over the enum values, because the xxx<N> functions in turn call another function yyy<N> which will not accept a runtime-generated template argument <N> (forgive my lingo there, I actually have no idea what I'm talking about or how this works, I just know it gave me compilation errors when I tried it that way).

A: You cannot pass function template as argument or overloaded function, but you can wrap the call in a type, and then
template <typename EnumClassName,
          EnumClassName N = EnumClassName::LAST_ENUM_VALUE,
          typename F>
std::vector<EnumClassName> xxx_stuff(F&& f)
{
    std::vector<EnumClassName> v =
        xxx_stuff<EnumClassName, EnumClassName(static_cast<int>(N) - 1)>(f);

    if (f(std::integral_constant<EnumClassName, N>{})) {
        v.emplace_back(N);
    }
    return v;

}

with usage
auto v = xxx_stuff<E>([](auto n) { return xxx<n()>(); });

Demo
Note: That recursion can be avoided using std::integer_sequence.


text:
Q: Vuex blocking/freezing on websocket updates i didn't find a better way to word the title, sorry.
I'm building a table of crypto markets. (Vue/Vuetify v-data-table). Data is kept in a Vuex store.
I'm connecting to the (Laravel/Echo) API via Vue-Native-Websocket
Vue.use(VueNativeSock, url, {
  format: 'json',
  store: store,
  connectManually: true,
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 3000,
})

After opening the page in question, i'm subscribing to the update method
subscribeMarketUpdates() {
        let marketsToSubscribe = []

        const data = this.$store.state.exchange.markets
        const marketKeys = Object.keys(data)

        for (let i = 0; i < marketKeys.length; i++) {
          marketsToSubscribe = marketsToSubscribe.concat(data[marketKeys[i]].map(market => market.name))
        }

        this.$store.dispatch('sendExchangeSocketMessage', {
            "method": "state.subscribe",
            "params": marketsToSubscribe, // <- all currently present markets
            "id": Date.now(),
        })
      },

then i get back a success message, followed by the requested market update messages (one update message PER MARKET (!) ).
i handle them as follows:
SOCKET_ONMESSAGE (state, message)  {

      state.exchangeSocket.message = message

      if (message.method === 'state.update') {
        this.commit('exchange/UPDATE_MARKET_STATE', { params: message.params, BigNumber })
      }
}

UPDATE_MARKET_STATE(state, payload) {
      console.log('updating market ', params[0])

      let { params, BigNumber } = payload
      let coin = params[0].match(/(^.*)-/)[1]
      let market = params[0].match(/\w+$/)[0]
      let updatedValues = params[1]
      let resultIndex = state.markets[market].findIndex((e) => e.ticker === coin)
      let result = state.markets[market][resultIndex]
      result.amount = new BigNumber(updatedValues.amount).toFixed(8)
      result.change = new BigNumber(updatedValues.change).toFixed(8)
      result.change_pct = new BigNumber(updatedValues.change_pct).toFixed(4)
      result.close = new BigNumber(updatedValues.close).toFixed(8)
      result.high = new BigNumber(updatedValues.high).toFixed(8)
      result.last = new BigNumber(updatedValues.last).toFixed(8)
      result.low = new BigNumber(updatedValues.low).toFixed(8)
      result.open = new BigNumber(updatedValues.open).toFixed(8)
      result.period = updatedValues.period
      result.volume = updatedValues.volume
      state.markets[market][resultIndex] = result
    }
}

it kind of works, but i noticed it being painfully slow.
a console.time around the commit call reveals 400-700ms (!) for each execution.
each line inside UPDATE_MARKET_STATE reports 0.02ms though.
at first i thought something was wrong on the backend, but the guy working on that ensured me that all of the messages are sent within a couple of ms. there has to be something here on my end, that i'm not understanding. this is the backend log:
[2022-02-24 14:47:38.733082] [29576] [trace]aw_state.c:206(on_timer): send request to 127.0.0.1:1234, cmd: 301, sequence: 2544786, params: ["ETH-BTC", 86400]
[2022-02-24 14:47:38.733096] [29576] [trace]aw_state.c:206(on_timer): send request to 127.0.0.1:1234, cmd: 301, sequence: 2544787, params: ["404-BTC", 86400]
[2022-02-24 14:47:38.733108] [29576] [trace]aw_state.c:206(on_timer): send request to 127.0.0.1:1234, cmd: 301, sequence: 2544788, params: ["2GIVE-BTC", 86400]
[2022-02-24 14:47:38.733121] [29576] [trace]aw_state.c:206(on_timer): send request to 127.0.0.1:1234, cmd: 301, sequence: 2544789, params: ["$PAC-BTC", 86400]
[2022-02-24 14:47:38.733132] [29576] [trace]aw_state.c:206(on_timer): send request to 127.0.0.1:1234, cmd: 301, sequence: 2544790, params: ["1337-BTC", 86400]

(note all of the messages being sent nearly instantly)
the table for displaying the data seems to lock up too (i can only scroll the table each second, and it coincides with a console.log i made, so it really seems there is something blocking, even though i can't see anything that could be the culprit).
17:36:03.863 actions.js?4221:19 updating market  1337-BTC
17:36:04.646 actions.js?4221:19 updating market  2GIVE-BTC
17:36:05.421 actions.js?4221:19 updating market  2X2-BTC
17:36:06.264 actions.js?4221:19 updating market  404-BTC
17:36:07.030 actions.js?4221:19 updating market  ABJ-BTC
17:36:07.795 actions.js?4221:19 updating market  ACP-BTC
17:36:08.520 actions.js?4221:19 updating market  ADC-BTC
17:36:09.415 actions.js?4221:19 updating market  AERM-BTC
17:36:10.170 actions.js?4221:19 updating market  ALEX-BTC
17:36:10.977 actions.js?4221:19 updating market  AMBER-BTC

(note the update being called roughly each second, even though the ws messages are coming in much faster)
so my assumption is: there's something wrong in how i update my vuex store. something is blocking there, but i can't figure out what exactly. i don't see anything there that could possible cause this lock-up.
(i've also tried to handle the updates in an action (and calling the mutation from there) rather than a mutation, the result was the same, so here you see the mutation code)
i hope somebody can spot my error, because i can't :/
thanks for any help


text:
Q: Complex context-menu submenu I have a Qt5 application mainly driven by context menu.
Right now I have the standard structure with menu(s), submenu(s) and actions.
I would like to add, in place of a submenu, a small dialog with a few input widgets, something like this:

Is there any (possibly simple) way to get this?
I know I can open a normal dialog from popup, but that is not what I mean.
I would like to have normal submenu behavior, with chance to go back to parent menu... if possible.
Note: I'm actually using PyQt5, but I think this is a more general Qt question.

A: Following @G.M. advice I was able to partially solve my problem.
My code current code looks like:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class ActionFont(QWidgetAction):
    def __init__(self, parent: QWidget, target: QPlainTextEdit):
        super(ActionFont, self).__init__(parent)
        self.setIcon(QIcon("font-face.svg"))
        self.setText("Face")
        w = QFontComboBox()
        w.currentFontChanged.connect(self.doit)
        self.setDefaultWidget(w)
        self.cursor = target.textCursor()
        self.char_format = self.cursor.charFormat()
        font = self.char_format.font()
        w.setCurrentFont(font)
        # self.triggered.connect(self.doit)

    def doit(self, font):
        self.char_format.setFont(font)
        self.cursor.setCharFormat(self.char_format)

class ActionSize(QWidgetAction):
    def __init__(self, parent: QWidget, target: QPlainTextEdit):
        super(ActionSize, self).__init__(parent)
        self.setIcon(QIcon("font-size.svg"))
        self.setText("Size")
        self.has_changed = False
        w = QSpinBox()
        self.setDefaultWidget(w)
        self.cursor = target.textCursor()
        self.char_format = self.cursor.charFormat()
        font = self.char_format.font()
        size = font.pointSize()
        w.setRange(6, 100)
        w.setValue(size)
        w.valueChanged.connect(self.doit)
        w.editingFinished.connect(self.quit)

    def doit(self, size):
        print(f'ActionSize.doit({size})')
        self.char_format.setFontPointSize(size)
        self.cursor.setCharFormat(self.char_format)
        self.has_changed = True

    def quit(self):
        print(f'ActionSize.quit()')
        if self.has_changed:
            print(f'ActionSize.quit(quitting)')

class Window(QMainWindow):
    def __init__(self, parent=None):
        from lorem import text
        super().__init__(parent)
        self.text = QPlainTextEdit(self)
        self.setCentralWidget(self.text)

        self.text.setContextMenuPolicy(Qt.CustomContextMenu)
        self.text.customContextMenuRequested.connect(self.context)

        self.text.appendPlainText(text())

        self.setGeometry(100, 100, 1030, 800)
        self.setWindowTitle("Writer")

    def context(self, pos):
        m = QMenu(self)
        w = QComboBox()
        w.addItems(list('ABCDE'))
        wa = QWidgetAction(self)
        wa.setDefaultWidget(w)
        m.addAction('Some action')
        m.addAction(wa)
        m.addAction('Some other action')
        sub = QMenu(m)
        sub.setTitle('Font')
        sub.addAction(ActionFont(self, self.text))
        sub.addAction(ActionSize(self, self.text))
        m.addMenu(sub)

        pos = self.mapToGlobal(pos)
        m.move(pos)
        m.show()

app = QApplication([])

w = Window()
w.show()

app.exec()

This works with a few limitations:

*

*I have been able to add just a single widget using setDefaultWidget(), if I try to
add a fill QWidget or a container (e.g.: QFrame) nothing appears in menu.

*I have therefore not been able to prepend an icon (or a QLabel) to the widget.

*Widget does not behave like a menu item (it does not close when activated); I tried to overcome that as implemented in ActionSize, but looks rather kludgy and I'm unsure if it's the right way to go.

I will therefore not accept my own answer in hope someone can refine it enough to be generally useful.


text:
Q: HTTP Status 500 - Font 'Arial' is not available to the JVM I have made my report on iReport, in localhost it runs normally 'cause i got OS Microsoft , but when i run my project in Linux Server, the report show me an error
HTTP Status 500 - Font 'Arial' is not available to the JVM. See the Javadoc for more details.

net.sf.jasperreports.engine.util.JRFontNotFoundException: Font 'Arial' is not available to the JVM. See the Javadoc for more details.

I guess I have to install the Font in my Linux Server, but I got this server for Free on Jelastic, someone can help me Please 'cause i have to run this on my Linux Server rented.

A: Fonts are protected by copyright. If you don't have a license from the font owner to install it somewhere, it's better to try to use the fonts available on your target system.


text:
Q: How to Create AVD on version 4.0 APi 14 in Eclipse in Eclipse, I have installed the latest version Android 5.0.1(API 21) and created an AVD. However to test backward compatibility I need to create an AVD for older Android 4.0 (API 14), which is also installed in Eclipse. However, when go open Andriod AVD Manager and say create, in the Target pulldown menu, I do not see Android 4.0 (API 14) and therefore unable to create a AVD to support Android 4.0 (API 14). Can someone tell me how to do this please?

A: check whether Google API 14 in installed on your device.
Click Android SDK Manager, u can see SDK Manager, u can see Android 4.0(API 14) u can see Google APIs should be installed then only u can install the AVD otherwise u cannot create a AVD
If you want to create an AVD in Eclipse you need to do this:
Go to Window -> Android Virtual Device Manager
Then you need to give a name and select the platform that you want (Target option)
Then the button "Create AVD" activates.
The other options modify if u need

A: You can do following steps:
1. Open SDK Manager as this screen:

You must install SDK, Arm system image or Intel system image whose version as you need (mine is 21 and you is 14) for run emulator
2. Open AVD Manager and click "Create"

3. enter name, choose target and other properties. Then you have your emulator

Hope this help! And dont foget to mark this is answer if you archived your goal!


text:
Q: Can't type lowercase "q" in parallels When I type a lowercase "q" in any program on the Parallels side of my iMac, the parallels desktop disappears, and all of the open program windows appear to be floating in front of the Mac desktop (the Parallels icon in the dock still appears to be active).  When I type lowercase "q" again, the parallels desktop reappears with the program windows inside of it.  The lowercase q does not ever appear in the fields I'm trying to type within, it just causes the actions described above.  Uppercase Q and all other letters work just fine.  What's going on?

A: Sounds like q is activating and deactivating the "Coherence" feature of parallels. Check the parallels preferences for a hot-key assignment. In Coherence, the desktops are merged as you describe.


text:
Q: ACF | Problem with conditional fields values So I'm dealing with quite a weird issue with ACF.

*

*I have field B, which is set to appear only if field A == true. If A == true, B appears and I can change its value.

*In a given post, I have A == true and then I set a value to B. I save the post. All is well with the world.

*I then change my mind and I find that I do not want to have A == true, I want A == false. Field B disappears, as expected.

Problem: While field B disappears as expected, its value is still saved in the post and its still showing in the frontend.
My expectation: Since field B is hidden, it should have its value erased.
Has anyone else faced this issue? Am I wrong to expect that behaviour?

A: The behavious is as it is and this has the advantage, that when switch A back to true, B has it's old value again.
So you have to an if query in your code to use B only if A == true.


text:
Q: Clipping an image with GraphicsPath My problem is with clipping an image via GraphicsPath. I have a fairly complex clipping path (composed of various arcs) and I need to save only that part of the image that is within this path.
I have a class like this:
class A
{
    private GraphicsPath GetGraphicsPath()
    {
        ... some stuff ...
        return gp;
    }

    public void Draw(Graphics g)
    {
         g.DrawPath(pen, GetGraphicsPath());
    }

    public Save(Image img, string fileName)
    {
        Bitmap b = new Bitmap(img.Width, img.Height);
        Graphics bg = Graphics.FromImage(b);
        bg.Clip = new Region(GetGraphicsPath());
        bg.DrawImage(img, 0, 0);
        b.Save(fileName + ".png");
    }
}

and then I have a form with a panel pnMain, with a background image. I have two buttons with the following functions:
    private void button1_Click(object sender, EventArgs e)
    {
        Graphics g = pnMain.CreateGraphics();
        a.Draw(g);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Image img = pnMain.BackgroundImage;
        a.Save(img, "test");
    }

(in both cases a is an instance of A). My problem is that the clipping region drawn on screen (using first button and method Draw) is what I would like to save, however, the clipped image saved through second button and method Save is distorted, smaller and shifted. What am I missing?

A: I figured it out -- it is the resolution of the background image in the panel. The properties HorizontalResolution and VerticalResolution of the Bitmap img have to match the DPIX and DPIY properties of the Graphics. I did not found out how to set any of these via C#, but I was able to change the resolution of the bitmap in Photoshop and now everything works.


text:
Q: The "generator" of Taylor Series It's since a bit of time that I'm wondering if to ask this or not, but eventually I will, hoping it's not a stupid question.
Let's write the Taylor Series for a general function $f(x)$ around $x_0$:
$$\sum_{k = 0}^{+\infty} \frac{f^{k}(x_0)}{k!}(x-x_0)^k$$
Now let's call
$$f^{k}(x_0) = \frac{d^k}{dx^k} f(x)\big|_{x = x_0} = D^k_{x_o} f(x)$$
The Taylor Series expression now reads
$$\sum_{k = 0}^{+\infty}\frac{D^k_{x_0}f(x)}{k!}(x-x_0)^k$$
Which I can write as
$$\sum_{k = 0}^{+\infty} \frac{(D_{x_0}\cdot (x-x_0))^k}{k!}\ f(x)$$
But wait: this is nothing but (operatorially speaking)
$$\large e^{(x-x_0)\ D_{x_0}}f(x)$$
That is
$$f(x_0) + (x-x_0)D_{x_0}f(x) + \frac{1}{2}(x-x_0)^2 D^2_{x_0}f(x) + \ldots$$
which brings me to conclude that Taylor Series is nothing but the series of the exponential of the derivative of a function around a point, applied to the initial function $f(x)$.

*

*Is that correct?

*Moreover, since I came to this result, what meaning (if any) could have to take another "generator" (I beg your pardon for the illicit use of this word) like $\sin$ or $\sinh$ or whatever?
Thank you so much!

A: This can be given a sense in the theory of strongly continuous one parameter semi-groups of bounded operators in Banach and Hilbert spaces. Consider the translation operator
$$(T_t f)(x) = f(x + t)$$
This is for example an isometry in $L^2({\mathbb R})$, but other spaces are possible. $T_t$ is a one parameter group of bounded operators, that is to say
$$T_t T_s = T_{t+s}\qquad T_0 = I$$
This group is generated by an unbounded closed operator with a dense domain, defined by
$$A f = \lim_\limits{t\to 0} \frac{1}{t}(T_t f - T_0 f)$$
when the limit exists. Here the limit exists if $f\in H^1({\mathbb R})$ and
$$A f = \frac{d }{d x} f$$
Then the group can be identified with the exponential of the unbounded generator, that is to say
$$T_t = e^{t A} = e^{t\frac{d}{d x}}$$
Or, the translation operator is the exponential of the derivation operator.
For suitably smooth function, you can then justify the Taylor series by expanding the exponential series
$$f(\cdot + t) = T_t f = \sum_0^\infty \frac{t^k}{k!} \left(\frac{d}{d x}\right)^k f$$


text:
Q: conditionally change array used in foreach loop I want to conditionally change the array that is looped though with foreach loop and send var in
Url = domain.com/myphppage.php?myarray=$array1

Script has two arrays. Also $_GET is used to get var from url and finally foreach loop that uses one of the two arrays to output array content on to the page.
    <?php
    $array1 = array(1,2,3,4)
    $array2 = array(5,6,7,8)
    ?>

    <?php
    $arrayused = $_GET['myarray'];
    echo $arrayused;
    ?>

    <?php foreach($arrayused as $item): ?>
     some html code to show loop values
    <?php endforeach; ?>

The var is passed by url as it is shown on page as output by echo $arrayused.
I am expecting that the $arrayused variable will also be picked up by the foreach and looped through whichever of the two arrays that is in the variable.
However, it doesn't pick up variable and does not go into the foreach loop. If I hardcode either of the two array names into the foreach statement, then the foreach loop works fine.
Why doesn't the foreach statement appear to 'recognize' the variable that is retrieved from url? It prints on page just before the loop so it is obviously available?

A: It doesn't work 'cause for PHP, $_GET['myarray'] is a string not a variable, even it have a $ in it.
You have to specify to use a variable which has this string for name.
So, you can use your array like this:
$arrayused = ${$_GET['myarray']};

foreach($arrayused as $item) {
    // ...
}

A: Use a switch.
switch($_GET['myarray']) {
case '$array1':
    $arrayused = $array1;
    break;
case '$array2':
    $arrayused = $array2;
    break;
}

A: If I understand you correctly - $arrayused is a string that can be 'array1' or 'array2'.
Than you should add additional $ to the beggining of variable (Variable Variables).
Here is the code sample:
<?php
$array1 = array(1,2,3,4);
$array2 = array(5,6,7,8);
?>

<?php
$arrayused = 'array1';
echo $arrayused;
?>

<?php foreach($$arrayused as $item): ?>
    some html code to show loop values
<?php endforeach; ?>

A: I would just send the key with the URL, then you can insert the key right away, and don't have to do fancy tricks. Try it like this:
// URL: http://www.domain.com/page.php?myarray=1
$my_arrays = array(
    1 => array(1, 2, 3, 4),
    2 => array(4, 5, 6, 7)
);

$array_used = $my_arrays[$_GET['my_array']];
foreach($array_used as $item) {
    // do stuff with the array
}

And if you want to be a bit more safe, or want to prevent errors, grab the array like this:
$array_used = array_key_exists($_GET['my_array'], $my_arrays)
        ? $my_arrays[$_GET['my_array']]
        : array();

The empty array (the 'else' part of the ternary) can be anything you like, but like this you don't have to do an extra check (like: if($array_used == 'NOTFOUND') {})


text:
Q: Short story about humans being robots controlled by aliens I have read this short story long time ago in a Czech anthology so the author might originally be from Russia.
The story is about a scientist making a bombastic announcement that humans are robots controlled by aliens. Obviously nobody believes him. At the end of the story the scientist is summoned in front of some aliens who told him that he is causing too much trouble.

A: Either this is the story I am thinking of or it is damned close. The story is Sitting Duck, and was published in a short-story collection The 6 Fingers Of Time and Other Stories. I don't remember the author.
The story goes like this: a guy goes on a hunting trip with his father-in-law. They set up in a duck blind and wait. The father-in-law explains that all the decoy equipment they use is only useful to a point, that in every flock there is one smart duck who sees through the illusion,  and that's the duck you shoot first, so he doesn't alert the rest. The guy then proceeds to go through a series of experiences which show that aliens are doing something similar (setting up a fake store and shooting the people who shop there from behind a false wall, fake robot people being used to fool them and all) and realizes that he is the smart duck, and the aliens are gunning for him.


text:
Q: Create a logic captcha from scratch I haven't touched a scrap of code yet, but here's my thoughts on how to do this:
Create a :interactions entry in my session hash. This will contain an array of time stamps. Every time a user goes through any action, the time they did this will be appended to the :interactions entry. The array will be initialized in my sessions controller, and timestamps appended to it via a filter in my application controller:
class SessionsController < ApplicationController
    def create
        create_session
        session[:interactions] = []
    end
end

class ApplicationController < ActionController::Base
    after_action :log_time

    private

    def log_time
        session[:interactions] << Time.now.to_i
    end
end

Then, create another action in my application controller, the one tasked with launching the recaptcha if the user's behaviour is suspicious. All it does is see when we have 20 entries in our session[:interactions] array, find out the time elapsed between each pair of consecutive entries, and then find the average time elapsed between these interactions. If the average time is under two minutes, the recaptcha is launched. The session[interactions] array is then reset.
class ApplicationController < ActionController::Base
    after_action :log_time
    before_action :launch_captcha

    private

    def launch_captcha
        if session[:interactions].length == 20

            elapsed = []

            session[:interactions].each_slice(2) do |a, b|
                elapsed << b - a
            end

            total = elapsed.inject(:+)
            average = total / 20

            if total < 120
               # this a part I'm really not sure how to do:
               # various instance variables should be populated here
               redirect_to 'application/launch_captcha.html.erb'
            end

            session[:interactions] = []
        end
    end

    def log_time
        session[:interactions] << Time.now
    end
end

Now, the fact the session[:interactions] is reset may be a bit of a weakness; all bets are off for those twenty interactions. But I want to build on the above logic, maybe add session[:captchas_sent], to the session hash (or even have captchas_sent as a column and save it to the user's record), and if the session[:captchas_sent] is x amount or y amount, warnings or temporary bans could come into effect.
What are your thoughts on the above way of monitoring user behaviour?
Here's where my knowledge of rails is starting to break down though. Once I've redirected the user to the recaptcha page, how should I proceed? I have two tables, questions and answers with a has_many belongs_to relationship between them respectively.
So a random question will come from my questions table, and then I'll have a form that pertains to an answer. It will be an ajax form, and have just one field, a text field for the answer. The action the form links to, human test, will see if the answer given is equal to one of the question's answers. But how should the question's id be passed into this action? It couldn't be a simple hidden field, because once the spammer knows the answer to one question, his script could always set the id to that one question. So the params hash or the sessions hash maybe? I need some advice here guys.
I also don't really know how the human test method should proceed once the it finds the user's answer is equal to one of the question's answers:
Let's say the user is submitting a comment. They fill in the comment, hit the submit button, the launch_captcha action kicks in, and redirects them to 'application/launch_captcha.html.erb'. What has happened to the data in the comment create form? Once they've answered the captcha correctly, how should the human_test method proceed? How could it go on to submit their comment as usual? I just don't know how to do that...I need to create an action that is called before the create action of a form...and..argh I just don't know. Help guys!


text:
Q: Config Transform, Unrecognized XML Namespace After Transformation One of our config files is being transformed oddly.
Base Config
<?xml version="1.0"?>
<configuration >

</configuration>

Release Config (as it is in the project, truncated for brevity)
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore xdt:Transform="Insert">
    <contentSearch>
      <configuration>
        <indexes>
          <index id="sitecore_web_index">
            <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_web_index</param>
          </index>
        </indexes>
        <indexes role:require="Standalone or ContentManagement">
          <index id="sitecore_master_index">
            <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_master_index</param>
          </index>

After a build is run, the output of the final config looks very strange:
Post build
<?xml version="1.0"?>
<configuration>
    <sitecore>
        <contentSearch>
            <configuration>
                <indexes>
                    <index id="sitecore_web_index">
                        <param desc="core" d7p1:instead="param[@desc='core']" xmlns:d7p1="http://www.sitecore.net/xmlconfig/">ASHQA_web_index</param>
                    </index>
                </indexes>
                <indexes d5p1:require="Standalone or ContentManagement" xmlns:d5p1="http://www.sitecore.net/xmlconfig/role/">
                    <index id="sitecore_master_index">
                        <param desc="core" d7p1:instead="param[@desc='core']" xmlns:d7p1="http://www.sitecore.net/xmlconfig/">ASHQA_master_index</param>
                    </index>

Notice how the patch and role definitions are changed to d7p1 and d5p1 respectively.
While this is valid XML, it is causing issues in our application which parses the XML and looks for the proper terms of patch and role.

A: TL;DR
Any namespaces required in a transformed config, need to be defined in the base config.
Base Config Updates
<?xml version="1.0"?>
<configuration xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">

</configuration>

Even though the base config does not rely on these namespaces, they do not carry over properly if they are not included. This also cleans up the output of the resulting config as expected:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:patch="http://www.sitecore.net/xmlconfig/">
    <sitecore>
        <contentSearch>
            <configuration>
                <indexes>
                    <index id="sitecore_web_index">
                        <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_web_index</param>
                    </index>
                </indexes>
                <indexes role:require="Standalone or ContentManagement">
                    <index id="sitecore_master_index">
                        <param desc="core" patch:instead="param[@desc='core']">#{IndexEnvironment}#_master_index</param>
                    </index>


text:
Q: nginx route all requests to a pre-backend service before sending to upstream I need to route every request to 2 upstreams one after another (1st auth-server, 2nd misc-server). 1st upstream may or may not add headers and may/ may not alter request body.

Upstreams API can be POST/GET

Can we do something like below with nginx:
    upstream auth-server {
        server localhost:8800 weight=5;
    }
    upstream misc-server {
        server localhost:8800 weight=5;
    }

    server {
    location /misc {
        proxy_pass http://auth-server/misc/auth/pre; #1st route to this
    }
    location /misc {
        proxy_pass http://misc-server/misc; #2nd route to this
    }

}

The reason I'm trying to achieve this is for request validation by 1st upstream ie auth-server before actually routing request to destination upstream ie misc-server. Is this advisable?


text:
Q: SQL Server SELECT INTO and Blocking With Temp Tables So, recently a DBA is trying to tell us that we cannot use the syntax of
SELECT X, Y, Z
INTO #MyTable
FROM YourTable

To create temporary tables in our environment, because that syntax causes a lock on TempDB for the duration of the stored procedure executing.  Now, I've found a number of things that detail how temporary tables work, scope of execution, cleanup and the like.  But for the life of me, I don't see anything about blocking because of their use.
We are trying to find proof that we shouldn't have to go through and do CREATE TABLE #MyTable... for all of our temporary tables, but neither side can find proof.  I'm looking for any insight SO people have.
Additional Information
Currently working with SQL Server 2005, and soon to be SQL Server 2008  (Enterprise editions)

A: That advice has been floating around for a long time:

Bottlenecks in SQL Server 6.5
Many people use a SELECT...INTO query
  to create a temporary table, something
  like this:
SELECT * INTO #TempTable FROM
  SourceTable
While this works, it creates locks
  against the tempdb database for the
  duration of the SELECT statement
  (quite a while if you are trawling
  through a lot of data in the source
  table, and longer still if the
  SELECT...INTO is at the start of a
  longer-running explicit transaction)
  While the lock is in place, no other
  user can create temporary tables. The
  actual location of the bottleneck is a
  lock on tempdb system tables. In later
  versions of SQL Server, the locking
  model has changed and the problem is
  avoided.

Fortunately, it was only a problem for SQL 6.5. It was fixed in 7.0 and later.

A: This will probably float around for a long time, feeding the pockets of various 'consultants'. Like all myths, it has a kernel of truth and a lot of BS.
The truth: SQL 2000 and previous versions had known contention issues around the allocation of extents in tempdb. The contention was true in fact in all databases, but more visible in tempdb due to some heavy tempdb usage. It is documented in KB328551:

When the tempdb database is heavily
  used, SQL Server may experience
  contention when it tries to allocate
  pages.
From the sysprocesses system table
  output, the waitresource may show up
  as "2:1:1" (PFS Page) or "2:1:3" (SGAM
  Page). Depending on the degree of
  contention, this may also lead to SQL
  Server appearing unresponsive for
  short periods.
These operations heavily use tempdb:
  Repeated create and drop of temporary
  tables (local or global).
  Table variables that use tempdb for storage
  purposes.
  Work tables associated with
  CURSORS.
  Work tables associated with
  an ORDER BY clause.
  Work tables associated with an GROUP BY clause.
  Work files associated with HASH PLANS.
Heavy and significant use of these
  activities may lead to the contention
  problems.

A trace flag -T1118 was added in SQL Server 2000 SP3 that was forcing SQL to use a round-robin algorithm for mixed pages allocations. This new algorithm, when correlated with the practice of deploying tempdb on top of a set of equal size files, one for each CPU, would alleviate the contention. The trace flag is still present in SQL 2005/2008, although its far less likely to be needed.
Everything else about this myth is pretty much BS.

*

*does use of #temp tables cause blocking? No. At worst it increases contention under load in SQL 2000 and earlier, but that is a far cry from saying that it blocks anything. You would have to measure first and see that this is the case, and if so deploy the remediation measures (allocate one tempdb file per CPU, make them equal size, turn on -T1118)..

*Does select ... into #temp block something for the duration of the select? Not really.

*Does select ... into #temp block something for the duration of the stored procedure containing the select? Hell no. Just reading that claim and I burst into laugh.

For more details, there is this article: Misconceptions around TF1118.

A: Why not do the following?
SELECT X, Y, Z
INTO #MyTable
FROM YourTable
WHERE 1 = 2

The statement would run instantly - creating your temp table and avoiding any possible locking. Then you could insert into it as usual:
INSERT #MyTable
SELECT X, Y, Z
FROM YourTable

A: You can get blocking if you create #temp tables inside a transaction. While this is generally not recommended I have seen this done a lot.
However the blocking this causes is on some system tables in tempdb that do not affect other connections from creating temp tables (except perhaps for SQL versions prior to 2000?). It does mean that running sp_spacesused on tempdb will block unless you set transaction isolation level to read uncommitted. Also viewing properties on tempdb from SSMS will fail and timeout no doubt because it is using read committed transaction isolation level.

A: While SELECT INTO has been fixed from blocking the tempdb i would use caution when writing such code as under testing some system tables do get blocked.
Reference:
http://www.sqlservercentral.com/Forums/Topic1642797-2799-1.aspx

A: I would say lack of locking proof means no locking, which is your proof.  Why would the method that the temp table is created in (CREATE or SELECT ... INTO) make a difference in locking TempDB?

A: Well if that were true then mssql would have problems, since any large query can make use of tempdb to hold a copy of the rows. This can often be seen in the query plans as a table spool or can be used by the HASH JOIN operator if it runs out of memory for its buckets.
You can look at using table variables, which mssql will try to store in memory and move to tempdb if they grow to large.
DECLARE @foo TABLE (x int, y int, z int)
INSERT INTO @foo(x, y, z) SELECT x, y, z FROM YourTable

Of course, you should evaluate if the temporary table and copy is required first. Though if the query is complex enough that using a temp table is far more readable it might also be complex enough for a temp table to be worthwhile.

A: SELECT INTO #temp_table holds a shema lock in tempdb for the duration of the statement because part of the work it's accomplishing is creating the table.  This is fundamentally different than first creating the table using CREATE TABLE #.... and then running a set based INSERT.  SELECT INTO does have advantages over INSERT, in particular the operation is minimally logged if the recovery model of the database is simple or bulked log.


text:
Q: Browser stops responding to events during function execution, breaking "draggables" I have a slider a little like this:
             ________
------------|        |---------------------------------------
   :    <-- | slider | -->    :        :        :        :
------------|________|---------------------------------------

I'm using jQuery UI to make the slider draggable. This works fine.
The problem is that I'm executing a function each time the slider crosses a section boundary (indicated by :). This function takes approximately 30ms to execute (it's constructing a DocumentFragment and inserting it into the document). During this time the browser does not respond to events, so jQuery UI stops adjusting the slider's position and the drag is prematurely ended (the user is forced to release the mouse button and commence a new drag). This makes the slider feel jerky and buggy.
Is there a solution to this problem?
Edit: I've created a simple fiddle which demonstrates the problem. Note that while the drag is essentially paused during the execution of the slow function, it resumes afterwards. This makes me suspect that there's something about my more complex scenario which is causing the drag event to be cut short (perhaps the DOM manipulation is causing the position of the slider to change briefly).
Edit: After further investigation I'm much closer to understanding the problem. The DOM manipulation code contains a line something like $('.droppable').remove(). This removes the matching elements from the DOM after detaching any event handlers bound to them and removing any associated data. If I use .detach() instead, the behaviour is the same as in the simple fiddle above. Something untoward is happening during the cleanup.

A: I'd suggest to use jQuery's or Underscore's debounce function, or some equivalent method, to call the function just once every 100 or 200 ms or so.
This won't make things smooth, but at least they won't feel buggy.
Interesting article about it.


text:
Q: Custom mail headers using MIME in Java I want to create a new custom header while sending email, but by using setHeader() and addHeader() methods I am unable to do it.
How can I create a user defined X-"" email header?

A: setHeader() works for me. In below case, I set encoding options to mail header.
String mail_body = "
Mail Body
This is mail body of Test mail.";
String encodingOptions = "text/html; charset=UTF-8";

MimeMessage message = new MimeMessage(session);
message.setContent("Hello", "text/plain");
message.setSubject(mail_subject);
message.setText(mail_body);
message.setHeader("Content-Type", encodingOptions);
message.setSentDate(new Date());

You can see message header in receiving email with https://support.google.com/mail/bin/answer.py?hl=en&answer=22454
Sample program.
Mail.java
package com.test.mail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mail {
    private String host = "smtp.gmail.com";

    private String mail_to = "xxxx@gmail.com";

    private String mail_from = "aaaa@abc.com";// using gmail server

    private String mail_subject = "Subject of this test mail";

    private String mail_body = "
Mail Body
This is mail body of Test mail.";

    private String personalName = "xxx";

    private String encodingOptions = "text/html; charset=UTF-8";

    public void sendMail() throws SendFailedException {
        try {

            Properties props = new Properties();
            Authenticator auth = new Email_Autherticator();

            //props.put("mail.smtp.host", host);
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "587");
            System.out.println(props);

            Session session = Session.getDefaultInstance(props, auth);

            MimeMessage message = new MimeMessage(session);
            message.setContent("Hello", "text/plain");
            message.setSubject(mail_subject);
            message.setText(mail_body);
            message.setHeader("Content-Type", encodingOptions);
            //message.setHeader(mail_head_name, mail_head_value);
            message.setSentDate(new Date());

            Address address = new InternetAddress(mail_from, personalName);
            message.setFrom(address);

            Address toaddress = new InternetAddress(mail_to);
            message.addRecipient(Message.RecipientType.TO, toaddress);

            System.out.println(message);

            Transport.send(message);
            System.out.println("Send Mail Ok!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // return flag;
    }

    public static void main(String args[]) {
        try {
            Mail mailObj = new Mail();
            mailObj.sendMail();
        } catch (Exception e) {

        }
    }
}

Email_Autherticator.java
package com.test.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class Email_Autherticator extends Authenticator {
    String username = "froml@gmail.com";

    String password = "password";

    public Email_Autherticator() {
        super();
    }

    public Email_Autherticator(String user, String pwd) {
        super();
        username = user;
        password = pwd;
    }

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}


text:
Q: How do I retrieve data independently from nested JSON objects that are part of the same group in android/java? ( more clarity/details in body) I have a pretty common scenario, but I am stuck trying to figure out how to retrieve data from certain json objects within the same json response but returning different size of items.
To make it less confusing, here's my json response:
{
    "totalResults": 5,
    "meetings": [
        {
            "id": "754e6670-2376-4eb2-b5f6-ea63ca7c2669",
            "dateStart": "2019-11-28T15:25:36.000Z",
            "dateEnd": "2019-11-28T23:00:36.000Z",
            "visitors": [
                {
                    "visitId": "34608af6-bbe4-439c-b472-500790385f60",
                    "firstName": "Lord",
                    "lastName": "Wilkins",
                    "email": "  lwilkins@df.dj",
                },
                {
                    "visitId": "fe61e1f0-34f1-4701-b806-45395980acfb",
                    "firstName": "cg",
                    "lastName": "cg",
                    "email": "cg@gg.hg",
                },
                {
                    "visitId": "226eed33-b2ca-4406-b085-8534c2f87c69",
                    "firstName": "ar",
                    "lastName": "fg",
                    "email": "ar@gg.hh",
                }
            ]
        },
        {
            "id": "cf6934c1-3800-4b79-9d0f-570934097d26",
            "dateStart": "2019-11-30T00:00:06.000Z",
            "dateEnd": "2019-11-30T02:00:06.000Z",
            "visitors": [
                {
                    "visitId": "03a01b91-f307-4a04-ae7a-71a5e3e183c5",
                    "firstName": "ar",
                    "lastName": "fg",
                    "email": "ar@gg.hh",
                }
            ]
        },
        {
            "id": "a46130c3-5b80-419e-8c57-e17428d4b735",
            "dateStart": "2019-11-28T13:00:09.000Z",
            "dateEnd": "2019-11-29T02:45:09.000Z",
            "visitors": [
                {
                    "visitId": "5068a774-1cf3-45e2-af65-b98ab4dfbff2",
                    "firstName": "dot",
                    "lastName": "mn",
                    "email": "dtmn@gg.gh",
                }
            ]
        }
    ]
}

If anyone's interested here's my model class: https://pastebin.com/fUmiBiQP
Now, I am trying to retrieve the date start and date end and place it on top of first and last name and email, something like this :
" Nov 28, 2:00pm - 6:00 pm
  lord wilkins
  lwilkins@df.dj

  Nov 28, 2:00pm - 6:00 pm
  cg cg
  cg@gg.hg"

Notice how I repeat the same date that applies to entries grouped together , I want to achieve that, but currently I just am able to retrieve first and last name and email, but not the date based on how I have arranged my code. Everytime I try to modify the code to include meetings start and end date it crashes with either an index out of bounds exception due to size or null pointer exception.The issue happens in adapter.
Here's my adapter code for reference:
public class UpcomingGuestListAdapter extends RecyclerView.Adapter<BaseViewHolder>  {

    private Context context;
    private UpcomingGuestListAdapter.Callback mCallback;
    private List<UpcomingGuestsList.Visitor> mUpcomingGuestListResponseList;
    private List<UpcomingGuestsList.Meeting> mUpcomingGuestListResponseMeetingList;

    public class MyViewHolder extends BaseViewHolder {
        public TextView name, email, arrivalDate;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            Timber.d("viewholder butterknife bind");
            name = itemView.findViewById(R.id.upcoming_guest_name);
            email = itemView.findViewById(R.id.upcoming_guest_email);
            arrivalDate = itemView.findViewById(R.id.arrival_date);
            ButterKnife.bind(this, itemView);
        }

        @Override
        protected void clear() {

        }
        public void onBind(int position) {
            super.onBind(position);
            final UpcomingGuestsList.Visitor guest = mUpcomingGuestListResponseList.get(position);
            final UpcomingGuestsList.Meeting meeting = mUpcomingGuestListResponseMeetingList.get(position);

            String guestWholeName = guest.firstName + " "+ guest.lastName;
            if( guest.getFirstName() != null && guest.getLastName() != null) {
                name.setText(guestWholeName);
            }

            if (guest.getEmail() != null) {
                email.setText(guest.getEmail());
            } else {
                email.setText("");
            }

            String meetingDate = meeting.dateStart + "-"+ meeting.dateEnd;
            if( meeting.getDateStart() != null && meeting.getDateEnd() != null) {
                arrivalDate.setText(meetingDate);
            }
            itemView.setOnClickListener(v -> {
                if(mCallback != null) {
                    mCallback.onItemClick( guest.getFirstName(), guest.getLastName(), guest.getEmail());
                }
            });

        }

    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_upcoming_guest, parent, false);

        return new UpcomingGuestListAdapter.MyViewHolder(itemView);
    }

    public interface Callback {
        void onItemClick(String guestFirstName, String guestLastName,String guestEmail);

    }

    @Override
    public long getItemId(int position) {
        Timber.d("item id for eventlist adapter : %s",position);
        return position;
    }

    public void addItems(@NonNull List<UpcomingGuestsList.Visitor> repoList) {

        mUpcomingGuestListResponseList.addAll(repoList);
         notifyDataSetChanged();
    }

    public void addMeetingItems(@NonNull List<UpcomingGuestsList.Meeting> meetingList) {
        mUpcomingGuestListResponseMeetingList.addAll(meetingList);
        notifyDataSetChanged();
    }
    @Override
    public void onBindViewHolder(BaseViewHolder holder, final int position) {
        holder.onBind(position);

    }

    public UpcomingGuestListAdapter(Context context, List<UpcomingGuestsList.Visitor> visitorGuestList, List<UpcomingGuestsList.Meeting> meetingList) {
        Timber.d("SearchGuestListAdapter constructor");
        this.context = context;
        this.mUpcomingGuestListResponseList = visitorGuestList;
        this.mUpcomingGuestListResponseMeetingList = meetingList;

    }

    @Override
    public int getItemCount() {

        return (mUpcomingGuestListResponseList  != null)?mUpcomingGuestListResponseList.size():0;
    }

    public void setCallback(UpcomingGuestListAdapter.Callback callback) {
        mCallback = callback;
    }

}

Here's the code in activity where it gets the data from :
   @Override
    public void updateUpcomingGuestList(List<UpcomingGuestsList.Visitor> guestList,List<UpcomingGuestsList.Meeting> meetingList) {

        mUpcomingGuestAdapter.addItems(guestList);
        mUpcomingGuestAdapter.addMeetingItems(meetingList);
        mUpcomingGuestAdapter.notifyDataSetChanged();
    }

In the same activity this is how I set my adapter on create :
   guestList = new ArrayList<>();
        mUpcomingGuestAdapter = new UpcomingGuestListAdapter(this, guestList, meetingList);
        mUpcomingGuestAdapter.setCallback(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mUpcomingGuestAdapter);
        mPresenter.onViewPrepared();

and the code for on viewprepared where i retrieve the json data :
 @Override
    public void onViewPrepared() {
        getCompositeDisposable().add(getDataManager()
                .getUpcomingGuestListApiCall(AppPreferencesHelper.getInstance().getCurrentUserId())
                .subscribeOn(getSchedulerProvider().io())
                .observeOn(getSchedulerProvider().ui())
                .subscribe(response -> {
                    int sizercount = 0;
                    for (int i = 0; i <response.totalResults; i++) {
                            Objects.requireNonNull(getMvpView()).updateUpcomingGuestList(response.meetings.get(i).getVisitors(),response.getMeetings());

                            sizercount++;
                    }

                    totalGuests = sizercount;

                    Timber.d("total results value is : from upcomingguests %s",response.totalResults);
                    getDataManager().getUpcomingGuestsList();
                    AppPreferencesHelper.getInstance().setTotalUpcomingGuestCount(sizercount);

                }, throwable -> {
                    if (!isViewAttached()) {
                        return;
                    }

                    // handle the error here

                    if (throwable instanceof ANError) {
                        ANError anError = (ANError) throwable;
                        Timber.d("it is ERROR in displaylocation in Registervisitorpresenter:%s", anError.getErrorDetail());

                        handleApiError(anError);
                    }
                }));
    }

As you can see from above, I try to retrieve the visitors list and meeting list together here:                                 Objects.requireNonNull(getMvpView()).updateUpcomingGuestList(response.meetings.get(i).getVisitors(),response.getMeetings());
, but not sure if its the right way to do it as both visitors list and meetings list have different positions/size based on the data and this is probably causing the crash.Is there a way to go around this and update my code so I can assign the correct dates to the right visitors so I can achieve the output I listed above? Any help appreciated.
Thanks! Happy to share more info if needed.

A: Instead of trying to use response as it came from your API(which is causing problems), you could declare a model class that will be more friendly and perform some operations on your API response to create a list of your new model class.
Declare a new model UpcomingGuest that takes a Visitor object and a Meeting in its constructor.
public class UpcomingGuest {

    private String visitId;

    private String firstName;

    private String lastName;

    private String email;

    private Object phone;

    private String status;

    private String meetingId;

    private String meetingDateStart;

    private String meetingDateEnd;

    public UpcomingGuest(UpcomingGuestsList.Visitor visitor, UpcomingGuestsList.Meeting meeting){

        this.visitId = visitor.getVisitId();
        this.firstName = visitor.getFirstName();
        this.lastName = visitor.getLastName();
        this.email = visitor.getEmail();
        this.phone = visitor.getPhone();
        this.status = visitor.getStatus();
        this.meetingId = meeting.getId();
        this.meetingDateStart = meeting.getDateStart();
        this.meetingDateEnd = meeting.getDateEnd();

    }

    public String getVisitId() {
        return visitId;
    }

    public void setVisitId(String visitId) {
        this.visitId = visitId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Object getPhone() {
        return phone;
    }

    public void setPhone(Object phone) {
        this.phone = phone;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMeetingId() {
        return meetingId;
    }

    public void setMeetingId(String meetingId) {
        this.meetingId = meetingId;
    }

    public String getMeetingDateStart() {
        return meetingDateStart;
    }

    public void setMeetingDateStart(String meetingDateStart) {
        this.meetingDateStart = meetingDateStart;
    }

    public String getMeetingDateEnd() {
        return meetingDateEnd;
    }

    public void setMeetingDateEnd(String meetingDateEnd) {
        this.meetingDateEnd = meetingDateEnd;
    }

}

Then construct a list of UpcomingGuest from your response which will be used in your RecyclerView's adapter.
.subscribe(response -> {
                    int sizercount = 0;
                    for (UpcomingGuestsList.Meeting meeting: response.meetings) {
                        for(UpcomingGuestsList.Visitor visitor: meeting.visitors){
                            upcomingGuests.add(new UpcomingGuest(visitor,meeting));
                        }
                    }

                    // send upcomingGuests results to view

                }

Then in your RecyclerView's adapter use a List of UpcomingGuest instead of the two Lists you are using.
private List<UpcomingGuest> mUpcomingGuestList;

EDIT
For your sorting issue, you could sort your response before iterating through them like below:
.subscribe(response -> {
        ArrayList<UpcomingGuest> upcomingGuests = new ArrayList<>();

        //sort meetings by date
        List<UpcomingGuestsList.Meeting> meetings = response.meetings;
        Collections.sort(meetings, new Comparator<UpcomingGuestsList.Meeting>() {
            @Override
            public int compare(UpcomingGuestsList.Meeting meeting, UpcomingGuestsList.Meeting t1) {
                return meeting.getDateStart().compareTo(t1.getDateStart());
            }
        });

        for (UpcomingGuestsList.Meeting meeting: meetings) {
            //sort visitors by last name
            List<UpcomingGuestsList.Visitor> visitors = meeting.visitors;
            Collections.sort(visitors, new Comparator<UpcomingGuestsList.Visitor>() {
                @Override
                public int compare(UpcomingGuestsList.Visitor visitor, UpcomingGuestsList.Visitor t1) {
                    return visitor.getLastName().compareTo(t1.getLastName());
                }
            });

            for(UpcomingGuestsList.Visitor visitor: visitors){

                upcomingGuests.add(new UpcomingGuest(visitor,meeting));
            }
        }

        // send upcomingGuests results to view

}


text:
Q: What can be used with MySQL instead of EntityFunctions.DiffMilliseconds I have to OrderBy and Filter by TotalTime - computed value between Finish and Start. Previously, with MS SQL I was using
records = records.OrderByDescending(o =>  (o.LastRunStart != null) ? EntityFunctions.DiffMilliseconds(o.LastRunFinish ?? DateTime.UtcNow, (DateTime)o.LastRunStart) : 0);

But with MySql it is not working. Is there any useful method in EF for MySql that can by used in select?


text:
Q: Fine Uploader Response Error OnComplete In IE 10 Manual Uploader Working Fine with All Browser expect IE 10, i am not getting correct Response From the Server it is Showing on onComplete "No Valid message Received from Loaded iframe For i frame Name 1_97604 cec......".
File are uploading into the cloudbees server but not getting correct Response From the server.
In case of Other browser i am getting Response.success = true, but For IE 10 its undefined, how to handle this error. Please help me Out for this.
Regards
Yogesh

A: You aren't using IE10 if that is the message you are seeing.  Most likely, you are using IE9 or older.  The message you are seeing is logged by the form uploader, which is never used if you are uploading via IE10.  Perhaps you are running IE10 in IE9 or IE8 mode.  Either way, the message indicates that you are working in a cross-origin environment (you have set the cors.expected option to true) but are not returning the proper response from your server.  Note that older browsers, such as IE9 and older, utilize form submits, targeting an iframe, to upload files.  In order to access the contents of that cross-origin iframe, the iframe needs to post a message containing the server response to Fine Uploader's window.  This is all very easy to do, all you need to do is return a text/html response from your server that looks something like this:
"{\"success\": true, \"uuid\": \"9da17ad5-ad6a-40cd-81b5-226e837db45b\"}<script src=\"http://<YOUR_SERVER_DOMAIN>/iframe.xss.response-<VERSION>.js</script>.js\"></script>"

The javascript file mentioned in the script tag is provided in the Fine Uploader released zip file.  It does all of the work for you.  You must return a JSON response before the script tag, as illustrated above, and the response must include the UUID of the associated file.
You should read about cross-origin support either in the associated blog post.


text:
Q: Does T[] implement IList? I have a class constructor that takes a IList<IElement> as an argument.
When creating a new instance of the class I'm able to pass a IElement[] instead of the IList<IElement> how is that posible?

A: An array with element type T derives from IList<T>.
This is not visible in the meta-data in mscorlib.dll, but the inheritance relationship is created at runtime in the CLR. C# and the CLR are aware of the array type and treat it specially.


text:
Q: How to use router links in a list in React For a project of mine I have created a navbar which has a profile icon. When the profile icon expands it previews four different options which are "Log in" "Register "Edit" "Admin". The issue that I have is that when I click on the links that expand, it's not always that I get redirected to the correct place. Sometimes it routes me to the clicked path, and sometimes it just stays on the current one i.e. nothing happens.
The list of links looks like this at the moment. Every router-link redirects to another .js component. I then map through them in the code furthest down. Any suggestions to how I can edit this in order to be redirected to the clicked link every time?
const guestSettings = [
  <Link key={'Logga in'} to="/SignIn" style={{ textDecoration: 'none', color: 'black' }} >Logga In</Link>,
  <Link key={'Registrera'} to="/SignUp" style={{ textDecoration: 'none', color: 'black' }} >Registrera Konto</Link>,
  <Link key={'Redigera'} to="/UserProfile" style={{ textDecoration: 'none', color: 'black' }} >Redigera Profil</Link>,
  <Link key={'Admin'} to="/AdminHome" style={{ textDecoration: 'none', color: 'black' }} >Admin</Link>,
];

              <Menu
                sx={{ mt: '45px' }}
                id="menu-appbar"
                anchorEl={anchorElUser}
                anchorOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                keepMounted
                transformOrigin={{
                  vertical: 'top',
                  horizontal: 'right',
                }}
                open={Boolean(anchorElUser)}
                onClose={handleCloseUserMenu}
              >
                {guestSettings.map((setting) => (
                  <MenuItem key={setting.key} onClick={handleCloseUserMenu}>
                    <Typography textAlign="center">{setting}</Typography>
                  </MenuItem>
                ))}
              </Menu>

DropDown from the Icon
I haven't really been able to locate how to solve this with other things that i have tried.

A: My best guess is that in your handleCloseUserMenu function, which at least gets called every time a user clicks on the item itself, you prevent the default behaviour which would be a redirect, so this would not work:

 e.preventDefault()}>
    Prevent Default


text:
Q: Can we access connection string from session variable in SqlDataSource Control? I have four database on same server, I am using SqlDataSource Control to bind grid view in my application.And I have implemented a drop-down base on its item selection connection string is saved in a session variable. but I don't know how to pass this session variable in connctionstring property of SqlDataSource Control
<asp:SqlDataSource ID="dsMyAlarm" runat="server" ConnectionString="<%$ ConnectionStrings:AlarmDirectorDTUConnectionString %>"  SelectCommand="AD_FetchAlarmSubscriptionsByUserID" SelectCommandType="StoredProcedure">
     <SelectParameters>
                <asp:SessionParameter DefaultValue="0" Name="ContactId" SessionField="CurrentUser" Type="Int32" />
      </SelectParameters>
 </asp:SqlDataSource>

In This property I want to pass a session variable
ConnectionString="<%$ ConnectionStrings:AlarmDirectorDTUConnectionString %>"

Is it possible? or can i achive this by other way please suggest me I am open for suggestion

A: You could bind the session variable in code behind page_load.
dsMyAlarm.connectionString=Session["constr"];

or refer to the document data binding expression.https://support.microsoft.com/en-in/kb/976112


text:
Q: make[1]: cc: Command not found make[1]: *** [Makefile:366: stress-access.o] Error 127 I cross-compiled a stress-ng file on a VM. It worked perfectly i could run stress-ng on the VM but I needed to run it on my imx8m so I tared the file and uploaded it on the platform. I did a make (after untaring) to get the executable file but surprise ..
make[1]: cc: Command not found
make[1]: *** [Makefile:366: stress-access.o] Error 127
I'm using Yocto so i can't sudo or get-apt ect...
I'm begining on Linux and I don't know what to do.


text:
Q: Edit/Cancel Button in Javascript I have a form where the user can edit their text. I want the user to be able to retrieve their text if they delete it by hitting the cancel button.
How would I be able to retrieve a users text if they edit the original text, and when they press cancel the original text in the form before the edit comes back?

A: You could use data-* attributes to do this by adding data-original-text to the input like :
<input name='first_input' data-original-text='First input text' value="First input text"/>

And add a click event to the cancel button that will get the data attribute and assign it to the value :
$('form').on('click','#cancel',function(){
  $(this).closest('form').find('input').each(function(){
    $(this).val($(this).data('original-text'));
  })
})

Hope this helps.

$('form').on('click','#cancel',function(){
  $(this).closest('form').find('input').each(function(){
    $(this).val($(this).data('original-text'));
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input name='first_input' data-original-text='First input original text' value="First input original text"/>
  <input name='second_input' data-original-text='Second input original text' value="Second input original text"/>

  <button id='cancel'>Cancel</button>
</form>

A: Something like the following could be built upon so that they could make multiple changes and still have the previous text available on change.
// JavaScript source code
var orginalText = "Please Enter Some Text here";
var newTest = "";

$(document).ready(function () {
    $("#target").change(function () {
        newText = this.text;
    });

    $(".cancel").on("click", function () {
        $("#target").text(orginalText);
    });
});


text:
Q: TRIAC BT136 as DIAC BD3 conversion both have MT1 and MT2 A DIAC looks like a diode.
A TRIAC looks like transistor.
I have project that uses a DB3 and a BT136, but the BD3 is not available in the local market.
Can I cut the gate terminal off of a BT136 to make a BD3, just like we can make a "transistor as diode?" I have noted both (TRIAC/DIAC) have MT1 and MT2, where as TRAIC BT136 has an extra G terminal.
If the answer is no, how can I make alternative to a DIAC when it is not available?

A: Diac and Triac work in different operating principles.

DIAC (diode for alternating current) is a diode that conducts
electrical current only after its breakover voltage. TRIAC
(triode for alternating current) is a component that conducts current
in either direction when triggered.

Thus, it is not straight forward to replace a DIAC with a TRIAC, however possible it can be.
"diode that conducts electrical current only after its breakover voltage" is the keyword.
You may simply replace a Diac with two Zener diodes back to back in series. However, unlike a Diac, the voltage accross back-to-bak-Zener does not fallback after brakeover voltage reached.


text:
Q: Why does this service return null when return value is not null? Not sure why this is happening.
In the SaveRole() method when I try to hover over and see the value when debugging this line always shows null on the apiResponse variable.
var apiResponse = await RoleUiService.CreateAsync(createRoleRequest);

Even though it actually sets the value on _messages, after this value is set. The debugger still shows apiResponse as null.
if (apiResponse.StatusCode != HttpStatusCode.BadRequest)
{
  NavigationManager.NavigateTo("/RoleManagement/Roles",false);
}
else
{
  _messages = apiResponse.ResponseMessages;
}

public class HttpService
{
  public async Task<ApiResponse<T>> HttpPostAsync<T>(string uri, object dataToSend) where T : class
  {
     var content = ToJson(dataToSend);
     var apiURL = $"{_apiBaseUrl}{uri}";

     var result = await _httpClient.PostAsync(apiURL, content);

     return await FromHttpResponseMessageAsync<T>(result);
  }
}

public class RoleUiService
{
  private readonly IHttpService _httpService;

  public RoleUiService(IHttpService httpService)
  {
     _httpService = httpService;
  }

  private async Task SaveRole()
  {
    //Debugger always shows apiResponse as null even when _messages
    gets a value from apiResponse.ResponseMessages
   var apiResponse = await

   RoleUiService.CreateAsync(createRoleRequest);

   if (apiResponse.StatusCode != HttpStatusCode.BadRequest)
   {
      NavigationManager.NavigateTo("/RoleManagement/Roles",false);
   }
   else
   {
       _messages = apiResponse.ResponseMessages;
   }
}

//Blazor wasm component code
public partial class CreateOrEditRole
{
  [Inject]
  public IRoleUiService RoleUiService { get; set; }

  public async Task<ApiResponse<CreateRoleResponse>>
      CreateAsync(CreateRoleRequest createRoleRequest)
  {
    var result = await _httpService.HttpPostAsync<CreateRoleResponse>
    (CreateRoleRequest.Route,
    createRoleRequest);
    return result;
  }
}

//Services registered in PROGRAM.cs

builder.Services.AddScoped<IHttpService, HttpService>();
builder.Services.AddScoped<IRoleUiService, RoleUiService>();

Thank you for the responses, see screen shots. Even though a value was pulled from the apiResponse and assigned to a variable the object is still reported as null.
apiResponse object is null
apiResponse show null even though a value a was set to the var

A: This is one possible cause.
Debugging in Visual Studio

See the picture, exactly at that point, the name has not being changed, the change will happen as soon as you advance one step and the line where the name variable is assigned is no longer highlighted.
In this article, just bellow this picture it says:

Hover over the name variable to see its current value, which is an empty string.


text:
Q: Real world examples of AIDL I have been reading about AIDL and my understanding is that it is an implementation of IPC that allows 2 separate processes in the android environment to communicate with each other. I have read this from the Android Docs.
But my question is what is an real world example of AIDL being used and how is AIDL implemented in these examples?
NOTE: I have also come across this similar stackoverflow question but the example here can be implemented with ContentProviders so please make this differentiation also explicitly clear in your answer


text:
Q: Can't deserialize an HttpResponse message from a REST service using their XSD to generate C# classes I have a project where we are consuming a REST api from another company. They have provided an XSD that defines the various objects/elements, along with their attributes, etc.
One is something called QueryResponse which will contain various pieces of data based on what Query REST function I called from the 3rd party.
However, within the returned XML, they wrap it as follows and this is what is returned:
<Envelope xmlns="http://schemas.some.org/soap/envelope/">
     <Body>
          <QueryResponse xmlns="https://erpm.some.org/rpm/xml">
               <PeakLoadSummarySet>
                    <PeakLoadSummary Day="2018-03-10">
                         ... other data associated with a PeakLoadSummary type
                    </PeakLoadSummary>
                    .... PeakLoadSummary can repeat
               ... various other elements they define that can repeat.
               </PeakLoadSummarySet>
          </QueryResponse>
     </Body>
</Envelope>

I then extract the XML from the HttpResponse object to deserialize it into a QueryResponse C# POCO that was generated via the XSD command-line utility with Visual Studio using an XSD file provided by the company. However, their XSD does not define Body nor Envelope elements. QueryResponse (and there's another one called QueryRequest) are their top level elements and all other items are defined to be wrapped within either a QueryRequest or QueryResponse document.
I attempted to deserialize it as follows in C# in VisualStudio 2019:
// HttpResponse has already returned so I extract the content which would be the XML listed above.
string responseString = await msg.Content.ReadAsStringAsync();
MemoryStream stm = new MemoryStream();
StreamWriter stw = new StreamWriter(stm);

stw.Write(responseString);
stw.Flush();
stm.Position = 0;

XmlSerialize ser = new XmlSerializer(typeof(QueryResponse));
QueryResponse response = ser.Deserialize(stm) as QueryReponse;

At the call to Deserialize, it throws this error:
System.InvalidOperationException : there is an error in XML document (1,4).
---- System.InvalidOperationException : <Envelope xmlns='http://schemas.some.org/soap/envelope/'> was not expected.

Just to reiterate, their XSD does not define the Envelope or Body tags. I'm new to all of this so I'm not sure how to handle this? I know I can generate the code by pasting the XML into Visual Studio using Paste Special but is that the right way to do it? What is the proper way to handle a situation like this when they do not fully specify their XML message format but only a subset of it?
UPDATE: Per a request, here are the classes as they were generated from the XSD:
    namespace Schema {
        /// <remarks/>
        [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
        [System.SerializableAttribute()]
        [System.Diagnostics.DebuggerStepThroughAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="https://erpm.some.org/rpm/xml")]
        [System.Xml.Serialization.XmlRootAttribute(Namespace="https://erpm.some.org/rpm/xml", IsNullable=false)]
        public partial class QueryResponse {
             private object itemField;

             /// <remarks/>
             [System.Xml.Serialization.XmlElementAttribute("PeakLoadSummarySet", typeof(PeakLoadSummarySetType))]

             public object Item {
                 get {
                     return this.itemField;
                 }
                 set {
                     this.itemField = value;
                 }
             }
         }

        /// <remarks/>
        [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
        [System.SerializableAttribute()]
        [System.Diagnostics.DebuggerStepThroughAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://erpm.some.org/rpm/xml")]
        public partial class PeakLoadSummarySetType {

            private PeakLoadSummaryType[] peakLoadSummaryField;

            /// <remarks/>
            [System.Xml.Serialization.XmlElementAttribute("PeakLoadSummary")]
            public PeakLoadSummaryType[] PeakLoadSummary {
                get {
                    return this.peakLoadSummaryField;
                }
                set {
                    this.peakLoadSummaryField = value;
                }
            }
        }

        /// <remarks/>
        [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
        [System.SerializableAttribute()]
        [System.Diagnostics.DebuggerStepThroughAttribute()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://erpm.some.org/rpm/xml")]

        public partial class PeakLoadSummaryType {

            private string lSEField;

            private string zoneNameField;

            private string areaNameField;

            /// <remarks/>
            public string LSE {
                get {
                    return this.lSEField;
                }
                set {
                    this.lSEField = value;
                }
            }

            /// <remarks/>
            public string ZoneName {
                get {
                    return this.zoneNameField;
                }
                set {
                    this.zoneNameField = value;
                }
            }

            /// <remarks/>
            public string AreaName {
                get {
                    return this.areaNameField;
                }
                set {
                    this.areaNameField = value;
                }
            }
        }
    }


text:
Q: Odoo, write a list in a one2many field I just need to insert into a table the results of a search into a one2many field.
It works, but only write the last record that match the search parameter and I want to write, all of them, not only the last one created.
This is my code.
@api.model
def create(self, vals):
    domain =[('first_name','=','Luis')]
    student = self.env['university.student'].search(domain)
    for record in student:
        vals.update({'participants_ids':[(0,0,{
        'first_name_participant':record.first_name,
        'last_name_participant':record.last_name,
        })]})
    return super(university_course,self).create(vals)

A: You could get it done like this:
@api.model
def create(self, vals):
    vals.update({
        'participants_ids':[
            (0, 0, {
                'first_name_participant': record.first_name,
                'last_name_participant': record.last_name,
            }) for record in self.env['university.student'].search([
                ('first_name','=','Luis')
            ])
        ]
    })
    return super(university_course,self).create(vals)


text:
Q: Subdomain and Database per customer? I'm currently working on a farming IoT system and confused about the architecture so I wanted to get your views.
I'm using a relational DB (PosgreSQL).
I have multiple customers, each customer has one or more farmhouse and each farmhouse has one or more field.
I have IoT devices on each field, from a few to 200 hundred which communicates with backend each second.
I have multiple options how to architect this system.

*

*Subdomain and server per customer which will have their own database (logical db's on single instance), schema per farmhouse and a table for keeping fields. So when I want to get devices on certain field, I only need to do a inner join with fields and devices and filter.

*No subdomains, schema per customer and table for farmhouses and fields. Then I need to create association between farmhouse and field, and use this composite key to select the field and then make inner join on field_id.

*Single schema, I need to have a table for customers, farmhouses and fields. I need to associate customers with farmhouses, farmhouses with fields and select devices on fields with composite key of customer, farmhouse and field.
I'm quite junior on architectural design so I can't tell which one of these makes more sense.

A: People typically decide, based on the following:
Choose option 1 (separate databases and servers) for isolation and security. For instance, if your customers ever want full-control of their own data but never want to share with other customers, or if you get a new customer who insists that the data must be on Oracle, or DB2 or something, or they occasionally want to operate in a disconnected (no internet) manner.
Choose option 2 (separated by schema) if different customers may want different features which require differences in schemas, or if you need tiered security (farmer A has simple security needs, but farmer B works for USDA and needs higher security).
Choose option 3 (one server, one schema) if cost, maintenance, simplicity are of any consequence to you. Multiple servers often add cost and extra maintenance effort eventually. It requires more planning and design, but those are good things.
Most developers/SWAs would default to option 3 because it is the easiest design for cost, maintenance and managing. It becomes more relevant as your number of customers increases. (imagine maintaining thousands of independent servers).


text:
Q: Inserting PNG file as is I'm inserting a PNG file and it's rendered enlarged, somehow.
Here is my MWE:
\documentclass{book}
\usepackage{graphicx}
\begin{document}
\mainmatter
hello, world.
the following screenshot should be rendered in 1:1 scale, isn't it?

\begin{figure}[H]
\centering
\includegraphics{screenshot.png}
\end{figure}

\end{document}

Here is a screenshot I desire to insert: http://conus.info/tmp/screenshot.png
I use XeLaTeX.
And here is a result: http://conus.info/tmp/result.pdf
All I want is to insert a PNG picture (screenshot), so it will be rendered in the same width/height in PDF viewed at 100%.
The size of screenshot.png is 726 pixels by 489 pixels.
I want it to be exacly the same size when viewed in Acrobat Reader at 100%.
What should I do?
What are the best practices of inserting screenshots into TeX and exporting them to PDF?

A: This question cannot have general answer for ALL monitors.
The size of the PNG image on the screen depends on the screen resolution (e.g. 110.27 PPI (pixels per inch) for my MacBook), and on Retina (220 PPI) it will be twice smaller.
And the size of image inside PDF, shown at real 100%, will be monitor-independent.
Thus solution for my monitor:
\includegraphics[scale=0.65]{screenshot.png}

will be different from yours:
\includegraphics[scale=0.75]{screenshot.png}

A: \documentclass{book}

\usepackage{graphicx}

\begin{document}
    \mainmatter

    \begin{figure}[H]
        \centering
        \includegraphics[height = 0.3, width = 0.6]{crocodile.png}
    \end{figure}

\end{document}


text:
Q: Merging rows when some columns are the same using Pandas Python Now I have a dataframe, I want to merge rows. The value B is determined by the order in the strings in a list L = ['xx','yy','zz']
    A   B
0   a   xx
1   a   yy
2   b   zz
3   b   yy

*

*For row 0 and 1, the result will be 'a' for column A and 'xx' for column B ('xx' come before 'yy' in L)

*For row 2 and 3, the result will be 'b' for column A and 'yy' for column B ('yy' come before 'zz' in L)

Desired outcome:
    A   B
0   a   xx
1   b   yy

A: You can use pandas.Series.map and pandas.DataFrame.groupby:
df['C'] = df['B'].map(dict(zip(L,range(len(L)))))
df.groupby('A')[['B','C']].apply(lambda x: x.iloc[x["C"].argmin()]['B'])
#A
#a    xx
#b    yy

You can get the same result using pandas.Categorical:
df['B'] = pd.Categorical(df['B'], categories = L, ordered = True)
df.groupby('A').min()
#      B
#A
#a    xx
#b    yy


text:
Q: Confusion with StringBuilder in java Why is StringBuilder gives me an updated string when i use append but not when i use subString. Following is an example :-
class Hello{

 public void doSomething(){

StringBuilder sb = new StringBuilder("animals");
sb.append("s");
System.out.println("Original        = "+sb); // prints animals
sb.substring(sb.indexOf("a"), sb.indexOf("al"));
System.out.println(sb);// prints animals

}
}

A: substring doesn't change the state of the StringBuilder. It returns a String containing the requested substring. See the Javadoc for more details.
I think what you were looking for is StringBuilder#delete


text:
Q: What is the best way to move an element that's on the top to the bottom in Responsive design I have the following HTML format, what is the efficient way to position the given element on the top on a desktop and bottom on mobile devices (width < 640pixels)? Since there are lots of different devices, I don't want to write the position coordinates since the contents of the page's height varies. Any suggestions?

..

..

I am on the top of desktop page, and bottom of mobile page

...

A: Better compatibility than flexbox can be achieved with display: table-footer-group (IE8+)
Reverse effect: to move an element higher than it is in the HTML code, you can try table-caption and table-header-group.
Doesn't work with self-replaced elements like img or input, at least on Chrome (and that's quite normal) but fine with div for example.
EDIT: it's 2016 so Flexbox (and Autoprefixer) all the things \o/

A: Reordering elements of unknown heights in a responsive fashion is best done with Flexbox.  While support isn't great for desktop browsers (IE being the primary limiting factor here, support starts with v10), most mobile browsers do support it.
http://cssdeck.com/labs/81csjw7x
@media (max-width: 30em) {
  .container {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -moz-box-orient: vertical;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    /* optional */
    -webkit-box-align: start;
    -moz-box-align: start;
    -ms-flex-align: start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
  }

  .container .first {
    -webkit-box-ordinal-group: 2;
    -moz-box-ordinal-group: 2;
    -ms-flex-order: 1;
    -webkit-order: 1;
    order: 1;
  }
}

http://caniuse.com/#feat=flexbox
Be aware that Flexbox can clash with other layout methods, such as the typical grid techniques.  Flex items that are set to float can cause unexpected results in Webkit browsers using the 2009 specification (display: -webkit-box).

A: I don't know if it's the best approach, but you could replicate the same element where you want it and play with the display: none/display: inline-block attribute. When it's viewed on desktop, your css tells it to display the one on top and not the one at the bottom. Then, when viewed on mobile, it should not display the one on top and display the one at the bottom.
Like I said, I'm not sure this is the most efficient way of doing it, but it does work. If anyone else has a better solution, I'd love to hear it.

A: I assume when you say "postion" you mean so that it doesn't move when you scroll. In that case you could use:
p.className {
  position: fixed;
  bottom: 0; // for mobile devices
  top: 0; // for desktops
}

Where p element gets a class attribute like this:

I am on the...

bottom & top would not exist at the same time you would need to load the relevant one based on the device. For the desktop you would also need to offset your content with the height of the div so that it isn't hidden under the fixed div