text:
Q: Audio signal on oscilloscope I am exploring the mainboard of an Epson 3010 projector. This particular projector has internal speakers but does not have an audio out and - as I have built my own external audio amplifier - I wanted to modify it and extract audio from the projector.
At this moment, I am NOT considering an HDMI audio splitter. I am aware of that solution but I do not wish to go that way.
I opened up the projector and backtracked the integrated speakers wires to a chip that is a MAX9736A, a class D audio amplifier, conveniently located on top of the mainboard. Note: I wasn't able to find a schematic of this board, so I have to try to guess how it works.
https://datasheets.maximintegrated.com/en/ds/MAX9736-MAX9736B.pdf

From the datasheet it looks like this chip takes a line level input and outputs an amplified audio signal. I connected my oscilloscope (ground to chassis) and (for example) I can see the "PWM" speaker output. With the probe on pins 23..26 I see this wave that changes according to the input, and I can hear it while being played.
In the following image, my setup, with the area where the chip lives highlighted in a circle.

However, I expected to see a signal when putting the scope probe on pin 18 - instead I get a (noisy?) fixed 2VDC. Kind of surprisingly, I get some sort of noisy waveform that matches the input on pin 19, that is the feedback channel, connected to the input through at least a resistor and a capacitor (in the picture, see pins 5 and 6 for the left channel). Note I did not use the analog ground (pins 13,14), as my scope is not floating and I want to exercise caution. Now, this is just an audio signal, I'd expect levels and bandwidth to be fairly simple to see on a scope, I'm not exactly debugging DDR memory chips. I even tried to mess with AC coupling and bandwidth limiter, I gave a 440Hz audio input to the projector - I can hear it well in output - but I cannot detect it on pin 18.
My questions are:

*

*Why cannot I "see" a good audio wave input on the oscilloscope? I suspect I'm missing something obvious here

*If I manage to solder a line audio cable to pins 6 and 18 and ground to 13,14, what trouble can I expect? Please note I have an OK lab equipment with stereo microscope and I'd be technically able to perform the rework, in fact this chip is not even that small. But I typically work mostly on fully digital boards and this audio stuff escapes me.

EDIT:
I have soldered an audio cable to the entry point of the input network of the left channel of the MAX9736A. I cannot hear anything on that input, not even a faint signal. Difficult to make a good picture, but I soldered it with the aid of a stereo microscope and I have made sure they are good. I checked with a DMM that all grounds, AGND, PGND, main ground plane are all shorted with the chassis and the ground prong in the AC connector. (and yes, I even floated my fully-plastic cased oscilloscope to see if it made a difference)

Note: before and after this modification, the projector's integrated audio works perfectly with no issues.
EDIT2:
I have probed the circuit again with the oscilloscope; the probe point is the entry point of the input network as explained by the answer below:

The result is this, an extremely noisy waveform that in fact, might be a 440Hz audio input:

EDIT3:
The extremely noisy signal persists even if I solder a short lead to the AGND of the chip, I float the scope (yes, I know bad practice) and ground my probe there:

A: The audio input is connected via external feedback components to inverting op-amp inside the Maxim chip. Pin 18 is the inverting input and will have only DC bias due to feedback - that is what op-amps do. External circuitry to set gain and block DC bias is C716, R714 and R715 for right channel. You can find right audio at capacitor C716. Op amp output is pin 19, which is why you see audio there. Noisy, because you don't have oscilloscope ground connected.
Audio inputs are at vias near C716 and C709, but is of course unknown where they come from and if they have DC bias or not.

A: As others have suggested and you have also figured out, you can get the audio signal on C709 and C716, as well as on IC pins 5 and 19 (internal, inverted, op-amp outputs).
 One thing that I see missing and could solve the issue is to add a capacitor between the audio signal you want to pick up and your audio probe, so that you eliminate DC levels and offsets.
 You could try probing the signal from between those capacitors and the resistors right after them (the side of the C709 and C716 towards the amplifier inputs). I am curious to see what you get.
As for the noisy signal observed on your scope, your noise is very likely coming from the chip itself whose PWM switching frequency is around 300kHz and the scope probe having a very high impedance input is picking the noise up (If you look very carefully at the noise, you might see that there are around 300 peaks per ms, or 3 peaks per µs. Try reducing the time-base on the scope and you will see!).
Your grounding wire and clip are long enough to pick up this high frequency noise. There is a capacitor on the feedback pin which is clearly there to reduce high frequencies (low pass filter or an integrator).
Any time you have a noisy circuit, a small signal and a high impedance, the noise is bound to get picked up. Differential signalling is used in such cases.
You could use the hot ends of the 2 scope probes and use the DIFFERENCE between them to observe a noise-free signal.

A: Nothing is wrong here, everything looks to be working exactly as expected! The simple answer is that you're attempting to extract the audio signal from the 'virtual ground' node of an inverting amplifier (which won't work) rather than extracting the audio at the input of the inverting amplifier (which will work).
Pin 18 is NOT the audio input, but rather the inverting (negative) input into an operational amplifier serving as an internal pre-amp inside the MAX9736.
I understand your confusion given the naming of these pins in the datasheet.  The subtle but important difference here is that an audio input is NOT the same as the inverting input to an amplifier, which they've named 'inverting audio input'.
Some audio ICs do have pins that are direct audio inputs, but in such cases, those inputs do not connect directly to the inverting(-) input of the preamp, but rather to a feedback network that uses resistors and possibly capacitors that are internal to the chip.  This has the advantage of being simpler to design for and easier to use, but at the cost of flexibility.  It is this feedback network that sets the gain of the preamp stage, so in cases where the feedback network is inside the IC, your gain is fixed to whatever that chip has set it as.
The MAX9736 (and plenty of other audio ICs, don't get the impression that either of these solutions are unusual or the norm.  Either is perfectly fine and it is really at the whims of the IC designer and the target market for a given chip) on the other hand exposes the inverting input and immediate output of the preamps directly onto external pins, allowing you to choose the gain yourself.  This also means that you must provide the resistors (and capacitors if needed) externally yourself.
Here, look at the block diagram for the chip.

See the two triangle symbols?  Those are op amps, which are the basic building block of any amplifier.  But those resistors external to the IC are what determine the gain and the type of amplifier an op amp will function as.  In other words, the preamp isn't just the op amps internal to the IC.  The external resistors are a core part of the preamp.  What I am getting at here is that the pin you are probing, pin 18 (or pin 6 for the left channel) are not audio inputs, but rather should be viewed as a connection internal to the preamplifier circuit.
Measuring or attempting to extract audio from there is not going to work because this is not the input of the preamps and not where the audio signal gets inputted, but rather an internal node of the preamps themselves.
The actual audio input is, sadly, unlabeled in the block diagram, but it is the left lead of the 470nF capacitors on each channel.   That is where you will find your audio signal, and where you must extract it.
But why?
Well, those amplifiers are configured as inverting amplifiers.  There is one thing you need to know about inverting amplifiers above all else, and that is this:  inverting amplifiers will do everything that is within their power to maintain 0V across the input terminals.  The negative feedback from their output to the inverting input is taking any voltage that appears across their input and amplifying it as much as is needed to cancel out that voltage on their own input.
Returning to this specific IC, the non-inverting (+) inputs of the op amps are both connected to a bias voltage, which is, based on what you've measured, 2.5V.  That means that these amplifiers will do their absolute best to maintain 0V between the + and - (non-inverting and inverting) inputs.  So if the non-inverting input is at 2.5V, then 0V difference from that is 2.5V.
Which is exactly what you're measuring.  They're biased via the non-inverting inputs at 2.5V, so those amps will fight tooth and nail to make sure that the inverting input is always at 2.5V as well.  This is also often referred to as the 'virtual ground' node of an inverting op amp, because it acts as a fixed reference that serves as the 'ground' that the output signal is amplified in reference to.  Instead of true ground, if this node is biased to 2.5V, then an output voltage that might swing from 1V to -1V (at least referenced to true ground) will instead swing from 3.5V to 1.5V (2.5V plus or minus 1V - it is literally a pretend, virtual ground for the output).
Just to drive this home, here is an approximation of the input circuit I drew in LTSpice.  An 8kHz sine wave serves as our audio input at standard audio input voltage levels.  The audio signal is visible, loud and clear, at the true input, but if we measure the signal that the virtual ground node (pin 18/pin 6 on the MAX9736), look what we get:

And that 1mV of voltage ripple (note how it is centered at 2.5V, exactly like you're measuring) at that node is ultimately due to various parasitic elements of the op amp interacting with phase shift/delay as the op amp forces the voltage difference back to 0V.   It can't do this instantly, so a minute voltage difference does still appear, and could be as low as microvolts, depending on the op amp and the circuit.
So, if you want to get the audio, you'll need to get the audio from the actual audio inputs, and not at the one voltage node internal to the preamp where one can be most sure to NOT find any signal at all, the virtual ground node.
Connect your wires to the SMD capacitor terminal pointed to with the orange arrows. You cannot extract the audio directly from the IC pins, as these are not the true audio inputs.  The true inputs are what the orange arrows are pointing at.  Just make sure your amplifier has AC coupling capacitors on its inputs since these connections omit the projector's own.

Note:  The bottom most orange arrow should read (L), not (R).  I was a little too gun-ho with my copy and pasting.
I have intentionally not gone into how inverting amplifiers work, but rather only touched on the relevant aspects to your problem.  Such a discussion is non-trivial, well outside the scope of this question, and frankly already has answers on this site far better than I myself could do, as well as being a chapter in just about any analog electronics text book.  If you're curious and want to know how this stuff actually works, I definitely recommend looking for some resources on both inverting amplifiers and negative feedback, as well as op amps in general.  Those topics can go quite deep with some pretty serious math (bode plots, transfer functions, and laplace transforms, oh my!) but don't feel like you need to go that deep.  Just a basic conceptual understanding of this stuff can be quite useful.


text:
Q: Adding constraints to a UILabel to put within a CAShapeLayer I have a problem where I am trying to center a UILabel within a programmatically generated circle (CAShapeLayer). The problem is that CAShapeLayer is not extended from UIView or NSLayoutGuide, so I am getting a runtime error with the following segment of code:
let circlePathLayer = CAShapeLayer()

let xConstraint = NSLayoutConstraint(item: statusLabel, attribute: .CenterX, relatedBy: .Equal, toItem: circlePathLayer, attribute: .CenterX, multiplier: 1, constant: 0) //Cannot set circlePathLayer

Is there an easy way to fix this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: OR operator in C not working I don't understand why the final printf in the code below is not printing 255.
char c;
c = c & 0;
printf("The value of c is %d", (int)c);
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);

A: It is probably printing -1. That is because
c = (c | j);

will evaluate as
c = (0 | 255) = (0 | 0xFF) = 0xFF

but, since c is signed, 0xFF will be -1 and not 255 as you expected. If you change c to unsigned char it will print 255, as you imagined.

A: Try to replace char c with unsigned char c. Basically char type supports values from -128 to 127. Your result is bigger than the supported range and overflows.

A: In most implementations the char type is signed, so it ranges from -128 to 127.
This means, 11111111 (which is 255 written in binary) is equal to -1. (As it's represented as a value stored in two's complement)
To get what you expect, you need to declare c as a unsigned char, like so:
unsigned char c = 0;
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);

A: By default    char
 is     signed char
 in C. If you want     255 to be printed then use      unsigned char
however i explain the output in context of     signed char
so that the concept becomes clear.
If you write     j=127 then it will print      127 as the bit representation is 01111111.
But if you write      j=128
 then it will print     -128
because the bit representation 01111111 has increased by 1 to become 10000000.
now if you write     j=255
then the bit representation is 11111111. so it will print      -1
If you write      j=256
then it will print      0
because when bit representation 11111111 is increased by 1 it becomes 100000000. But only 1 byte is allocated for a characher variable so the left most bit is not stored and bit representation becomes 00000000.
Further if you write      j=257
then its also a case of overflow and the bit representation become 00000001 and      1 will be printed.


text:
Q: Construction of a polynomial Let $ m \in \mathbb{N}$ be fixed and $q=p^n$ (a variable prime power) for $n \in \mathbb{N}$  and $p$ prime. We define
$$c_m=|\left\lbrace f \in \mathbb{F}_q[X]; f \ \text{irreducible, monic, deg}(f)=m \right\rbrace|. $$
I want to prove the following statements:
(A) $q$ relatively prime to $m$ $\Longrightarrow$ $q \mid c_m$
(B) $\exists$ a monic polynomial $C_m \in \mathbb{Z}[X]$ with $\text{deg}(C_m)=m$ so that $c_m=\frac{C_m(q)}{m}$ for all $q$.

A: Hints:
A: We can let the additive group of the field $\Bbb{F}_q$ act on the set of monic irreducible polynomials of degree $m$ as follows. Let $f(x)$, a monic irreducible of degree $m$, and $\alpha\in\Bbb{F}_q$ be arbitrary. Then prove that $f(x+\alpha)$ is also a monic irreducible, and that this defines a group action. The upshot is to prove that if an irreducible monic has a non-trivial stabilizer, then necessarily $\gcd(m,q)\ge p$. Here you can use the fact that all the element of the field have additive order $p$.
B: It looks like you already solved this one.


text:
Q: How can I prevent cluster markers group after click on specific marker? I want to prevent open markers which shows after click on bubbles. Current problem is that when we click on marker then a popup opens and marker of cluster bubbles hide. And I also want to change the lines color on hover which is connecting markers after on bubble click. Below is my sample code and some screenshots:
Thank you in advance.
<!DOCTYPE html>

    <link href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" rel="stylesheet" />

A: There is an option to customize the style of those lines stickLayerOptions. The hover style is defined as part of the feature-state so you can use a data driven style expression to customize the options. Here is how you would make that line purple when hovering.
spiderManager.setOptions({
    stickLayerOptions : {
        strokeColor: [
                'case',
                ['boolean', ['feature-state', 'hover'], false],
                'purple',
                'black'
            ]
    }
});

Looking through the code for the spider cluster library, it looks like when a click event occurs, the cluster closes automatically. I don't see an option to prevent that from happening. I'll take a look later today to see if there is a way to modify the library to support this scenario somehow.


text:
Q: Selecting rows in DataFrame by/after grouping using DataFramesMeta in Julia I am trying to select certain data rows in a DataFrame using @linq macros:
using DataFrames, DataFramesMeta
df=DataFrame(x = ["a", "a", "a", "b", "b", "b"],
             y = [1, 2, 3, 2, 3, 4],
             z = [100, 200, 300, 456, 345, 234])

| Row | x   | y | z   |
|-----|-----|---|-----|
| 1   | "a" | 1 | 100 |
| 2   | "a" | 2 | 200 |
| 3   | "a" | 3 | 300 |
| 4   | "b" | 2 | 456 |
| 5   | "b" | 3 | 345 |
| 6   | "b" | 4 | 234 |

I am trying to select those rows that have the maximum y for a given type of x, that is
| Row | x   | y | z   |
|-----|-----|---|-----|
| 1   | "a" | 3 | 300 |
| 2   | "b" | 4 | 234 |

So, I am grouping by column x and adding a column with the maxima
@linq df |> @by(:x, maxY = maximum(:y))

which gives
| Row | x   | maxY |
|-----|-----|------|
| 1   | "a" | 3    |
| 2   | "b" | 4    |

but I don't see how to put the corresponding z entries back in. Probably, it would be join but I don't see how to do that or get the result in another, simple way.

A: You can do it in one line joining on=[:x,:y] but for this to work you need to name the maximum(:y) column y not maxY:
df2 = @linq df |> by(:x, y=maximum(:y)) |> join(df, on=[:x, :y])

You can later rename that column to the intended maxY:
rename!(df2, :y, :maxY)


text:
Q: Divs not aligning properly on website (work fine in CodePen though) My site consists of green boxes (divs) that are aligned side-by-side in rows.
There are 3 divs per row, and their heights are suppose to be the same.
Everything works perfectly except for some reason there are 3 divs not aligning properly at the bottom of the page.
The problem only occurs on my website though, but works fine in a CodePen for some reason. Can you pinpoint the problem?
Here is my site (scroll down to see problem)
Here is the codepen  (no issue for some reason)
and here is a screenshot showing the issue on my server:

The div's HTML is:

Sample Title Title Title

Demo Demo

Demo Demo

A:     .mainbox {
  width:80%;
  margin:auto;
  overflow:hidden;
  text-align:center;
  height: 4000px;
}
.mainbox a {
display: inline-block;
vertical-align: top;
margin: 0 0.5em 0;
width: 25%;
background: #A1F997;
box-shadow: 0 50px 0 #A1F997 , 0 100px #A1F997 , 0 150px #A1F997;
border-top: 1em solid white;
padding: 0.5em;
margin-top: 151px;
height: 450px;}

try it now

A: Your website has one more box than your Codepen example, so the CSS selector:
.mainbox a:last-of-type:nth-child(4n){
   margin-right:calc(25% + 1.7em);
   box-shadow: 0 50px 0 #A1F997 , 0 100px #A1F997  , 0 150px #A1F997,  100px 0 white,  200px 0 white,  300px 0 white,  400px 0 white
}

is taking effect and giving the last box a large right margin, which forces it to the next line.


text:
Q: Structure to add a node id with correct type I am trying to specify a node id on my server but don't understand the structure that I am supposed to follow. I followed the seemingly simple structure to change the node ID and didn't receive errors or warnings. I was successful in creating the nodes as seen below but not creating a node_id. I thought to add a simple node id I would follow the same structure and add the lines with $$$$ in them;
// opcua_server.c

#include "ua_types.h"
#define HANDLE_PDU1 15

const uint8_t EN_DISPLAYNAME_PDU1[] = "PDU1";
const UA_UTF8_string_t ENGLISH_TEXT[] = {
    {0, 0}, {sizeof(EN_DISPLAYNAME_PDU1) - 1, EN_DISPLAYNAME_PDU1}};

void opcua_add_nodes(void) {
    UA_Status_t status = 0;

    // Add PDU1 Folder
    UA_Folder_t PDU1;
    UAServer_Init_config_structure_Folder(&PDU1);
    PDU1.node_handle = HANDLE_PDU1;
    PDU1.display_name_handle = HANDLE_PDU1;
    UA_NodeId_Config_t randomHANDLE; // $$$$ Not creating node id
    PDU1.node_id = randomHANDLE;     // $$$$ Not creating node id

    status = UAServer_Create_Folder(&PDU1);
    if (status != 0) {
        UA_SERVER_PRINTF("UAServer_Create_Folder returned: %d\n",
                         (uint16_t)status);
    }
    status = UAServer_Add_to_folder(folder.node_handle, PDU1.node_handle);
    if (status != 0) {
        UA_SERVER_PRINTF("UAServer_Add_to_objects_folder returned: %d\n",
                         (uint16_t)status);
    }
}

// ua_types.h
typedef struct {
    /**
     * A mandatory unique identifier that identifies the node in the library.
     * The value zero is invalid.
     */
    uint32_t node_handle;
    /**
     * A mandatory unique identifier that allows the host to efficiently look up
     * the
     * node name text to display in a translate callback. The value zero is
     * invalid.
     */
    uint32_t display_name_handle;
    /**
     * An optional unique identifier that allows the host to efficiently look up
     * the
     * node description text to display in a translate callback. The value zero
     * is
     * invalid.
     */
    uint32_t description_handle;
    /**
     * An optional visibility mask that restricts the visibility of the node
     * depending
     * on which user is logged in. The anonymous user is bit 0 and bits 1 - 15
     * represent the corresponding users
     */
    uint16_t user_visibility;
    /**
     * Specifies the namespace index for this node. The UA namespace is 0 and
     * cannot
     * be used. The default server namespace is 1. Other namespaces may be added
     * to the configuration data structure.
     */
    uint16_t namespace_index;
    /**
     * An optional parameter set that defines the NodeId for the node as a
     * string
     * or a GUID. If this parameter is set to default values then the SDK will
     * assign
     * an opaque node id to the node. Opaque node ids are easily decoded by the
     * SDK
     * and offer the best performance. Only populate this parameter set if your
     * application requires it.
     */
    UA_NodeId_Config_t node_id;
} UA_Base_t;

/*****************************************************************************/
/** \brief A configuration structure for Folder address space nodes.
 *
 */
typedef UA_Base_t UA_Folder_t;

/*****************************************************************************/
/** \brief A configuration structure for View address space nodes.
 *
*/
typedef UA_Folder_t UA_View_t;

/*****************************************************************************/
/** \brief A configuration structure for Method address space nodes.
 *
 */
typedef struct {
    /**
     * Configuration common to all nodes
     */
    UA_Base_t base_config;
    /**
     * The file size in bytes
     */
    uint64_t size;
    /**
     * The file is writable
     */
    bool_t writable;
    /**
     * An optional writable mask that restricts write access of the file
     * depending
     * on which user is logged in. The anonymous user is bit 0 and bits 1 - 15
     * represent the corresponding users
     */
    uint16_t user_writable;
} UA_File_t;

A: When you define PDU1, a node_id is already created and associated with it. You just need to access node_id and assign value for each of its elements.
Replace
UA_NodeId_Config_t randomHANDLE; // $$$$ Not creating node id
PDU1.node_id = randomHANDLE;     // $$$$ Not creating node id

with
PDU1.node_id.identifier_type = xxxx;  // xxxx, yyyy, zzz is whatever valid value for their type.
PDU1.node_id.string_identifier = yyyy;
PDU1.node_id.guid_identifier = zzzz;

A: Turns out I needed to specify the identifier type (which I did by looking at the identifier types) and set it equal to opcua_node_encoding_string. The result is a string node id that I set out to create.
    //Add PDU1 Folder
    UA_Folder_t PDU1;
    UAServer_Init_config_structure_Folder(&PDU1);

    PDU1.node_handle             = HANDLE_PDU1;
    PDU1.display_name_handle     = HANDLE_PDU1;
    PDU1.node_id.identifier_type = opcua_node_encoding_string;

    const char TEST_STRING_ID2[]          = "PDU1";
    PDU1.node_id.string_identifier.length = sizeof(TEST_STRING_ID2) - 1;
    PDU1.node_id.string_identifier.data   = (uint8_t*)TEST_STRING_ID2;

    status = UAServer_Create_Folder(&PDU1);
    if (status != 0)
    {
        UA_SERVER_PRINTF("UAServer_Create_Folder returned: %d\n",        (uint16_t)status);
    }
    status = UAServer_Add_to_folder(folder.node_handle, PDU1.node_handle);
    if (status != 0)
    {
        UA_SERVER_PRINTF("UAServer_Add_to_objects_folder returned: %d\n", (uint16_t)status);
    }


text:
Q: Partitioned view not working I am trying to get partitioned views to work, and still see query optimizer scanning both tables. Here is my script:
CREATE TABLE A(DataDate [date] NOT NULL CHECK(datepart(yy, DataDate) <= 2010))

CREATE TABLE B(DataDate [date] NOT NULL CHECK(datepart(yy, DataDate) > 2010))

CREATE VIEW V AS SELECT * FROM A UNION ALL SELECT * FROM B

select * from V where datepart(yy, DataDate) = 2009

But when I look at the execution plan I see that both table A and table B were scanned and the  "Number of Executions" for both tables is 1. I would expect table A to have Number of Executions = 1, and table B to have Number of Executions = 0. I am on SQL Server 2012.
Can somebody clarify how this is supposed to work? Thank you.

A: Is supposed to work like this:
CREATE TABLE A(DataDate [date] NOT NULL CHECK(DataDate < '20110101'));

CREATE TABLE B(DataDate [date] NOT NULL CHECK(DataDate >= '20110101'));
go

CREATE VIEW V AS SELECT * FROM A UNION ALL SELECT * FROM B
go

select * from V where DataDate >= '20090101' and DataDate < '20100101';
go

A: From the documentation in CREATE VIEW, on Partitioned Views, when discussing the constraints that must exist on the base tables:

Constraint C1 defined on table T1 must be of the following form:

C1 ::= < simple_interval > [ OR < simple_interval > OR ...]
< simple_interval > :: =
< col > { < | > | <= | >= | = < value >}
| < col > BETWEEN < value1 > AND < value2 >
| < col > IN ( value_list )
| < col > { > | >= } < value1 > AND
< col > { < | <= } < value2 >

Your constraints are not of this form, and thus it's not eligible to be a partitioned view. You need simple constraints, such as the ones that @Remus has shown, and not ones that call on functions.

And, of course, the other advice found anywhere you look up Partitioned Views in BOL:

The preferred method for partitioning data local to one server is through partitioned tables. For more information, see Partitioned Tables and Indexes.

Partitioned tables have been the preferred method of partitioning since their introduction in SQL Server 2005.


text:
Q: ¿Cómo clono un subdirectorio sólo de un repositorio Git? Quiero clonar sólo una aplicación de un repositorio que contiene toneladas.
Básicamente parece que sólo necesito clonar un subdirectorio sólo de un repositorio Git. Así probé el método de este hilo:
(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial>mkdir oil_dashboard

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial>cd oil_dashboard

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>git init
Initialized empty Git repository in C:/Users/antoi/Documents/Programming/DashTutorial/oil_dashboard/.git/

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>git config core.sparseCheckout true

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>cat >> .git/info/sparsecheckout
'cat' is not recognized as an internal or external command,
operable program or batch file.

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>echo >> .git/info/sparsecheckout

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>vim .git/info/sparsecheckout
'vim' is not recognized as an internal or external command,
operable program or batch file.

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>notepad .git/info/sparsecheckout

(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>git pull origin master
remote: Enumerating objects: 162, done.
remote: Counting objects: 100% (162/162), done.
remote: Compressing objects: 100% (27/27), done.
error: RPC failed; curl 56 OpenSffSL SSL_read: SSL_ERROR_SYSCALL, errno 10054
atal: early EOF
atal: the remote end hung up unexpectedly
fatal: index-pack failed

Sin embargo, tengo este error fatal. Entonces, ¿cómo puedo clonar este repositorio específico?
En .git/info/sparsecheckout tenemos:
apps/dash-oil-and-gas/

Aqui esta git remote -v:
(venv) (base) C:\Users\antoi\Documents\Programming\DashTutorial\oil_dashboard>git remote -v
origin  https://github.com/plotly/dash-sample-apps (fetch)
origin  https://github.com/plotly/dash-sample-apps (push)


text:
Q: Nginx. Directory of index is forbiden I have load balancing nginx server 192.168.2.168 with the following nginx config:
upstream balancer {
server 192.168.2.165;
server 192.168.2.166 backup;
}
server {
listen 80;
server_name 192.168.2.168;
error_log /var/log/nginx/balancer-error_log;

location /something {
proxy_pass http://balancer;
}
}

Then I try 192.168.2.168/something it gives 403 Forbiden
tailf /var/log/error.log on the 192.168.2.165 shows:
*47 directory index of "/usr/share/nginx/html/glpi/" is forbidden, client: 192.168.2.168, server: localhost, request: "GET /glpi/ HTTP/1.0", host: "balancer"

But if I replace http://balancer with http://192.168.2.165 it works fine.
proxy_pass http://192.168.2.165;

What am I doing wrong and how to make upsream servers work?

A: The problem is solved using server_name balancer.home; instead of server_name 192.168.2.168; + I added some headers.
Here is my config:
upstream backend {
server 192.168.2.165;
server 192.168.2.166;
server 192.168.2.167 backup;
}

server {
    listen 80;
    server_name balancer.home;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name balancer.home;

    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;

    error_log /var/log/nginx/balancer-error_log;
    access_log /var/log/nginx/balancer-access_log;

    location / {
            proxy_pass_header   Server;
            proxy_set_header    Host $host;
            proxy_set_header    X-Real-IP $remote_addr;
            proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto $scheme;

    proxy_pass http://backend;
}
}

PS: On upstream servers, the same server_name as on the balance server (domain name) should be specified.


text:
Q: SQL Server: How does the type of an index affect a join's performance? If I'm am trying to squeeze every last drop of performance out of a query what affect does having these types of index's being used by my joins.

*

*clustered index.

*non-clustered index.

*clustered or non-clustered index with extra columns that may not be involved in the join.

Will I gain any performance if I go through and create clustered index's that only contain the columns involved in my joins and nothing else?
(I realize I may have to move the clustered index from another index(making that index non-clustered) since it can only have one.)

A: In addition to Gareth Saul's answer a tiny clarification:

Non-clustered indexes repeat the
included fields, with pointer to the
rows that have that value.

This pointer to the actual data value is the column (or the set of columns) that are in your clustering key.
That's one of the main reasons why you should try and keep the clustering key small and static - small because otherwise you'll waste a lot of space, on disk and in your server's RAM, and static because otherwise, you'll have to update not just your clustering index, but also all your non-clustered indices as well, if your value changes.
This "lookup pointer is the clustering key" feature has been in SQL Server since version 7, as Kim Tripp will explain in great detail here:

What is a clustered index?
In SQL Server 7.0 and higher the
internal dependencies on the
clustering key CHANGED. (Yes, it's
important to know that things CHANGED
in 7.0... why? Because there are still
some folks out there that don't
realize how RADICAL of a change
occurred in the internals (wrt to the
clustering key) in SQL Server 7.0).
What changed is that the clustering
key gets used as the "lookup" value
from the nonclustered indexes.

A: You only get one clustered index - this is what controls the physical storage of the table on disk / in memory.
Non-clustered indexes repeat the included fields, with pointer to the rows that have that value. Having an index on the columns being used in your joins should improve performance. You can further optimise by using "included columns" in your index - this duplicates the row information directly into the index, which can remove the performance penalty of having to look up the row itself to perform the select.
It is useful to pay attention to the order in which your joins occur - the sequence of columns in your index should match up to this. Remember that the SQL engine may optimise and re-order your query internally - profiling may be helpful.
In most situations, you can just use the Database Engine Tuning Advisor - the recommendations it provides are pretty much spot on.

A: If you can your best bet is for a non-clustered index that has all the element of your join in it and if possible the field you are selecting.
This will create a spanning index meaning that all the fields SQL requires to perform are on one index.
If possible have an index which has no unnessasery field in it. Every field added makes the an individual index record larger, the smaller each index record the more you get in each Page. The more index items you get in each page the less you have to go to the Disk.
Clustered Index - Will mean the table is layed out in the order specified in the Index, this means that you will get better performance for select * from TABLE where INDEXFIELD = 3. Unless you are selecting lots of large data items this should not be required.

A:
Will I gain any performance if I go through and create clustered index's that only contain the columns involved in my joins and nothing else?

Not as I understand. The point of a clustered index is that it then sorts the data on disk around that index (hence why you can only have the one), so if your join data isn't being sorted by those exact columns as well, I don't think it'd make any difference. Plus by putting data that might change (as opposed to the key) into the clustered index, you make it more likely that things will need rebuilding peridically, slowing the overall database down.
Sorry if this sounds a daft question, but have you tried running your query through the index tuning wizard? Not foolproof by any stretch but I've had some decent improvements from it in the past.


text:
Q: Fill or ignore required random field with selenium python I am practicing with selenium to log into a website and grab the mortage ticket (print/save/download it as pdf).
The logging page is as follows:
Field 1: Contract number
Field 2: National user-id
Botton: Botton to validate the contract
Field 3: Requests some aleatory personal info (day of birh, mother's name, zip code, National Health ID, voter registration etc.) each time the page is accessed/refreshed
When I log to it (every month) throughout the user page, when it comes to some aleatory info that I don't know by heart (such as National Heatlh ID or voter registration), I refresh the page until it brings me some easy to remember info(phone number, zip code, etc.).
What can I do to go through this last field that requests personal information in a random way(some that I know by heart, others I do not)?
The website code referring to the 3rd field is as follows. The parameters name="zipCode" and placeholder="Zip Code" parts are the ones that keeps changing their values each time the page is refreshed.
input id="aleatoryField" class="mat-input-element mat-form-field-autofill-control
ng-tns-c4-1 cdk-text-field-autofill-monitored ng-dirty ng-invalid ng-touched"
_ngcontent-iqu-c4="" autocomplete="off"
formcontrolname="aleatoryField" inputmode="decimal" matinput=""
pattern="[0-9]*" required="" name="zipCode" placeholder="Zip Code"
aria-describedby="mat-error-2" aria-invalid="true" aria-required="true"

input id="aleatoryField" class="mat-input-element mat-form-field-autofill-control ng-tns-c4-1 cdk-text-field-autofill-monitored ng-dirty ng-invalid ng-touched"
_ngcontent-iqu-c4="" autocomplete="off"
formcontrolname="aleatoryField" inputmode="decimal" matinput=""
pattern="[0-9]*" required="" name="voterId" placeholder="Voter Registration"
aria-describedby="mat-error-2" aria-invalid="true" aria-required="true"

input id="aleatoryField" class="mat-input-element mat-form-field-autofill-control ng-tns-c4-1 cdk-text-field-autofill-monitored ng-dirty ng-invalid ng-touched"
_ngcontent-iqu-c4="" autocomplete="off"
formcontrolname="aleatoryField" inputmode="decimal" matinput=""
pattern="[0-9]*" required="" name="yearBirth" placeholder="Year of Birth"
aria-describedby="mat-error-2" aria-invalid="true" aria-required="true"

# MY CURRENT CODE

from selenium import webdriver

driver = webdriver.Firefox(executable_path="./geckodriver.exe" )

# open the website
driver.get("https://www.habitacaodigital.caixa.gov.br/acesso-cliente")

# FIELD 1: contract info
contract = driver.find_element_by_id("contract")
national_id = driver.find_element_by_id("nationalId")

# FIELD 2: filling the contract info
contract.send_keys("123")
national_id.send_keys("321")

# botton
validate_contract = driver.find_element_by_id("validate_contract")
validate_contract.click()

# FIELD 3: aleatory personal info field (cellphone number, zip code, day of birth, mother's name...)
# aleatory_field = driver.find_element_by_id("aleatoryField")
# aleatory_field.send_keys("HOW TO DEAL WITH THIS PART OVER HERE?")

# undetected Selenium suggestion
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#aleatoryField[formcontrolname='aleatoryField']"))).send_keys("234567")

# LOGGING BOTTON
btn_logging = driver.find_element_by_id("btn_access")
btn_logging.click()

Result with undetected Selenium first suggestion added in

A: It seems you have no problem with dynamic element since element id was never changed. you have problem with input values based on type of the field name appeared on the screen on each login.
You can use python switch case and configured all return type attribute name and then call the function and if it matches the specific name then execute that block only with your input.
def SetInputValue(element, elementAttVal):
    match elementAttVal:
        case "zipCode":
            element.send_keys("400910")
        case "voterId":
             element.send_keys("1234588999")
        case "yearBirth":
            element.send_keys("1990")

//identify the element
element=WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input#aleatoryField")))
//Get the name attribute value
elementAttVal=element.get_attribute("name")
print(elementAttVal)
//Set the input based on name attribute
SetInputValue(element,elementAttVal)

Update: with if..block like that you have add the remaining config as well
def SetInputValue(element, elementAttVal):
        if elementAttVal=="zipCode":
                element.send_keys("400910")
        if elementAttVal=="voterId":
                element.send_keys("1234588999")
        if elementAttVal=="yearBirth":
                element.send_keys("1990")

    //identify the element
    element=WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input#aleatoryField")))
    //Get the name attribute value
    elementAttVal=element.get_attribute("name")
    print(elementAttVal)
    //Set the input based on name attribute
    SetInputValue(element,elementAttVal)

A: To send a character sequence to the <input> element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

*

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#aleatoryField[formcontrolname='aleatoryField']"))).send_keys("234567")

*Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='aleatoryField' and @formcontrolname='aleatoryField']"))).send_keys("234567")

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Jquery submit vs. javascript submit I am trying to invoke a form validation when clicked on ordinary button. This seems to work good with jQuery, but not with plain javascript. Can anyone explain this difference between jquery's .submit() and javascript's .submit() methods? Or what am I doing wrong?

<title>Form Submit</title>

<form action="index.php" name="loginform" method="post" onsubmit="return validateForm(this);">
  <input name="username" placeholder="username" required="required" type="text" />
  <input name="send1" type="button" value="Login1" onclick="$(document.forms.loginform).submit();" />
  <input name="send2" type="button" value="Login2" onclick="document.forms.loginform.submit();" />
  <input name="send3" type="submit" value="Login3" />
   Login4
   Login5
</form>

A: The DOM submit() method does not trigger submit events. jQuery's does.

A: I know this is an old question, but it is not been answered very well, so here you go:
The submit() DOM method in vanilla javascript is used to submit a form, but the JQuery submit() method is used to trigger a submit event.
You need to use the submit event
Example:
cosnt form = document.querySelecor('form')
form.addEventListener('submit', e => {
    e.preventDefault()
    /* Other stuff */
})

OR
const form = document.qeurySelector('form')
form.onsubmit = e => {
    e.preventDefault()
    /* Other stuff */
})


text: Q: StartScan() and StopScan() for lower APIs The methods StartLeScan() and StopLeScan() in the class BluetoothAdapter have been deprecated and removed from Android Library.The new methods startscan() and stopscan() support only API > 21. Could you please tell me about any alternative methods to scan for an I beacon and obtain its Proximity UUID for  APIs lower than 21 as well?


text:
Q: What is the release version for widgets documented in https://api.flutter.dev? e.g. where is AnimatedGrid? Let's take the case of AnimatedGrid, which is available in the file animated_scroll_view.dart of master branch in
https://github.com/flutter/flutter/tree/master/packages/flutter/lib/src/widgets.
Yet, it is not available in the latest (as of today) Flutter release 3.1.10 here https://github.com/flutter/flutter/tree/3.3.10/packages/flutter/lib/src/widgets. Hence, the sample program from documentation not even compile.
I cannot find either in API docs which version provides the AnimatedGrid?

A: In order to find out when a feature/widget was first released i usually would go to flutter.dev and find the page for that widget.
Let's take the example of the SelectionArea widget which was relased in Flutter 3.3 as we know from this post.
So, in flutter.dev i click on the little file icon as shown below:

That will take us to the file in Github where that widget is defined. There look for the line defining the Widget and click on its line-number to open a context menu and click on "View git blame":

there you will find the commit that made the last change on that line. If between the comit description and the file there is an icon like this

click on it until you travel to the first commit that introduced that class/line. Click on that comit's description, in our case would be as follows:

there you will see the last and the first Flutter version to contain that change with three dots in between that will show all the versions between the first and the last version that contain that change:

Look for the first version where no "pre" sufix is present. That will be the release version (3.3 in our case)

What if the file-icon in flutter.dev does not redirect to a valid github page?
Well, i believe that means there is not yet a release for that widget, as is the case for AnimatedGrid where we get this:

In that case you still can find some information. Go to flutter/flutter in Github and search for AnimatedGrid in that repository

there you can view the commits that contain AnimatedGrid and look for the oldest, in the case of AnimatedGrid, as of today there is only one commit that contains that word. Click on it and you will again see all the versions that include changes on that file

there we can see that there is not yet a final release for that widget (al releases have the "pre" suffix!).


text:
Q: Changing default font weight for FiraSans and smath I'd like to use FiraSans as default for my documents. The default values work fine, but I'd like FiraSans Medium as my default bold font and FiraSans Light as my default regular font.
I already tried \renewcommand{\seriesdefault}{l} and
\renewcommand{\bfdefault}{mb} but it has no effect (this worked while I used OpenSans - but with FiraSans only the regular font is affected, but the bold font stays untouched).
The several font series can be looked up here: ftp://ftp.rrzn.uni-hannover.de/pub/mirror/tex-archive/fonts/fira/latex/FiraSans.sty
Further, I have a problem with sfmath as it uses FiraSans Regular even when I use \renewcommand{\seriesdefault}{l} for FiraSans Light. I'd like to have the math font in light weight, too. Is that possible?
MWE:
% ATTRIBUTES
\documentclass{scrbook}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\parskip\baselineskip
\parindent0pt

% FONT
\usepackage[T1]{fontenc}
\usepackage[sfdefault]{FiraSans}
\usepackage{sfmath}

% MATH
\usepackage{mathtools}

\begin{document}

\subsubsection{How it is now (default)}

\textbf{This is bold} and this is regular font weight with $\sin(123456789)$ math.

\subsubsection{Hot I'd like it}

{\firalight But I'd like Fira Light as my standard regular font.}

{\firamedium And Fira Medium as my standard bold font.}

{\firalight And \texttt{sfmath} shall adapt Fira Light for $\sin(123456789)$ math, because at the moment it uses Fira Regular for math.}

\end{document}

A: Something like this? FiraSans has a rather non-standard font setup, and sfmath hard-codes the font series. You may need to fish out and redo some more declarations but this should give you the idea:
\documentclass{scrbook}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[sfdefault,light]{FiraSans}
\usepackage{sfmath}
\usepackage{mathtools}
\makeatletter
\def\bfseries@sf{m}
\SetSymbolFont{operators}{normal}{\math@encoding}{\math@sfdefault}{l}{n}
\SetSymbolFont{operators}{bold}{\math@encoding}{\math@sfdefault}{m}{n}
\DeclareSymbolFont{SFMath}{\math@encoding}{\math@sfdefault}{l}{sl}
\SetSymbolFont{SFMath}{normal}{\math@encoding}{\math@sfdefault}{l}{sl}
\SetSymbolFont{SFMath}{bold}{\math@encoding}{\math@sfdefault}{m}{\mathnormal@bold@shape}
\makeatother
\begin{document}

\subsubsection{How it is now (default)}

\textbf{This is bold} and this is regular font weight with $\sin(123456789)$ math.

\end{document}

Note that it is debatable whether you should typeset a document entirely in sans or maths in it at all.


text:
Q: JAVA Swing GUI Components howto RTL view? How can i make my Java Swing GUI Components [Right To Left] for Arabic language from NetBeans Desktop Application?

A: Don't you just have to use:
Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT )

I believe that the swing components all already have support for RTL, don't they?
Not sure how/where you'd do that in regards to netbeans, though.

A: The call of
 Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT )

should do the trick. But be sure to use the SwingConstants LEADING and TRAILING instead of LEFT and RIGHT in your layouts. The same goes for GridBagConstraints.LINE_START or LINE_END instead of WEST or EAST, and probably some similar cases which I forgot to mention.

A: You could use alignment, but that would not handle the complexities if you have English letters or numbers embedded within your text.
It might be preferable to use some sort of styled text widget or even an embedded HTML/rich text viewer.
I don't think that standard JLabels can handle the complexities otherwise.

A: you could use it if you have components inside panels inside contentPane
        Component[] component = contentPane.getComponents();
    for(int i=0; i<component.length; i++){
        component[i].applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        Component[] cp = ((Container) component[i]).getComponents();
        for(int j=0; j<cp.length; j++){
            try{
                ((Component) ((JComboBox) cp[j]).getRenderer()).applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
            }catch(Exception e){
                continue;

            }
        }
    }


text:
Q: Django admin select all checkbox not working I'm using Django 2.2.7 with python 3.8 in pipenv 2018.11.26. In my django admin i can't select all items checkbox (see pic below) in list of model objects and not see datepicker with actions "now" & "today".

A: I found a place that causes this problem.
In my settings.py:
FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

This setting override all widgets and his templates and therefore not work some of widgets in my django admin.


text:
Q: Function evaluated in Brownian motion vanishes implies that the function itself vanishes? tl;dr, here's my question:

Question. Let $f(t,x)$ be a measurable function such that $f(t,B_t)=0$ almost everywhere on $[0,T]\times\Omega$ for a Brownian motion $B_t$. Does this imply that $f(t,x)=0$ almost everywhere on $[0,T]\times\mathbb R$?

Given that Brownian motion is recurrent and normally distributed (and hence,
the probability that $|B_t|>a$ for any $a$ is nonzero, albeit very small for large $a$), it seems intuitive enough that this should be true, but I have been unable to prove it conclusively.

For context:
I was reading the answer to this question (which can actually be found on this MO question), and there was a detail that left me unsatisfied.
If we remove any specificities related to the linked problem and look at the core of the argument, unless I'm mistaken, it goes as follows (tl;dr skip to question below):

*

*Let $(B_t)_{t\geq0}$ be a Brownian motion (for simplicity), and let $f(t,x):\mathbb R^+\times\mathbb R\to\mathbb R$ be a measurable function.

*Suppose that $\int_0^tf(s,B_s)~\text d s=0$ for all $t\leq T$.
Then, for almost every $\omega$, $f\big(t,B_t(\omega)\big)=0$ for almost every $t$ (by the Lebesgue differentiation theorem).

*By Fubini's theorem, we can argue that $f\big(t,B_t(\omega)\big)=0$ almost everywhere on $[0,T]\times\Omega$.

*Therefore $f(t,x)=0$ for almost all $(t,x)$.

The only part of the argument that I'm not confortable with (which is the one that is left unexplained in the linked MO answer) is part 4, which is essentially the question above.

A: Let $D:=\{(t,\omega):f(t,B_t(\omega)\not=0\}$ and $C=\{(t,x):f(x,t)\not=0\}$. Observe that $D=\varphi^{-1}(C)$, where $\varphi(t,\omega) =(t,B_t(\omega))$ (mapping $[0,T]\times\Omega$ into $[0,T]\times\Bbb R$). Consequently, writing $\lambda$ for Lebesgue measure on $[0,T]$,
$$
0=\lambda\otimes\Bbb P(D) =\int\int 1_{C}(t,x){1\over\sqrt{2\pi t}}e^{-x^2/2t}\,dt\,dx.
$$
Because the integrand $(t,x)\mapsto{1\over\sqrt{2\pi t}}e^{-x^2/2t}$ is strictly positive, it must be that $\int\int 1_{C}(t,x)\,dt\,dx=0$. That is, $\lambda\otimes\Bbb P(C)=0$.

A: For any measurable set $A \subseteq [0,T] \times \Omega$ it holds that
$$\begin{align*} \{(t,\omega); (t,B_t(\omega)) \in A\} &= \int_0^T \! \int 1_A(t,B_t) \, d\mathbb{P} \, dt \\ &= \int_0^T \! \int 1_A(t,x) \frac{1}{\sqrt{2\pi t}} e^{-x^2/2t} \, dx \, dt. \end{align*}$$
Since $e^{-x^2/2t}$ is strictly positive, this implies
$$(\lambda|_{[0,T]} \times \mathbb{P})(A) = 0 \iff (\lambda|_{[0,T]} \times \mathbb{P})(\{(t,B_t) \in A\})=0.$$
Consequently, if we set $A:= \{(t,x); f(t,x) \neq 0\}$, then we find that
$$(\lambda|_{[0,T]} \times \mathbb{P})(\{(t,\omega); f(t,B_t(\omega)) \neq 0\}) = 0$$
if, and only if,
$$(\lambda|_{[0,T]} \times \mathbb{P})(\{(t,x); f(t,x) \neq 0\})=0.$$


text:
Q: MSDN example on async/await - can't I reach the break point after the await call? In trying MSDN's example on async/await, why I can't reach a break point after the await operator ?
private static void Main(string[] args)
{
    AccessTheWebAsync();
}

private async Task<int> AccessTheWebAsync()
{
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    /*** not relevant here ***/
    //DoIndependentWork();

    // The await operator suspends AccessTheWebAsync.
    //  - AccessTheWebAsync can't continue until getStringTask is complete.
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.
    //  - Control resumes here when getStringTask is complete.
    //  - The await operator then retrieves the string result from getStringTask.
    string urlContents = await getStringTask;

    // The return statement specifies an integer result.
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
    return urlContents.Length;
}

My understanding is that the await is a construct that abstracts the asynchronous flow from the developer - leaving him/her as if working synchronously. In other words, in the code above, I do not care about how and when the getStringTask finishes, I care only about it finishing and using its results. I would expect then to be able to reach the break point after the await call at sometime.

A: You call your asynchronous method from a Console application's Main method without waiting for the async method to finish. As a result, your process terminates before your task has a chance to complete.
Since you can't convert a Console application's Main to an asynchronous (async Task) method, you'll have to block on the asynchronous method, by calling Wait or .Result:
private static void Main(string[] args)
{
    AccessTheWebAsync().Wait();
}

or
private static void Main(string[] args)
{
    var webTask=AccessTheWebAsync();
    //... do other work until the resuls is actually needed
    var pageSize=webTask.Result;
    //... now use the returned page size
}


text:
Q: Fetching Core Data related Entities properties I have two many-to-many related Entities, Customer and City and NSManagedObject subclasses generated from them. I have relationship from Customer to City called cities. In City there is a property called city. Now I am trying to fetch everything from entity Customer with simple fetchResultsController:
-(NSFetchedResultsController *) fetchedResultsController {

  if (_fetchedResultsController != nil)
  {
      return _fetchedResultsController;
  }
  self.managedObjectContext = [[PTDataManager sharedManager] managedObjectContext];
  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer"
                                            inManagedObjectContext:[self managedObjectContext]];
  [fetchRequest setEntity:entity];

  _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                 managedObjectContext:self.managedObjectContext
                                                                   sectionNameKeyPath:nil
                                                                            cacheName:nil];
  _fetchedResultsController.delegate = self;

  return _fetchedResultsController;
}

As a result I am retrieving everything fine except cities property ((null) value) with predicate
@"cities.name CONTAINS[cd] %@"

In Customer subclass I can use method:
-(City *)city
{
  return (CDCities *)[[PTDataFetchHelper sharedInstance] entityForName:@"City"
                                                          withServerID:self.city_server_id
                                                             inContext:[self managedObjectContext]];
}

and I am retrieving city-values fine, but this way slows down UI (displaying this data in tableView).
So, questions:

*

*if I perform basic fetch like this, am I retrieve values of specified entity only, or values from related entities too?

*If I need additional predicate, how can I modify it to fetch also city properties from City entity?

A: A fetch request only fetches one entity type. If you fetch Customer, you get Customers. But you can traverse Core Data relationships without doing additional fetch requests. Just ask any Customer instance for the value of its cities attribute. That will get you zero or more City instances, and you can ask each one of those for its city attribute.
I'm not sure what you're getting at with @"cities.city [cd]". That's not a predicate. It could be part of a predicate, but it doesn't match the city attribute against anything. It's like one side of an equation.


text:
Q: String comparison without strcmp() How about comparing two strings with equality operator. I saw in GNOME glib library also. They compare two strings with == operator. Here is the code:
/* Code from Singly Linked List - gslist.c*/

GSList*
g_slist_find (GSList        *list,
              gconstpointer  data)  // Here gconstpointer is `const void*`
{
  while (list)
    {
      if (list->data == data)    // What is compare here?
        break;
      list = list->next;
    }

  return list;
}

So, Is glib code works or not always?

A: The == operator when used on char* will simply check to see if they point to the same memory address.  Sure every string pair which compares to true with == will also compare true with strcmp.  However the reverse is simply not true.  It is very possible that two strings are lexically equivalent but reside at different addresses
For example
char* p1 = "hello world";

// p2 will point to the same address as p1.  This is how pointer
// assignment work
char* p2 = p1;
printf ("%s\n", p1 == p2 ? "true" : "false")            // true
printf ("%s\n", strcmp(p1, p2) == 0 ? "true" : "false") // true

// the addressed return by malloc here will not be the address
// of p1.
char* p3 = malloc(strlen(p1) + 1);
strcpy(p3, p2);
printf ("%s\n", p1 == p3 ? "true" : "false")            // false
printf ("%s\n", strcmp(p1, p3) == 0 ? "true" : "false") // true


text:
Q: JTable multiple selection without using keyboard only using mouse Here is my code. I want to select multiple rows in JTable, I am using the following line:
table.getColumnModel().getSelectionModel().setSelectionMode(
    javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

With the above line I am able to select multiple rows using keyboard, but requirement is to select only using mouse.
Is there any thing other than this, that Java provides for multiple selection only using mouse without using keyboard?

A: If you have this code, you need only yo push ctrl + click multiple.
Edit: But if you don't want to use keyboard it's possible i think, try this:
Select Multiple Items In JList Without Using The Ctrl/Command Key

A: I don't think it's possible. I suggest adding an additional column to the table, containing a checkbox allowing to mark the row as selected. Of course, you won't be able to use the table selection model to know which rows are selected.

A: Yes, you can select multiple rows without using keyboard by overriding the changeSelection function, like this:
@Override
        public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
            latestClickedRowIndex = rowIndex;
            ListSelectionModel selectionModel = getSelectionModel();
            boolean selected = selectionModel.isSelectedIndex(rowIndex);
            //throw new UnsupportedOperationException("Paila.");
            if (selected) {
                selectionModel.removeSelectionInterval(rowIndex, rowIndex);
                getValueAt(rowIndex, columnIndex);
            } else {
                selectionModel.addSelectionInterval(rowIndex, rowIndex);
            }
        }

A: I finally used this code:
JTable table = new JTable(){
    @Override
    public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
        super.changeSelection(rowIndex, columnIndex, true, extend);
    }
};

This way CTRL(toogle) is always pushed(true).


text:
Q: how to store values of treeview into database using asp.net I am working on a news portal in asp.net. In that I have used a treeview for showing all the Categories of news. I have used following code to insert News category into sql server databse:
foreach (TreeNode node in TreeView1.CheckedNodes)
{
    long NewsCategory = Convert.ToInt64(node.Value);
    long NewsID = News_ID;
    int rt1 = new Process_NewsCategory().insert(objNewsCategory);
}

But it is showing error:

-Collection was modified; enumeration operation may not execute

Please help me.

A: Try to use the code below:
foreach (TreeNode node in TreeView1.CheckedNodes.ToList())
{
   long NewsCategory = Convert.ToInt64(node.Value);
   long NewsID = News_ID;
   int rt1 = new Process_NewsCategory().insert(objNewsCategory);
}


text:
Q: Matrix element cannot be updated due to function returning different reference I am trying to write a templated Matrix class that can be extended and used for other things like vectors. However, I cannot figure out why operator[] in the Row class, does not return the reference to the actual data_ vector in the Matrix, but a reference to a different data_.
The code below is the code for the Matrix. I'm using a Row class, which is hidden in a namespace so that I can use the double square brackets to access an element. In that class there is a shared pointer to the parent matrix, so that I can access the data_ vector in it from the Row class, which doesn't seem to work though.
#ifndef YAGE_MATH_MATRIX_HPP
#define YAGE_MATH_MATRIX_HPP

#include <iostream>
#include <memory>
#include <vector>

namespace yage
{

template<int Rows, int Cols, class Type> class Matrix;

namespace detail
{

template<int Rows, int Cols, class Type> class Row
{
private:
    std::shared_ptr<Matrix<Rows, Cols, Type>> parent_;
    int index_;

public:
    Row<Rows, Cols, Type>(std::shared_ptr<Matrix<Rows, Cols, Type>> parent, int index) :
        parent_(parent), index_(index)
    {}

    Type &operator[](int col)
    {
        std::cout<<"Other Data: "<<&parent_->data_[index_*Cols+col]<<'\n';
        return parent_->data_[index_*Cols+col];
    }
};

} // detail

template<int Rows=4, int Cols=4, class Type=double> class Matrix
{
    friend class detail::Row<Rows, Cols, Type>;
private:
    std::vector<Type> data_;

public:
    Matrix<Rows, Cols, Type>() : data_(Rows*Cols) {}
    Matrix<Rows, Cols, Type>(int rows, int cols) : data_(rows*cols) {}

    detail::Row<Rows, Cols, Type> operator[](int row)
    {
        std::cout<<"Main Data: "<<&data_[10]<<'\n';
        return detail::Row<Rows, Cols, Type>(std::make_shared<Matrix<Rows, Cols, Type>>(*this), row);
    }
};

} // yage

#endif

I tested these classes with the following program
#include "Math/matrix.hpp"

#include <iostream>

int main()
{
    yage::Matrix<4, 4> matrix;

    matrix[2][2];
    return 1;
}

and the output was
Main Data: 0x1f72960
Other Data: 0x1f72e30

which point to two different locations.
I know that there are different ways of solving this, for example using the operator(x, y) overload, but I am curious about what mistake I have made.
Thank you for your help.


text:
Q: LaTeX Error: Environment FlushLeft undefined while I receive an error of "LaTeX Error: Environment FlushLeft undefined." I did not find a package for FlushLeft.
\noindent\rule{\textwidth}{1pt}
\begin{FlushLeft}
\mycfs{7} \begin{concmath} $\blacktriangleright$ Text \newline
\qquad initial \leftarrow 2 \newline
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \newline
$\blacktriangleright$ Text \newline
\qquad node \leftarrow initial
\end{concmath}
\end{FlushLeft}
\noindent\rule{\textwidth}{1pt}

P.S. Before I did not receive error when using LNCF template, but this time I am using ACM journal template.


text:
Q: avc: denied { read } for name="/" dev="rootfs" ino=1 scontext=u:r:untrusted_app I was not able to find here solution to read/write problem on Android File manager application I am trying to create. When running on real device, I am not able to delete a file from SD card.
Could anyone guide me, what am I doing wrong and how to fix the permissions?
I have added read/write permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

but anyway, I am getting this error message:
avc: denied { read } for name="/" dev="rootfs" ino=1 scontext=u:r:untrusted_app

for dependencies I am using:
compile 'org.apache.directory.studio:org.apache.commons.io:2.4'

Full LogCat:
02-28 10:59:49.740 12067-12067/? W/art: Unexpected CPU variant for X86 using defaults: x86_64
02-28 10:59:49.765 12067-12067/? W/System: ClassLoader referenced unknown path: /data/app/com.example.filemanager-1/lib/x86_64
02-28 10:59:49.770 12067-12067/? I/InstantRun: Instant Run Runtime started. Android package is com.example.filemanager, real application class is com.example.filemanager.FileManager.
02-28 10:59:49.797 12067-12074/? E/art: Failed writing handshake bytes (-1 of 14): Broken pipe
02-28 10:59:49.797 12067-12074/? I/art: Debugger is no longer active
02-28 10:59:49.797 12067-12074/? I/art: Starting a blocking GC Instrumentation
02-28 10:59:50.284 12067-12067/? W/System: ClassLoader referenced unknown path: /data/app/com.example.filemanager-1/lib/x86_64
02-28 10:59:50.337 12067-12067/? W/ini.filemanager: type=1400 audit(0.0:27): avc: denied { read } for name="/" dev="rootfs" ino=1 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:rootfs:s0 tclass=dir permissive=0
[ 02-28 10:59:50.356 12067:12067 W/         ]
Process pipe failed
02-28 10:59:50.376 12067-12089/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-28 10:59:50.376 12067-12089/? D/OpenGLRenderer: Swap behavior 1
02-28 10:59:50.390 12067-12089/? E/EGL_emulation: tid 12089: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
02-28 10:59:50.390 12067-12089/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x76656d668840, error=EGL_BAD_MATCH


text:
Q: Jquery writing modular functions I am trying to write a main function which is called App.
It has certain public and private functions.see code below.
I want it write it in a modular way.
The problem is I want to map some private functions to public function and i am unable to do that.
For example;
I want to call App.ModuleA which should call _A() private functions and give me access to its public functions like  App.ModuleA.fun_1.
I know to make it to work; I need to make _A() as public. But is it possiple to map functions ?
How can I achieve such mapping? Can any one suggest better Coding structure So i Can access sub functions inside App and their public functions too?
For Now I am getting error TypeError: _A is not a function when i call App.ModulaA();
  var App = function () {
      // App Private Functions
      var _A = function () {
          return {
              fun_1: function () {
                  alert("_A.fun_1");
              },
              fun2: function () {
                  alert("_A.fun2");
              }
          };
      }();
      // App Public Functions
      return {
          init: function () {
              alert("App.init");
          },
          ModulaA: function () {
              return _A(); // doesnot work
              // return this._A(); // doesnot work
          }
      };
  }();

App.ModulaA();

A: _A() is not self invoking function, thus remove parenthesis, see it in action here
}() <---- remove parenthesis

A: You need to make one of two changes:
var _A = function() {
    //...
}();

// change to:
var _A = function() {
    //...
};

Or:
return _A();
// change to:
return _A;

In your example _A has already been evaluated so is no longer a function.

A: var App = function () {
    //App Private Functions
    var _A = function () {
        return {
            fun_1: function () {
                alert("_A.fun_1");
            },
            fun2: function () {
                alert("_A.fun2");
            }
        };
    },
    init = function () {
        alert("App.init");
    },
    ModulaA = function () {
        return _A();
    };

    // App Public Functions
    return {
        init: init,
        ModulaA: ModulaA
    };
}();

var moduleA = App.ModulaA();
moduleA.fun_1();    //Works
moduleA.fun2();    //Works


text:
Q: How to display recaptcha in an ajax based modal window I am having a hard time calling a recaptcha in a modal window. When I run the page it works fine but when I call it in modal window it shows as blank. Can you please guide me in what am I doing wrong.
This is my code I have out in my ajax page
Main page
Ajax Page
PS. I am using a custom theme for my recaptcha as its responsive
this is my fiddle

Incorrect. Please try again.

        Enter the words above:
        Enter the numbers you hear:

        <input type="text" id="recaptcha_response_field" name="recaptcha_response_field">

                Get another CAPTCHA

                 Get an audio CAPTCHA

                 Get an image CAPTCHA

                 Help

    <textarea name="recaptcha_challenge_field"></textarea>
    <input type="hidden" name="recaptcha_response_field" value="manual_challenge">

A: Looking at the Recaptcha docs, it looks like you have to use the Ajax API, rather than their regular API for Ajex Recaptcha requests. You can find more details about it on this page under the header Ajax API. Doing it that way, instead of loading a separate page, is probably the easier method of making it work.
Google has a demo for using an Ajax call here, and making that use a modal window wouldn't be very difficult.

A: In order to show the recaptcha in a modal, you should render the element in which recaptcha exists in an init function because it is necessary that the modal should be rendered in advance to show your recapthca. For example:
In my index.jsp where I have a modal template:


text:
Q: Java - Castor XML mapping : how to concatenate two Java field values into one XML attribute value and vice versa Consider the following period : 2017-11-03 to 2017-11-06

*

*The XML has one element : TimePeriodCovered: v="2017-11-03T00:00Z/2017-11-06T00:00Z" which is a concatenation of two dates ;

*The Java object maps this field with two attributes (Date) : startPeriod & endPeriod

.java
public class foo implements Serializable {

    private Date startPeriod;

    private Date endPeriod;

    ...
}

.xsd
<xs:element name="container" >
    <xs:complexType>
        <xs:sequence>
            <xs:element name="foo" type="fooType" />
            ...
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:complexType name="fooType">
    <xs:sequence>
        <xs:element name="TimePeriodCovered" minOccurs="0" type="PeriodType" />
        ...
    </xs:sequence>
</xs:complexType>

<xs:complexType name="PeriodType">
    <xs:attribute name="v" use="required">
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:pattern value="[1-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]Z?/[1-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]Z?" />
            </xs:restriction>
        </xs:simpleType>
    </xs:attribute>
</xs:complexType>

mapping.xml
I have absolutely no idea. What should it be ?


text:
Q: Compiling FreeRTOS in IAR7.5 from IAR4.0 - Cstartup.s79 error I am trying to recompile a (modified) FreeRTOS project from IAR4.0 to IAR7.5 and am getting errors in Cstartup.s79 of the type described here:
Is there a suitable version of Cstartup.s79 anywhere for versions of IAR beyond 4.0? I am not familiar with ARM Assembler and running out of time.
The relevant information in the link is:
If I copy intrinsics.h to intrinsic.h, C-compilation seems to work, but I still get these assembler errors:

Error[116]: Section type missing
  FreeRTOSV4.1.3\FreeRTOS\Demo\uIP_Demo_IAR_ARM7\SrcIAR\Cstartup.s79 34
  Error[116]: Section type missing
  FreeRTOSV4.1.3\FreeRTOS\Demo\uIP_Demo_IAR_ARM7\SrcIAR\Cstartup.s79 35
  Error[40]: Bad instruction
  FreeRTOSV4.1.3\FreeRTOS\Demo\uIP_Demo_IAR_ARM7\SrcIAR\Cstartup.s79 41
  Warning[24]: ENDMOD directive is ignored (only one module is allowed)
  FreeRTOSV4.1.3\FreeRTOS\Demo\uIP_Demo_IAR_ARM7\SrcIAR\Cstartup.s79 220
It seems it doesn't like these lines: RSEGINTRAMSTART_REMAP
  RSEGINTRAMEND_REMAP org0 ENDMOD

A: Example cstartup.s files can be found in your ewarm installation. Look in src/lib/arm if you have an ARM-capable devices (Cortex-A/R or legacy devices) or src/lib/thumb if you have a Cortex-M device.
That said, there are two major technology steps between ewarm 4.1 and ewarm 7.5 so you should expect more problems than the cstartup.s issue. There is a migration guide in the documentation catalog and it covers both the step from 4.x to 5.x and 5.x to 6.x (7.x is essentially the same as 6.x).

A: The answer, as suggested by IAR is to go back to using 4.41. Hooray. Or pay someone to do the port from EWARM 4.41 to 7.8
That was well worth the £1500 a year support we pay them.


text:
Q: Paging using REST/OData with SP 2013 I'm trying to do paging on a document library (also trying this on a list) with SP 2013 using REST/OData but I can't seem to get the skipping of items working.
Here are some examples of URLs that I'm trying on my own SP 2013 farm and it also doesn't work on my Office 365 2013 Dev Preview farm. Results are returned and $top and $orderby work fine but it never skips any items. i.e. I can take the $skip out of the URL and I get the same result.
http://sp15/_api/web/lists/GetByTitle('FAQ')/Items?$skip=2&$top=2&$orderby=ID
http://sp15/_api/web/lists/GetByTitle('FAQ')/Items?$skip=2
http://sp15/_api/web/lists/GetByTitle('FAQ')/Items?$skip=2&$top=2

http://sp15/_api/web/lists/GetByTitle('Documents')/Items?$skip=2&$top=2&$orderby=ID
http://sp15/_api/web/lists/GetByTitle('Documents')/Items?$skip=2&$top=2&$orderby=ID desc

etc.
Any ideas on what I'm doing wrong?

A: In my experience, none of the above solutions work - this could be because I was attempting this using an external list. To implement paging, I added ?$skiptoken=Paged=TRUE&$top=100 to the end of the URI. The URI for the next page will be included under JSON.d.__next. Once the last page is reached __next will not be present

A: I'm not that familiar with REST but try the old syntax:
Example: *http://sp15/_vti_bin/ListData.svc/FAQ?$skip=4&$top=2*

A: I see the same issue on SP2013 online with the new OData V3 _api endpoint. For CRUD operation it might be better to use the OData v2 listdata.svc endpoint for the time being.

A: Vadim's response is very close, but his query string is off a bit. The issue isn't really his, its Microsoft's as they are not being consistent with their URI escaping.
I used the Postman extension for Chrome and by examining the __next value returned when using $top (which is alternative approach worth considering) I noticed that there is an ampersand that is not escaped properly in the __next values. Using that approach I was able to get pagination with 2013 REST OData calls working. Here is the relevant code to use in conjunction with Vadim's response.
var queryString = "?%24skiptoken=Paged%3DTRUE%26p_ID%3D" + (startItemId - 1) + '&%24top=' + itemCount;

A: The $skip parameter does not work in SharePoint 2013 for list items. It only works for collection of data (like list collections, ecc..).
See my comment at the end of this article:
http://msdn.microsoft.com/library/d4b5c277-ed50-420c-8a9b-860342284b72.aspx

A: Currently $skip query option is not supported in SharePoint 2013/Online.
According to Use OData query operations in SharePoint REST requests:

The $skip query option does not work with queries for SharePoint
  list items.

But you could utilize $skiptoken query option to return paged results as demonstrated below.
Format:  $skiptoken=Paged=TRUE&p_ID=<last item id to skip>&$top=<items count>
Example
The example demonstrates how to retrieve the limited count of items (2 items) with id equals or greater 2  from Pages library:
function getPagedItems(webUrl,listTitle,startItemId,itemsCount)
{
    var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle +  "')/items?$skiptoken=" + encodeURIComponent('Paged=TRUE&p_SortBehavior=0&p_ID=' + (startItemId-1) + '&$top=' + itemsCount);
    return executeRequest(endpointUrl,'GET');
}

getPagedItems('https://contoso.sharepoint.com/','Pages',2,2)
.done(function(data){
    if(data.d.results.length == 0){
        console.log('Items not found');
        return;
    }
    for(var i = 0; i < data.d.results.length; i++){
        var item = data.d.results[i];
        console.log(item.Title);
    }
});

where
function executeRequest(url,method,headers,payload)
{
    if (typeof headers == 'undefined'){
        headers = {};
    }
    headers["Accept"] = "application/json;odata=verbose";
    if(method == "POST") {
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
    }

    var ajaxOptions =
    {
       url: url,
       type: method,
       contentType: "application/json;odata=verbose",
       headers: headers
    };
    if(method == "POST") {
      ajaxOptions.data = JSON.stringify(payload);
    }

    return $.ajax(ajaxOptions);
}


text:
Q: action complete notification I'm new in JSF. I'm working on some table with many rows. I want to delete some row:
<h:commandButton action="#{users.deleteSelectedUsers}" onclick="return confirm('Are you sure?')"  value="Delete Users">
After deleting I want to add a new row on top of the table with notification with some info. To which event I can add the function? If I'm putting <f:ajax> between <h:commandButton> the table is not rendered.

A: You should add <f:ajax render="@form"> so that the form with the table will be refreshed...


text:
Q: I want to create a global MediaPlayer that will keep playing no matter which layout is displayed Instead of creating one in my menu class, I'd like to create a global one outside of the menu class that I can call to keep the sound playing no matter which activity is started. I'm a noob to java, but I have searched and can't find a solution. Here is my "menu" activity. As you can see my MediaPlayer snd is local so it gets paused when the onPause method gets called.
    public class Menu extends Activity{

MediaPlayer snd;
ToggleButton btnSound;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu);
    snd = MediaPlayer.create(getApplicationContext(), R.raw.bgmusic);
    snd.start();
    btnSound = (ToggleButton) findViewById(R.id.tglSound);

@Override
protected void onPause() {
    super.onPause();
    snd.pause();
}

A: The best way to implement your requirement is using a service. You can start a service while the app is intialised. Inside the service start a mediaplayer and start playing. So evenif you are navigating to next or other activities the media will keep playing. You can also give property to the service when to start ad stop. Isted of pausing or stoping mediaplayer you can just stop the service so that the mediplayer will also stop playing. Hope this link will help you for sure.

A: The answer to your problem lies in the Android reference:
MediaPlayback

If you want your media to play in the background even when your
  application is not onscreen—that is, you want it to continue playing
  while the user is interacting with other applications—then you must
  start a Service and control the MediaPlayer instance from there. You
  should be careful about this setup, because the user and the system
  have expectations about how an application running a background
  service should interact with the rest of the system. If your
  application does not fulfil those expectations, the user may have a
  bad experience. This section describes the main issues that you should
  be aware of and offers suggestions about how to approach them.

A: Create a service like this snippet:
public class whatEverYourServiceName extends Service{

@Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);

//Add your code here mate

}

@Override
public void onDestroy(){
super.onDestroy();

//Add what do you want to do here when the service is stop like do a backflip
snd.pause();
}

@Override
public IBinder onBind(Intent arg0) {

return null;
}

}

Then call it using this
Intent it = new Intent();
it.setAction("your.package.name.whatEverYourServiceName");
startService(it);

Then add this to your manifest
 <service
    android:name="your.package.name.whatEverYourServiceName"
    android:label="Your Service Homie"
    android:process=":my_process" >
    <intent-filter>
        <action android:name="your.package.name.whatEverYourServiceName" >
        </action>
    </intent-filter>
</service>

To stop the sound just stop the service using this
stopService(new Intent(this, whatEverYourServiceName.class));

Hope it helps.


text:
Q: How to grouping with distinct or group max sql i have date like this Data
id      name period difference
6172    A      6      10
6172    A      3      10
10099   AB     12     24
10099   AB     6      24
10099   AB     3      24
10052   ABC    12     26
10052   ABC    6      26
10052   ABC    3      26
9014    ABCD   12     21
9014    ABCD   6      21
9014    ABCD   3      21

how to get result like this
id      name    period  difference
6172    A         6      10
10099   AB        12     24
10052   ABC       12     26
9014    ABCD      12     4

i try with distinct on (id), but the result like this
id     name    period   difference
6172    A         6      10
10099   AB        6      24
10052   ABC       6      26
9014    ABCD      6      4

A: The query you want looks something like:
SELECT DISTINCT ON (id) *
FROM Data
ORDER BY id, period DESC;

Demo
This is probably the most efficient way to write your query on Postgres.  Note that DISTINCT ON syntax does not support more than one column in the ON clause.  The above logic happens to work here assuming that id would uniquely identify each group (that is, that id would always be unique).  If not, then we might have to resort to using ROW_NUMBER with a partition over id and name.

A: using max()
select id, name, t2.period, difference from tableA t1
inner join
 (select id, max(period) as period from tableA
 group by id) t2 on t2.id = t1.id

using distinct()
select distinct id, name, t2.period, difference from tableA

A: it seems you need just max()
select id,name,max(period),max(difference)
from table group by id,name

Though i have not found difference=4 in your sample data but you used that on output,so i guessed its your typo

A: Use max()
select id, name, max(period), difference from tablename
group by id, name,difference

A: You can try my code:
SELECT
  id, name, max(period), difference
FROM
  data_table
group by id, name,difference
order by name

This is a demo link http://sqlfiddle.com/#!17/9ab8d/2


text:
Q: Why am i getting parsing errors in react-intl V3.2.2? I updated my app from reactinlt 2.x to 3.2.2. Now I get the following error for each formatted message:
index.js:1437 [React Intl] Error formatting message: "titleBar.login" for locale: "de", using default message as fallback.
TypeError: A message must be provided as a String or AST.
Same for the default message:
Error formatting the default message for: "titleBar.login"
TypeError: A message must be provided as a String or AST.
And finally:
[React Intl] Cannot format message: "titleBar.login", using message source as fallback
However the GUI renders correctly and shows the German translation ("de"). But I get swamped in the Chrome console with error messages. What's wrong?
  const userInfo = useContext(UserContext);  // using hooks

  return (
    <UncontrolledDropdown className={styles.user}>
      <DropdownToggle>
        ...
      </DropdownToggle>
      <DropdownMenu>
       ...

        {!userInfo.isLoggedIn && (
          <DropdownItem>
            <div onClick={() => userInfo.login()}>
              <FormattedMessage {...msgs.login} />  // this has id=titleBar.login
            </div>
          </DropdownItem>
        )}
      </DropdownMenu>
    </UncontrolledDropdown>
  );
};

Any idea how I can get rid of those error messages?
BTW: The error is thrown in format message. The message is parsed as a string (no placeholders etc). Then it checks if the AST is an array and throws because it is only one node...
Here's the code section:
 if (typeof message === 'string') {
      this.message = message;

      if (!IntlMessageFormat.__parse) {
        throw new TypeError('IntlMessageFormat.__parse must be set to process `message` of type `string`');
      } // Parse string messages into an AST.

      this.ast = IntlMessageFormat.__parse(message);
    } else {
      this.ast = message;
    }

    if (!Array.isArray(this.ast)) {
      throw new TypeError('A message must be provided as a String or AST.');
    }

A: You should check your translations file. It seems that the value of titleBar.login is not a string, but an object

A: Ultimately, it was a version mismatch between the client and server tooling. Meanwhile we updated to the latest version of all libs and ist working again.


text:
Q: AttributeError: type object 'Employee' has no attribute 'empCount' since I am new to python programming language and OOP concept.
I am exercising class's and object code. while I got this error

AttributeError: type object 'Employee' has no attribute 'empCount'"

class Employee:

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount = Employee.empCount + 1

    def DisplayCount(self):
        print("Total Employee %d" % Employee.empcount)

    def DisplayEmployee(self):
        print("Name:",self.name," Salary:",self.salary)

code
emp1 = Employee("Zara", 1000)
emp2 = Employee("Brad", 1500)

emp1.DisplayEmployee()
emp2.DisplayEmployee()
print("Total Employee %d" % Employee.empCount)`emp1 = Employee("Zara", 1000)
emp2 = Employee("Brad", 1500)

emp1.DisplayEmployee()
emp2.DisplayEmployee()
print("Total Employee %d" % Employee.empCount)`

Can anyone tell me what is wrong in here? with explanation.

A: The issue is Employee.empCount is not yet defined at the class level yet and you are trying to access it. If your intention is to have a tap employee count based on instances created, then a class variable like this would do the trick. However it is usually not advised to share variables across instances this way rather advised to find a reliable alternative.

Note class Employee is inheriting from object this is called new style classes in Python.

In [29]:
class Employee(object):
    empCount = 0

    def __new__(cls, *args, **kwargs):
        cls.empCount += 1
        return super(Employee, cls).__new__(cls, *args, **kwargs)

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def DisplayCount(self):
        print("Total Employee %d" % Employee.empcount)

    def DisplayEmployee(self):
        print("Name:",self.name," Salary:",self.salary)
## -- End pasted text --

In [30]: emp1 = Employee("Zara", 1000);emp2 = Employee("Brad", 1500)

In [31]: emp1.empCount
Out[31]: 2

In [32]: emp3 = Employee("Tes", 100)

In [33]: emp1.empCount
Out[33]: 3

A: In your __init__, you are trying to access a class variable that is non existent:
Employee.empCount = Employee.empCount + 1
#                   ^^^^^^^^^^^^^^^^^ what's the initial value?

You need to define the variable at the class level in order to make subsequent updates to the variable, and python case sensitive so you need to fix your next error in the DisplayCount:
class Employee:
     empCount = 0
     ...

    def DisplayCount(self):
         print("Total Employee %d" % Employee.empCount)
         #                                     ^^^^^

A: You need to set the 'Employee.empCount' variable.
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount = 0
Employee.empCount = Employee.empCount + 1

That should work.

A: Your problem is that you are trying to count the number of employees in the class of an employee. It is like each employee knows the total count...
You must have to have a kind of class that count the employees each time an employee is created or the simpliest way is to store employees in a list then look at the size of your list.
A solution may be:
class Employee:

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def DisplayEmployee(self):
        print("Name:",self.name," Salary:",self.salary)

code:
employees = []
employees.append(Employee("Zara", 1000))
employees.append(Employee("Brad", 1500))

[e.DisplayEmployee() for e in employees]
print("Total Employee %d" % len(employees))

Resulting in:
Name: Zara  Salary: 1000
Name: Brad  Salary: 1500
Total Employee 2

Hope it is clear enough to help you.


text:
Q: Block cyrilic characters in nginx Recently I see a lot off spam messages on a contact form on our website, I was wondering if their was an easy way to block cyrilic (Russian) characters in post data. If such a character is found, it can just cancel the request with a 400 error code.
So something like a reqular expression on the post data, looking for specific byte values (for those unicode chars).
I already added blocking based on a recent GeoIP database, but that didn't solve the issue.


text:
Q: Why is this not a 2-dimensional array? I'm very confused by the following code:
>> x = [0.4+randn(100,1).*0.15; 1+ randn(200,1).*0.25];

>> size(x)

ans =
    300    1

I thought semicolons were used to indicate a separate row in the matrix.  Shouldn't this raise an error given that the two vectors are not of the same length?
What am I missing?

A: As you create 2 arrays and concatenate those:
randn(100,1) creates a 100 row, 1 column array
randn(200,1) creates a 200 row, 1 column array
The semicolon in your expression says: 'Put these underneath each other'
If you remove the semicolon (;) it will be a matrix (and probably give an error). As you then put 2 column vectors next to each other.


text:
Q: ETL tool to access snowflake internal stage files? I'm new to snowflake even for data engineering. for me, I want to perform extract and transformation of snowflake internal staged files. like below,

name
size
md5
last_modified

sales/auto_ingest/3.csv.gz
3915392
b8b6286365965360a2b2ef0b45
Thu, 25 Aug 2022 10:29:43 GMT

sales/auto_ingest/4.csv.gz
3915392
5719ac992cb5c5718c24d13c0
Thu, 25 Aug 2022 10:30:03 GMT

and perform extract and transform using any suggested tool and load it into snowflake table. let me know is it possible? or suggest me any tools for accessing snowflake staged files.

A: You cannot access Snowflake staged files directly, you will need to use either a connector/driver or an application like SnowSQL.
To upload files to Snowflake stage you can use the PUT command and to download them from the stage you can use the GET command. Both commands can be used from SnowSQL.


text:
Q: Check pending changes before doing a another task on a ASP.NET Ajax page I'm developing an ASP.NET web application with AJAX.
I have a page where the user can edit some information: it has a list of item, the user select one item, click on Edit button and then edit item's name and item's description on two textboxes.
If user click on another item since he doesn't save his changes, he can click on edit button to edit this new item.
I want to check if there is some data on textboxes and ask to the user if he wants to lose their changes before loading the data of the new item.
How can I do that?
Thank you.

A: There are four ways that I can think of to handle this:

*

*Always save the changes (auto save). We've eliminated almost all save buttons from forms and just always auto save the data based on user feedback.

*Always prompt to save changes; i.e. assume that if the form is in edit mode then there are changes.

*Hook every control's change event and toggle a boolean if any control fires its change event; prompt the user if it's true.

*The hardest (and arguably best) method is to actually compare the previous values to the current values and only prompt if they're different.

The method you select depends on the application and user expectations.