text:
Q: Bringing drone maps into QGIS, CRS and scale bar I'm looking for a guide to bringing files into QGIS so that the scale bar in print composer reads accurately. At the moment the files I'm bringing in are Geotiff and DEM. I know this has something to do with CRS. They are in EPSG:4326,WGS84.

A: The Coordinate Reference System you use, also known as CRS, is probably not the correct one to measure distances on. If you want to change this correctly, you might need to know a little bit more background information.
Some well known systems are:

*

*WGS 84 (EPSG:4326), a geodetic (sphere) system, measures in degrees north and east. Coordinates from GPS are in this system.

*WGS 84 / Pseudo-Mercator (EPSG:3857), a projected (flat) system, measures in meters easting and northing (X,Y).

Measuring distances in WGS 84 will give results in degrees, which are not great to work with.
The Pseudo-Mercator projection is created to visualize our not so flat world on a flat map using square tiles. Google Maps, Open Streetmap, etc. As a flat piece of paper doesn't fit around a football without folding it, you can imagine this is not the correct system to measure distances on:

Uses spherical development of ellipsoidal coordinates. Relative to WGS
  84 / World Mercator (CRS code 3395) errors of 0.7 percent in scale and
  differences in northing of up to 43km in the map (equivalent to 21km
  on the ground) may arise.

To overcome this problem there are a lot of projected systems which cover smaller pieces of the world.
So, if you know the CRS your data is in and what projected CRS the data is on, you can reproject or transform the data to the projected CRS and measure more correct distances.

*

*Find the current CRS the dataset is on.

In QGIS, right click the layer, hit properties. Check the tab General.

That was easy. Looks like Pseudo-Mercator to me.

*Find a proper projected CRS.

In a browser, hit http://epsg.io and hit the name of the country the data is in. In my case, Netherlands. Hit Projected to filter only projected systems, choose one of your liking, in this example Amersfoort / RD New (EPSG:28992).
Important: Double check if your data fits in the extends of the system. Measuring outside the system technically works but the results will be off without warnings.

*Change the Project CRS to the projected system.

In QGIS, click Project, Project Properties... tab CRS. Search (use the EPSG code) and select the correct CRS.

If you have layers on other CRS's, mark "Enable 'on the fly' CRS transformation (OTF)". This way the data will be reprojected to the project CRS while panning and zooming. This will hurt your performance. Reprojecting the data (Processing Toolbox, Reproject Layer) will fix this.


text:
Q: Extending a class with many implementation that each have main methods in Scala imagine that I have a Tokenizer class with a single abstract method.
trait Tokenizer {
    def tokenize(sentence: String): List[String]
}

I will implement a number of tokenizers that provide an implementation.  I would like for each of these Tokenizer to have a main method.  My first thought was to write code like this:
abstract class TokenizerMain(tokenizer: Tokenizer) {
    def main(args: Array[String]) = println(tokenizer.tokenize(args(0)).mkString(" "))
}

class TokenizerOne(val model: String = "foo") extends Tokenizer {
    def tokenize(sentence: String) = List("asdf")
}

object TokenizerOne extends TokenizerMain(new TokenizerOne) {
}

However, I get the error "super constructor cannot be passed a self reference unless parameter is declared by-name".  I can rename object TokenizerOne to object TokenizerOneMain but I would like to keep it the same as the class.  Is there a better way to do this?
UPDATE: this problem seems to be caused by the implicit constructor parameter model of TokenizerOne.

A: Here's a reduced code sample that gives the same error,
class Foo(t: Any)
class Bar(x: String = "bar")
object Bar extends Foo(new Bar())
  //                   ^
  // Error, super constructor cannot be passed a self reference unless
  // parameter is declared by-name

The bytecode helps explain what's going on. From the REPL,
scala> class Foo(t: Any)

scala> class Bar(x: String = "bar")

scala> :javap -v Bar

Compiled from "<console>"
public class Bar extends java.lang.Object implements scala.ScalaObject
...
{
public Bar(java.lang.String);
...

We see that the class Bar has only a single constructor, which takes a String parameter. But we know that Bar also has a constructor that uses the default value x = "bar", where does that come from?
scala> :javap -v Bar$
...
public java.lang.String init$default$1();
  Code:
   Stack=1, Locals=1, Args_size=1
   0:   ldc #16; //String bar
   2:   areturn
  LineNumberTable:
   line 7: 0

Ahh, that's defined in the companion object, which belongs to class Bar$ (only the Scala compiler is supposed to know about that).
So what seems to be happening is that in extends Foo(new Bar()) you're trying to access a method in object Bar during the initialization of Bar's super-class (which is before the object Bar is actually constructed).
If this is not a bug in the Scala compiler, then it's a confusing error message! I can't say which. I filed issue SI-5000 in the bug tracker.
As a workaround, you can avoid the default value: object Bar extends Foo(new Bar("bar")).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compare two alphanumeric variables mixed with special expression in shell script I want to compare two alphanumeric strings and below is the bash expression I think should do the job. But I'm getting blank result. Please advise.
:~$ echo $tempnow $threshold
+60.0°C +80.0°C

:~$ res=`echo "$tempnow $threshold" | awk '{ if($1 > $2) print "Exceeds"; else echo "Normal" }'`
:~$ echo $res

:~$

A: There is no echo in awk.
You can use:
echo '+90.0°C +80.0°C' | awk '{ print ($1+0 > $2+0 ? "Exceeds" : "Normal") }'
Exceeds

echo '+60.0°C +80.0°C' | awk '{ print ($1+0 > $2+0 ? "Exceeds" : "Normal") }'
Normal

Also note use of +0 to convert fields into numeric values.

A: You have written echo instead of print in your awk script.
This will be interpreted as the name of a function or variable, which doesn't exist, then it will be coerced to an empty string and concatenated with the string "Normal". The result will be discarded.
I would recommend writing your script as follows:
res=$(awk '{ print ($1 > $2 ? "Exceeds" : "Normal") }' <<<"$tempnow $threshold")

This uses <<< to pass the string over standard input to awk. The result of the ternary operator is printed and stored in the variable $res.
Bear in mind that you are currently comparing strings, so you will run into problems in situations such as this:
$ tempnow=+9.0°C
$ threshold=+80.0°C
$ awk '{ print ($1 > $2 ? "Exceeds" : "Normal") }' <<<"$tempnow $threshold"
Exceeds

A: try below :-
res=`echo "$tempnow $threshold" | awk '{ if($1 > $2) print "Exceeds"; else print "Normal" }'`


text:
Q: DISTINCT for two out of three columns in with statement Trying to get my query to group but it isn't liking my group by so I have to come up with something else. How do I get one row for every unique Person_iD and ah_person_id combo, doesn't matter which row.
WITH w_accnt AS
             (SELECT DISTINCT account.id AS id,
                              account.group_code AS account_number,
                              account.attribute_1 AS group_number,
                              account.source_id AS ah_person_id,
                              weekly.person_id AS person_id
                FROM MyAccountTable account
               INNER JOIN MyWeeklyTable weekly
                  ON weekly.account_id = account.id

                 ),

Example Table
Person   AH_PERSON   ACCOUNT_num
A         1           22
B         2           23
B         2           24
C         3           25
C         4           26

What I want back Expected Results
Person   AH_PERSON   ACCOUNT_num
A         1           22
B         2           23
C         3           25
C         4           26

Thanks

A: Use aggregation:
SELECT MIN(a.id) AS id, MIN(a.group_code) AS account_number,
       MIN(a.attribute_1) AS group_number,
       a.source_id AS ah_person_id,
       w.person_id AS person_id
FROM MyAccountTable account a JOIN
     MyWeeklyTable w
     ON w.account_id = a.id
GROUP BY a.source_id, w.person_id

Or perhaps window functions:
SELECT aw.*
FROM (SELECT a.id, a.group_code AS account_number, a.attribute_1 AS group_number,
             a.source_id AS ah_person_id, w.person_id AS person_id,
             ROW_NUMBER() OVER (PARTITION BY a.source_id, w.person_id ORDER BY a.id DESC) as seqnum
      FROM MyAccountTable account a JOIN
           MyWeeklyTable w
           ON w.account_id = a.id
      GROUP BY a.source_id
     ) aw
WHERE seqnum = 1;

This gives you more control over which values are returned and ensures that they are all from the same row.


text:
Q: Solving an optimization problem where the decision variable is an unknown function to be solved for Apologies if this question is not well defined or if it lacks in mathematical understanding - I am still trying to improve my understanding and application of mathematics. Feel free to point me to relevant literature or books if you feel it is necessary.
My question is the following.
Suppose I have a transformation defined as follows:
$\phi : x \rightarrow y $ where $x \in \mathbb{R}^n$, $y \in \mathbb{R}^m$ and $m>n$
Also suppose that we know the time derivative of $x$ i.e. $\dot{x}$ then we can say by the chain rule:
$\dot{y} = J_{x}(y) \dot{x}$ where $J_{x}(y)$ is the Jacobian of y with respect to x. (Apologies for any abuse of notation)
Then I want my transformation to satisfy the following property:
$\dot{y} = J_{x}(y) \dot{x} = \lambda y$ where $\lambda \in \mathbb{R}^{m \times m}$ is an unknown matrix of coefficients relating $\dot{y}$ to $y$.
In effect, I have a system of $m$ equations with $m$ unknown transformations as well as $m\cdot m$ unknown coefficients. We have an underdetermined system of equations. My approach was to try and reformulate this as an optimisation problem:
$\min_{\phi,\lambda}$ $ || J_{x}(y) \dot{x} - \lambda y|| $
However, I don't know if this approach is correct and, if it is, how such a problem could be solved, in particular, do methods exist to solve optimisation problems where the decision variable is itself a function and the goal is to find some function which minimises the objective function? Again apologies if this question is not well defined or explained correctly or even mathematically "correct". Please feel free to provide any pointers. Thanks


text:
Q: SQL Insertion without duplication Is there a specific command for SQL Server in order to INSERT a lot of rows with the condition : if a row already exists in database doesn't duplicate it during insertion ?
Edited
In a sqlbulkcopy, I'd like to avoid exception because a row is already in the table ?

A: You can use the MERGE command for this.  Example Usage.
CREATE TABLE #A(
 [id] [int] NOT NULL PRIMARY KEY CLUSTERED,
 [C] [varchar](200) NOT NULL)

    MERGE #A AS target
    USING (SELECT 3, 'C') AS source (id, C)
    ON (target.id = source.id)
    /*Uncomment for Upsert Semantics
       WHEN MATCHED THEN
        UPDATE SET C = source.C */
    WHEN NOT MATCHED THEN
        INSERT (id, C)
        VALUES (source.id, source.C);

Edit Though you say in your edit this is for a bulk copy? You could also investigate the "Ignore Duplicate Keys" option on your index.

A: How to do it in T-SQL is discussed here (article is a bit old though)


text:
Q: How to return indented XML using Spring mvc:annotation-driven and ResponseBody I've implemented a simple controller that returns a converted XML object using JAXB and @ResponseBody annotation.
My problem is I'm having a hard time to configure the default converter created by mvc:annotation-driven, and I needed to configure it to render my XML indented. I know I can declare my view resolvers, but I wanted to keep using annotation-driven.
I've searched and found that I could configure mvc:annotation-driven through the usage of mvc:message-converters, but I'm having a lot of trouble finding good documentation to configure Jaxb2RootElementHttpMessageConverter.

A: <mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
      <property name="marshaller" ref="jaxb2Marshaller"></property>
      <property name="unmarshaller" ref="jaxb2Marshaller"></property>
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
   <property name="contextPaths">
     <list>
       <value>put your xml classes path here</value>
     </list>
   </property>
   <property name="marshallerProperties">
       <map>
            <entry key="jaxb.formatted.output">
                <value type="java.lang.Boolean">true</value>
            </entry>
            <entry key="jaxb.encoding" value="UTF-8" />
       </map>
   </property>
</bean>


text:
Q: Force Java Android Socket to Send Data Immediately As a hobby project, I'm writing an android voip client. When writing voice data to the socket (Vars.mediaSocket), many times, the data isn't immediately sent out over the wifi but just stalls and then all at once it will send 20 seconds worth of voice. Then it will stall again and wait for 30 seconds and then send 30 seconds of voice. The wait is not consistent but after a while it will continuously send voice data immediately. I've tried everything from using DataOutputStream to setting the socket output buffer size, setting the sendbuffer size huge, small, and lastly, buffering the voice data from its 32 byte chunks to anything from 128bytes to 32kb.
        Utils.logcat(Const.LOGD, encTag, "MediaCodec encoder thread has started");
        isEncoding = true;
        byte[] amrbuffer = new byte[32];
        short[] wavbuffer = new short[160];
        int outputCounter = 0;

        //setup the wave audio recorder. since it is released and restarted, it needs to be setup here and not onCreate
        wavRecorder = null; //remove pointer to the old recorder for safety
        wavRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLESWAV, AudioFormat.CHANNEL_IN_MONO, FORMAT, 160);
        wavRecorder.startRecording();
        AmrEncoder.init(0);

        while(!micMute)
        {
            int totalRead = 0, dataRead;
            while(totalRead < 160)
            {//although unlikely to be necessary, buffer the mic input
                dataRead = wavRecorder.read(wavbuffer, totalRead, 160 - totalRead);
                totalRead = totalRead + dataRead;
            }
            int encodeLength = AmrEncoder.encode(AmrEncoder.Mode.MR122.ordinal(), wavbuffer, amrbuffer);

            try
            {
                Vars.mediaSocket.getOutputStream().write(amrbuffer);
                Vars.mediaSocket.getOutputStream().flush();
            }
            catch (IOException i)
            {
                Utils.logcat(Const.LOGE, encTag, "Cannot send amr out the media socket");
                Utils.dumpException(tag, i);
            }

Is there something I'm missing? To simulate a second cell phone, I have another client which just simply reads the voice data, throws it away, and reads again in a loop. I can confirm in the simulated second cell phone when the real cell phone stops sending voice, the simulated one's socket.read hangs until the real one starts sending voice again.
I'm really hoping not to have to write a jni for the socket as I don't know anything about that and was hoping I could write the app as a standard java app.
CASE CLOSED: turned out to be a server side bug but the simplifying back to basics suggestions is still a good idea.

A: You are adding most of the latency yourself by reading large amounts of data before writing any of it. You should just use the standard Java copy loop:
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

You need to adapt this to incorporate your codec step. Note that you don't need a buffer the size of the entire input. You can tune its size to suit yourself but 8192 is a good starting point. You can increase it to say 32k but don't decrease it. If your codec needs the data in fixed-size chunks, use a buffer of that size and DataInputStream.readFully(). But the larger the buffer the more the latency.
EDIT Specific issues with your code:
byte[] amrbuffer = new byte[AMRBUFFERSIZE];
byte[] outputbuffer = new byte [outputBufferSize];

Remove (see below).
short[] wavbuffer = new short[WAVBUFFERSIZE];
int outputCounter = 0;

Remove outputCounter.
        //setup the wave audio recorder. since it is released and restarted, it needs to be setup here and not onCreate
        wavRecorder = null; //remove pointer to the old recorder for safety

Pointless. Remove.
        wavRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLESWAV, AudioFormat.CHANNEL_IN_MONO, FORMAT, WAVBUFFERSIZE);
        wavRecorder.startRecording();
        AmrEncoder.init(0);

OK.
        try
        {
            Vars.mediaSocket.setSendBufferSize(outputBufferSize);
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }

Pointless. Remove. The socket send buffer should be as large as possible. Unless you know that its default size is < outputBufferSize there is no benefit to this. In any case we are getting rid of outputBuffer altogether.
        while(!micMute)
        {
            int totalRead = 0, dataRead;
            while(totalRead < WAVBUFFERSIZE)
            {//although unlikely to be necessary, buffer the mic input
                dataRead = wavRecorder.read(wavbuffer, totalRead, WAVBUFFERSIZE - totalRead);
                totalRead = totalRead + dataRead;
            }
            int encodeLength = AmrEncoder.encode(AmrEncoder.Mode.MR122.ordinal(), wavbuffer, amrbuffer);

OK.
            if(outputCounter == outputBufferSize)
            {
                Utils.logcat(Const.LOGD, encTag, "Sending output buffer");
                try
                {
                    Vars.mediaSocket.getOutputStream().write(outputbuffer);
                    Vars.mediaSocket.getOutputStream().flush();
                }
                catch (IOException i)
                {
                    Utils.logcat(Const.LOGE, encTag, "Cannot send amr out the media socket");
                    Utils.dumpException(tag, i);
                }
                outputCounter = 0;
            }
            System.arraycopy(amrbuffer, 0, outputbuffer, outputCounter, encodeLength);
            outputCounter = outputCounter + encodeLength;
            Utils.logcat(Const.LOGD, encTag, "Output buffer fill: " + outputCounter);

Remove all the above and substitute
        Vars.mediaSocket.getOutputStream().write(amrbuffer, 0, encodeLength);

This also means you can get rid of 'outputBuffer' as promised.
NB Don't flush inside loops. As a matter of fact flushing a socket output stream does nothing, but the general principle still holds.


text:
Q: CONCEPT OF MOV AX,CS and MOV DS,AX Can someone please explain the functions of these three instructions?
  ORG 1000H
  MOV AX,CS
  MOV DS,AX

I know what the code, data, and extra segments are in theory, but:

*

*How they are implemented in this program?

*Why is the entire segment moved into another? (MOV AX,CS and MOV DS,AX)
What do these two instructions actually do?
I can understand the meaning of every other instruction in this code, except for the highlighted 3 instructions.
(The program works fine. It accepts input till 0 is hit -- there's a mov ah,01h and an int 21h, then it compares al to '0' and if al is '0', it jumps to last, otherwise it jumps into back.)
    ASSUME CS:CODE
    CODE SEGMENT
    ORG 1000H
    MOV AX,CS
    MOV DS,AX
BACK:
    MOV AH,01H
    INT 21H
    CMP AL,'0'
    JZ LAST
    JMP BACK
LAST:
    MOV AX,4C00H
    INT 21H
    CODE ENDS

    END

(Editor's note: .com programs are loaded at offset 100h, with all segment registers set equal to each other.  org 1000h is likely a typo for org 100h because this looks like a .com program.  This program doesn't break because it doesn't use any absolute addresses, only relative jumps.)

A: ORG 1000H tells the assembler that the code that follows should be placed at offset 1000H in the code image.
The other two instructions copy CS to DS. It is not copying the segment itself, just updating the pointer to the data segment. For a small program (<64K), static data (string literals in the source, indirect jump tables) may be placed together in the same segment with the code. The segment base pointer needs to be loaded in DS before accessing the static data. The loader (the part of the OS that reads the program from disk to memory and starts it running) has to set CS so that it can run the program, but may not set DS, so the program copies CS to DS when it starts.
The two instruction sequence is needed because "MOV DS, CS" is not a legal 8086 instruction.

A: To really explain the concept, we have to back up to the basic idea of segments, and how the x86 uses them (in real mode).
The 8086 has 20-bit addressing, but only 16-bit registers. To generate 20-bit addresses, it combines a segment with an offset. The segment has to be in a segment register (CS, DS, ES, or SS). You then generate an offset (as an immediate value, or the contents of another register or two.
So, to generate an address, a 16-bit segment register is shifted left four bits, and then a 16-bit offset in some other register is added to that, and the combined total is actually used as the address. Most instructions have a default segment attached to them -- push, pop and anything relative to bp will use ss. Jumps and such use cs. Some of the string instructions es (e.g., scans) and some use use two segments -- for example, movsd copies data from [ds:si] to [es:di]. Most other instructions use ds. You can also use segment overrides to explicitly specify an address like es:bx.
In any case, before you can make any meaningful use of a segment register, you first have to load it with the (top 16 bits of) the address of the data you care about. A typical "small model" program will start with something like:
mov ax, @Data
mov ds, ax

In tiny model, you use the same segment for the data and the code. To make sure it's referring to the correct segment, you want to get the 16 bits from CS and copy it to DS. As a number of others have mentioned, there's no instruction to move CS directly to DS. The question mentions one possibility; another common one is:
push cs
pop ds

A: you can't do
MOV DS, CS

it's an invalid operation (masm 32: error A2070: invalid instruction operands).
MOV AX, CS
MOV DS, AX

These 2 instruction perform the same as mov ds, cs (which is invalid). This way the assembler is happy and doesn't complain. But I can't tell you why the programmer wants the data segment to be the same as the code segment


text:
Q: How to pass a variable in form using GET with spaces in PHP+HTML+SQL I have a form where I display a select item and two other invisible inputs with some variable values that I need to pass to the same page at the press of the "Action" button. But I'm having the problem that those variables are city names like "New York", so there is a space inside the name, and at the moment of passing the variable only the "New" gets passed; nothing after the space goes with it. I have read that there shouldn't be any spaces in those variables, so how should I do this?
Here is my sample code:
// at the beginning of the code I get this variables pass from other pages

$pais=$_GET['pais'];
$name=$_GET['nombre'];

// this is how I query my table to populate my select item

$SN=mysql_real_escape_string($name);
$SP=mysql_real_escape_string($pais);
$estadoquery = "SELECT * FROM `".$SP."` ORDER BY Estado ASC";
$estadoresult = mysql_query($estadoquery);

// this is how I make my form

<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type="HIDDEN"  name=nombre  value="<? echo $SN ?>">
<input type="HIDDEN"  name=pais  value="<? echo $SP ?>">

      <select name=estado  id="estado" style="font-size:24px">
       <option value="">Todos</option>
        <?
        while($rowp = mysql_fetch_array($estadoresult)) {
               $estado = $rowp['Estado'];
               $Se=mysql_real_escape_string($estado);
          ?>
        <option value=<?php echo $Se ?>>
        <?php echo $Se ?></option>
        <? } ?>
      </select>

  <input type="SUBMIT"  name="ACTION" value="IR">
	</form>

// and this is what the button action does

 if(@$_POST['ACTION']=='IR')
{
$pais = $_POST['pais'];
$name = $_POST['nombre'];
$estado = $_POST['estado'];
  $pais = mysql_escape_string($pais);
  $name = mysql_escape_string($name);
  $estado = mysql_escape_string($estado);
// this next echos are just to check my variables.
echo $pais;
echo $name;
echo $estado; // so here I can tell that this variable is not complete

}
And I have read that variables cannot be passed with spaces, why does my $pais variable "United States" gets passed with the space in between correctly?
Can someone tell me how to achieve this or how to transform my <option value=<?php echo $Se ?>> so it can pass the space?

A: use urlencode(). it will transform the spaces into %20 which will be transfered successfully.. you can decode it using urldecode().
<option value=<?php echo urlencode($Se); ?>>

A: Per my comment above:
The problem is that there are not quotes around the option values. Change it like so:
<option value="<?php echo $Se ?>">

and you'll be good to go.

A: I believe this has to do with URL Encoding. A URL can't have spaces in it. However, there are special characters that can be used to represent a space in a url. The GET Method uses the URL.
I believe this may help; http://php.net/manual/en/function.urlencode.php

A: Use the function urlencode on the variables you want to pass in get. See http://php.net/manual/en/function.urlencode.php for a reference.
<input type="HIDDEN"  name=pais  value="<? echo urlencode($SP); ?>">

Then when you want to use the variable again you can use urldecode to decode it. http://php.net/manual/en/function.urldecode.php
After your edit:
<option value=<?php echo $Se ?>>

Should be:
<option value="<?php echo urlencode($Se); ?>">

With the qoutes and the urlencode.

A: <option value="<?php echo htmlspecialchars($Se); ?>">

A: About Gung Foo response. urlencode() will not transform white spaces to %20 but to + character.
Use rawurlencode() to transform white spaces to %20.
Also you may want to read this: https://stackoverflow.com/a/2678602/4481831

A: According to HTML standard you should use " (double quotes) around values, but also - you must properly encode them, so your code must look like this:
<option value="<?php echo htmlspecialchars($rowp['Estado']); ?>">

Note - that mysql_real_escape_string is NOT used, as it escapes different symbols, neither htmlspecialchars


text:
Q: How to remove "isCustom" key value pair from following JSON For example I receive a JSON response from postman and store it in a variable. How can I remove a specific key from this response?
{"editdata":[{"A11":"T55","ID":"4","FVAModifiedDateLongValues":"3:1334835002030","ModifiedDateLongValue":1614614214967,"F033":[{"Name":"p3","Type":"String","Values":null,"Description":"p3","isCustom":false},{"Name":"p3","Type":"String","Values":null,"Description":"p3","isCustom":false}],"flag":"edit"]}

A: You could just iterate over the array with the objects you want to delete, and delete the field from each object using the delete operator.

let myObject = {
    "editdata": [{
        "A11": "T55",
        "ID": "4",
        "FVAModifiedDateLongValues": "3:1334835002030",
        "ModifiedDateLongValue": 1614614214967,
        "F033": [{
          "Name": "p3",
          "Type": "String",
          "Values": null,
          "Description": "p3",
          "isCustom": false
        }, {
          "Name": "p3",
          "Type": "String",
          "Values": null,
          "Description": "p3",
          "isCustom": false
        }],
        "flag": "edit"}]
    };
// if you want to delete it for all objects in the editdata array, you could do a nested forEach.
myObject.editdata[0].F033.forEach(obj => delete obj.isCustom);
console.log(myObject);


text:
Q: React useState, adding new object to array of objects This a doubt I have regarding the best practice when pushing a new object in an array of objects via setState.
In the below implementation the 'prevObjects' are being spread into the new array to set the state. This passes the references of the old objects, but does not mutate the array or the objects. Hence does that mean the below implementation is good? It is working, but could it be problematic in some edge cases?
const [objArray, setObjArray] = useState([{ name: John }, { name: Jane }]);

setObjArray((prevObjects) => [...prevObjects, newObject])


text:
Q: Row-Level Security Predicate Filter On Oracle 19c.
We have users whose accounts are provisioned by specifying a comma separated list of department_code values.  Each of the department_code values is a string of five alpha-numeric [A-Z0-9] characters.  This comma separated value list of five character department_codes is what we call the user's security_string.  We use this security_string to limit which rows the user may retrieve from a table, Restricted, by applying the following predicate.
select *
from Restricted R
where :security_string like '%' || R.department_code || '%';

A given department_code can be in Restricted many times and a given user can have many department_codes in their comma-separated value :security_string.
This predicate approach to applying row-level security is inefficient.  No index can be used and it requires a full table scan on Restricted.
In alternative is to use dynamic SQL to do something like as follows.
execute immediate 'select *
from Restricted R
where R.department_code in(' || udf_quoted_values(:security_string) || ')';

Where udf_quoted_values is a user-defined function (UDF) that wraps in single quotes each department_code value within the :security_string.
However, this alternative approach also seems unsatisfactory as it requires a UDF, dynamic sql, and a full table scan is still likely.
I've considered bit-masking, but the number of bits needed is large 60 million (=36^5) and it would still require a UDF, dynamic sql, and a full table scan (function based index doesn't seem to be a candidate here).  Also, bit-masking doesn't make much sense here as there is no nesting/hierarchy of department_codes.
execute immediate 'select *
from Restricted R
where BITAND(R.department_code_encoded,' || udf_encoded_number(:security_string) || ') > 0';

Where Restricted.department_code_encoded is a numeric encoded value of Restricted.department_code and udf_encoded_number is a user-defined function (UDF) that returns a number encoding the department_codes in the :security_string.
I've considered creating a separate table of just department codes, Department, and joining that to the Restricted table.
select *
from Restricted R
join Department D
on R.deparment_code = D.department_code
where :security_string like '%' || D.department_code || '%';

We still have the same problems as before, but now it is on the smaller (table cardinality) Department table (Department.department_code is unique where as Restricted.department_code is not unique).  This provides for a smaller full table scan on Department than on Restricted, but now we have a join.
It is possible for us to change security_string or add additional user specific security values when the account is provisioned.  We can also change the Oracle objects and queries.  Note, the department_codes are not static, but don't change all that regularly either.
Any recommendations?  Thank you in advance.

A: Why not converting the string to a table, like suggested here, and then do a join.


text:
Q: ddd debugging c project, where to put -g tag when compile? I want to debug  c source code by using  ddd debugger. instruction say when compile it should compiled with -g tag.
here is how I compile this project.
aclocal , automake --add-missing, autoreconf, ./configure, make.
so where should I put -g tag, then how can I invoke ddd to debugging?
usually after compile, I run it by
./slim.exe filename
could anyone has experience in this?
Thanks in advance

A: If you invoke ./configure --help, you'll see following options at the end of the help:
Some influential environment variables:
CC          C compiler command
CFLAGS      C compiler flags

Just specify CFLAGS=-g3 and gcc will be called with the flags you specify here.


text:
Q: How To Upload Xml data into the skydrive server? When the user enters the registration data it will be created and stored in xml file whenever a new user register  then it has to append the created xml file but my problem is that how to upload that xml data file in skydrive rather than db or webservices by which it has to be update when change is done and how can we read the data present in the skydrive xml file.
And I have one doubt regarding this

*

*When the app opened for  the first time i didnot want to give the username and password
By default it has to be opened.Is it possible ?

Please provide me some sample example code it will be very helpful.

A: you can also use share option here : look this :
http://sdrv.ms/16fwwjq


text:
Q: Encoding problems during INSERT with Sqlite3 C++ and VisualStudio2010 I'm developing a small wrapper for a project using sqlite3 with the C++ API and VisualStudio 2010. As far as it goes and checking with a tool like SQLiteDataBaseBrowser, the main problem is that the information I try to insert in the table appears corrupted / doesn't appear at all. The table appears to be correctly created with UTF8 encoding.
I tried using the Character Set configuration values in VS as "Use Multy-Byte Character set" and also tried with "Use Unicode Character set" but got no change in the result. Both gave me the same problem with the corrupted data. I use the typical std::strings converted to legacy c char* and as I've seen in several examples that it should work properly with sqlite3_bind_text(...) functions that the API provides.
    sqlite3_bind_int(stmt, 1, newShop.GetId());
    sqlite3_bind_text(stmt, 2, newShop.GetName().c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, newShop.GetLocation().c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, newShop.GetPicturePath().c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 5, newShop.GetRegisters().c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 6, newShop.GetMixes().c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 7, newShop.GetAllowedUsers().c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 8, newShop.IsAvailable() == true?1:0);

newShop is an instance of a class which contains the information in std::strings and int. I have to say that the bindings with int type, work perfectly and without problem, but the others look totally messed up. when the strings are hardcoded, they also look ok until I try to insert special characters such as "áàä" and such.
The table is created with the statement:
char *szSQL = "CREATE TABLE IF NOT EXISTS SHOPS (ID INTEGER PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, LOCATION TEXT, PICTUREPATH TEXT, REGISTERS TEXT, MIXES TEXT, USERS TEXT, AVAILABLE INTEGER NOT NULL);";
int rc = sqlite3_exec(db, szSQL, NULL, 0, NULL);

This is how it looks when I insert the data using the code snippet above:

sending it from a WINUNIT test that looks like:
Shop shOne = Shop(1234, "Its about nothing", "Manhattan", "seinfeld.jpg", "1111,2222,3333", "1000x1,2000x7", "10,11,12", true);
Shop shTwo = Shop(4321, "Louie", "Manhattan", "", "1111,5555", "50000x1,10000x5", "60,70", true);

WIN_ASSERT_EQUAL(0, auxsql.InsertShop(shOne));
WIN_ASSERT_EQUAL(0, auxsql.InsertShop(shTwo));

Neither the insertion, the commit, the creation of the sql statement or any other function call to the sqlite3 API return an error code.

A: I found the solution. It was nothing related to encoding, as I thought because of the characters being strangely represented in the DB browser and also nothing related to the length.
The problem was in the last parameter of the binding. Where i pass SQLITE_STATIC, I should have passed SQLITE_TRANSIENT, as the object returned by the calls I want to bind are possibly destructed before the query is executed. Just as it is explained in this other question:
sqlite3_bind_text SQLITE_STATIC vs SQLITE_TRANSIENT for c++ string

A: I think sqlite reference is quite clear about the API usage.

In those routines that have a fourth argument, its value is the number
  of bytes in the parameter. To be clear: the value is the number of
  bytes in the value, not the number of characters.

As per your usage,
sqlite3_bind_text(stmt, 2, newShop.GetName().c_str(), -1, SQLITE_STATIC);
the 4th arguement is -1. However it should be either newShop.GetName().length or strlen(newShop.GetName().c_str())`

Note : be careful when you deal with string with multi-wide chars.
  Where strlen(chinese string) ! = chinese string.len . Refer here for more details.


text:
Q: JavaScript Moveable Divs with JavaScript I want to make some funny movable divs.
I have the following codes:

dragElement(document.getElementById("draggable_shortcut"));
        function dragElement(elmnt) {
          var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
          if (document.getElementById(elmnt.id + "top-content")) {
            /* if present, the header is where you move the DIV from:*/
            document.getElementById(elmnt.id + "top-content").onmousedown = dragMouseDown;
          } else {
            /* otherwise, move the DIV from anywhere inside the DIV:*/
            elmnt.onmousedown = dragMouseDown;
          }

          function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            // get the mouse cursor position at startup:
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            // call a function whenever the cursor moves:
            document.onmousemove = elementDrag;
          }

          function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            // calculate the new cursor position:
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;
            // set the element's new position:
            elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
            elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
          }

          function closeDragElement() {
            /* stop moving when mouse button is released:*/
            document.onmouseup = null;
            document.onmousemove = null;
          }
        }
#draggable_shortcut {
    position: absolute;
    z-index: 9;
    text-align: center;
    cursor: grab;
}
#draggable_shortcut img {
    width: 50px;
    height: 50px;
}
#draggable_shortcut p {
    color: black;
    font-size: 14px;
    margin: 0px;
}

Moveable Icon

It works really god without issues.
If I add some more divs, the script doesn't work anymore,
because it's just for one and not more.
But I want to make more than one div, which are movable.
I'm new in JavaScript Programming. Any ideas?

Thank you for the ideas and scripts.
Not my last question about this script:
Is it possible to make, if the user drops an div, the position should be setted on hundred px?For example, if the user drops the div on the coordinates (120/105) it should get moved to  (100/100). Another exmaple: (170/355) -> (200/400). If possible, would be nice if an user can change, he would want with the hundred corrds or cutsom like this before.
Update 12.11.2018:I found now a possibility to check the coords. But it will be only placed if the coords are exaclty 100 and not like 105. Any ideas? Demo here:
http://next.plnkr.co/edit/fBWlF0B3t4XbjuSW
Update 12.11.2018 Later...
I found now a possibillity. For these, who want the same: http://next.plnkr.co/edit/fBWlF0B3t4XbjuSW

A: Try with class instead of id.
You have to call the function for each element individually. You can use Document.querySelectorAll()
 to get a static (not live) NodeList representing a list of the document's elements. Then use Array.prototype.forEach() to call the function for each element:

document.querySelectorAll(".draggable_shortcut").forEach(function(el){
  dragElement(el);
});

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "top-content")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "top-content").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
.draggable_shortcut {
    position: absolute;
    z-index: 9;
    text-align: center;
    cursor: grab;
}
.draggable_shortcut img {
    width: 50px;
    height: 50px;
}
.draggable_shortcut p {
    color: black;
    font-size: 14px;
    margin: 0px;
}

Moveable Icon

Moveable Icon

A: You need to make loop for each item.
    var elements = document.getElementsByClassName("drag");
    for(var i=0; i<elements.length; i++) {
        console.log(elements[i].id)
        dragElement(document.getElementById(elements[i].id));
            function dragElement(elmnt) {
              var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
              if (document.getElementById(elmnt.id + "top-content")) {
                /* if present, the header is where you move the DIV from:*/
                document.getElementById(elmnt.id + "top-content").onmousedown = dragMouseDown;
              } else {
                /* otherwise, move the DIV from anywhere inside the DIV:*/
                elmnt.onmousedown = dragMouseDown;
              }

              function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // get the mouse cursor position at startup:
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // call a function whenever the cursor moves:
                document.onmousemove = elementDrag;
              }

              function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // calculate the new cursor position:
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // set the element's new position:
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
              }

              function closeDragElement() {
                /* stop moving when mouse button is released:*/
                document.onmouseup = null;
                document.onmousemove = null;
              }
            }
}

Also change id to classes
.drag {
    position: absolute;
    z-index: 9;
    text-align: center;
    cursor: grab;
}
.drag img {
   width: 50px;
    height: 50px;
}
.drag p {
  color: black;
    font-size: 14px;
    margin: 0px;
}

Now each div must have individual id and the same class
Working plunker: http://plnkr.co/edit/R8PUSaxkWebiZoq1XraC?p=preview


text:
Q: A complete url does not get pass through in node.js I am using following code
var http = require('http'),
    url = require('url');

function handle_incoming_request (req, res) {
    console.log('Incoming request: (' + req.method + ') ' + req.url);

    req.parsed_url = url.parse(req.url, true);
    console.log(req.parsed_url);
}

var server = http.createServer(handle_incoming_request);
server.listen(8080);

Now when I curl below
curl -i -X GET http://localhost:8080/albums/italy2012.json?page=0&page_size=20

Then I get below in node console
Incoming request: (GET) /albums/italy2012.json?page=0
{ protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?page=0',
  query: { page: '0' },
  pathname: '/albums/italy2012.json',
  path: '/albums/italy2012.json?page=0',
  href: '/albums/italy2012.json?page=0' }

As you can see in first line the url is half. It is omitting &page_size=20
Why and how can I fix this?

A: The issue is with how you post via CURL, you need to quote the URL, otherwise the ampersand sign will set CURL as a background process
curl -i -X GET "http://localhost:8080/albums/italy2012.json?page=0&page_size=20"


text:
Q: "Assume that A = B" subjunctive? Over on Math.SE, a question exists regarding the usage of the word "that" in the following sentences:

*

*Assume that A = B.

*Assume A = B.

A well-known author suggests that users elect Option 1 in mathematical writing.
A discussion arose whether or not Option 1 is perfectly acceptable usage of the subjunctive, with a caveat: that the glyph "=" be read "equal" and not "equals."
The author of the book in question also further suggested that the word "that" be used only if it helps parse a sentence, "Assume that A is a group" vs. "Assume A is a group." This point was less contended, but in the subjunctive discussion, contrary concerns also arose whether the usage "Assume A be a group" is correct archaically, is correct presently, or has never been correct at all.
First question: given that "Assume..." is functionally equivalent to necessity in mathematical writing, is the sentence "Assume that A equal B" a proper use of the subjunctive?
Second question: Is, or has ever been, the usage "Assume that A be a group" been proper conjugation of "is" in a properly-used subjunctive?
Third question: Is there anything structurally unsavory about the use of the conjunction "that" in the form "Assume that A equals B" (note the s)?

A: *

*Patterning of the subjunctive is becoming very spotty in English, but is generally restricted to subordinate clauses licensed by verbs of compulsion or persuasion. e.g., The court orders/requests/requires/prays that Thomas present himself for sentencing... [pray used in its legal sense]. In modern American English (I don't know about older English) the preceding sentence doesn't work with psych verbs like hope/wish/pray [pray used in its common sense] or cognition verbs like think/assume/believe/suppose. Note also that the modal use of were (e.g., Assume that Thomas were guilty...) is usually called irrealis, not subjunctive.

*That is correct, but only because let licenses a complement clause with its verb in the base form. It doesn't have to do with the subjunctive. (e.g., The judge let Thomas delay the hearing... is clearly not showing subjunctive mood)

*Nothing structurally unsavory, and I agree that the best guideline on omitting or using that is to improve parseability.

A: Your "well-known author" doesn't seem to know English very well.
The verb assume always takes the indicative in contemporary English.  The correct formulation is:

I assume that he is coming.

And therefore, of

Assume that A is equal to B.

or likewise

Assume that A equals B.

You can find people who might say

Suppose it were otherwise; what would you do?
Imagine that it were different; what would you do?

But there aren't many of those.
As for your second question,

Let A be a group.

Is perfectly grammatical.
Finally, on your last question, there is nothing whatsoever wrong with having a that there, any more than there is anything wrong with not having it there.

Edit
I suppose it might be possible that your writer is using assume as a substitute for let, making it a sort of auxiliary. It would therefore take a bare infinitive under that reading.
However, the OED presents no documented evidence of that sort of thing. The only thing of apparent relevance which the OED gives is this:

10. trans. To take for granted as the basis of argument or action; to suppose: a. that a thing is, a thing to be.

*

*1841 Myers Cath. Th. iii. §25. 91 — To assume that we have the most accurate possible translation.

*1868 Peard Water-farm. x. 103 — The entire length of our farm is assumed to be about thirty-two miles.

There you have documentation that it takes both that and a simple indicative is form: one assumes that a thing is such and such.

A: All right, the English subjunctive mood is tricky mostly because, in modern English, it's considered in many areas to be moribund or outmoded.  In most situations, the indicative and subjunctive can live side by side and have, in fact, done so since Middle English times.  I went to school for English and many of my theses have been written on this topic.  I shall break down the subjunctive, which can have a very formal, sometimes archaic feel to it, but is still quite beautiful, to say the least.  Here are some examples in the subjunctive mood (some examples may have a modal that replaces the subjunctive forms):

*

*Assuming that he be correct, can we still get to the show in time?

*"And ne'er throughout the year to church thou go'st/Except it be to pray against thy foes" (Shakespeare).

*I pray that God give them the serenity that they may forgive this man.

*O that I were the President of the United States.  What policies I would invoke were I holding that office.

*I can only hope that he find true love one day.  It's my only hope and wish that he be as lucky as I have been in my lifetime with my wife.

*Should he violate the terms of his parole, he shall be returned to prison forthwith.

*Whether the committee sanction him or not, he will still remain in his tenured position on the board.

*It is important that the students do their own work.

*I demanded that they not say another word.

*Though he face many perils, he will ultimately succeed. (Also, though he may face many perils...).

*It's better if he go with you.

*If you had gone to school, you would have had to take a test.

*I wish I were an Oscar Meyer wiener.

*If only he knew the answer, he wouldn't be in this predicament.

*It is the judgment of this court that you be sentenced to probation.

*He will be permitted to attend the ceremony provided he dress accordingly.

*We shall do it on the condition that we be paid $5,000.

*In the event that he died right now, his estate would devise to his next of kin.

*As long as he have answered all of the questions, the chances of his failing are slim.

*They will plant trees along the street in memory of the victims so that no one ever forget them.

*If he go to the store, he will buy some eggs.

*If I were to go with you, I would never forgive myself.

*He fled the country lest he be captured and imprisoned.
The above examples are all correct under the rules of English grammar; however, many of them would be considered archaic if they were used today.  Despite their being overly formal or archaic, they limn the usage of the subjunctive in English in a diachronic analysis more so than just capturing its modern usage.  None of the 23 examples above could be deemed ungrammatical, but many people might categorize them as stilted nonetheless.  These examples were not shown to be stilted; they were shown so that readers could see the entire usage of the subjunctive.
The subjunctive can be used after many other coordinating conjunctions like "until", "unless", "although", and "before".  It can also be used after subordinating "that" clauses when those clauses are linked by words of necessity, possibility, contingency, commands, requests, aspirations, supplications, doubts, fears, and other operative words that evoke latent emotions that do not necessarily indicate that an event happens, will happen, or has happened.  Those words that would indicate such actual events would fall into the indicative mood, which is the common mood of language: "He is the one. I went to the store yesterday.  They will find the time to do it."
That is the English subjunctive mood in a nutshell.  One example I did not discuss, "Let there be light", is called the hortatory subjunctive so those above who proclaimed that "let" doesn't open up a subjunctive are wrong.


text:
Q: Mocking Java 8 lamba function with Mockito 2 I am using JDBI 3 and have written the following utility function.
public class JdbiHelper {
    // ...

    public <T, DAO> T fetch(final Function<DAO, T> function, Class<DAO> daoClass) {
        return dbi.withHandle(handle -> {
           final DAO dao = handle.attach(daoClass);
           try {
               return function.apply(dao);
           }
           finally {
               handle.close();
           }
        });
    }
}

which I can call in methods like this
public Optional<Account> findByEmailAddress(final String emailAddress) {
    if (!exists(emailAddress))
        return Optional.empty();
    return jdbiHelper.fetch(dao -> ofNullable(dao.selectByEmailAddress(emailAddress)), AccountDAO.class);
}

private boolean exists(final String emailAddress) {
    return jdbiHelper.fetch(dao -> dao.count(emailAddress) > 0, AccountDAO.class);
}

I am trying to write a test for the findByEmailAddress mocking jdbiHelper using Mockito 2 but cannot work out how to mock the dao -> part of the method.
I've tried using jdbiHelper.fetch(any(Function.class), eq(AccountDAO.class)) but as there are two different expectations of what to return it fails trying to cast one or the other.
Passing in a mocked Function causes a NPE as the dao param is null.


text:
Q: Text in PDF render of Reporting Services report "overprints" A report I have been working on some time ago started mis-rendering around Christmas. Some of the text boxes on it suddenly started rendering each character in their text content on top of each other, as if the printing of each character no longer "advances the cursor" to the correct position for the next one. The report is rendered to PDF by URL access.
Anyone seen this behavior before?
Any idea what could be causing this?
I'm just curious, actually.
(I currently have no idea what was changed on the server "around Christmas".)

A: I've ran in to this once before. My problem was two textboxes were overlapping by barely a pixel. This kept them from "pushing" each other so the text didn't overwrite the other. So make sure your textbox objects aren't touching, hopefully that is it, easy fix, otherwise I wish you luck.

A: I had the same problem with text overlapping and rendering weird when printing and exporting to pdf of an ssrs report.
As Dustin says, the problem is that textboxes were overlapping.


text:
Q: How is a callback different from and advantageous to conditional function calls for event handling? I understand that in case of implementing a library where a library programmer doesn't know

*

*what different clients want to do after calling a particular library API (e.g. timer APIs)
or

*for which purpose they want to call the library API (e.g. a sort library, different methods of comparison available for different type of data),

the programmer provides a parameter in his API for a function pointer which is a good use of callback functions.
I have read this article about callbacks, but am still a little confused. How is a callback different from a normal function call in case of event handling? As I see them, they are analogous to normal function calls made in a switch statement, like this:
switch(eventType) {
    case EventA: handleEventA(); break;
    case EventB: handleEventB(); break;
    ...
}

How is "registering callbacks" different from this, and what are the advantages to doing so?

A: The main advantage of using callbacks is that you can call a subroutine defined in higher software level from a lower software level subroutine.
Let's take an example :

*

*Library function fetchData
int fetchData(type1 arg1 , type2 arg2, ... , functionPointerType funcPointer)

*Let's assume fetchData gets data from a HTTP server.

*Now suppose the user of the library wants to handle the data that fetchData gets from the HTTP server
4.So user will define a function handelData with prototype matching functionPointerType and will pass the pointer to this function to fetchData.
5.So whenever fetchData(lower level subroutine) gets content from HTTP server it will pass that data to handleData(higher level subroutine)
6.In my higher level subroutine i can handle the data passed from lower level subroutine, say based on content-type or any other attribute associated with that data.
If i were to use normal function calls made in a switch statement, then that code would have gone in the fetchData itself, so this doesn't give the user of the library the flexibilty of handling data according to the needs of his application.
The classic example of using callbacks is signal handling in C(Linux)
void takeAction(int signo)
{
  printf("Recieved SIGKILL (kill -%d)\nExiting now...\n",signo);
  exit(0);
}

int main()
{
  signal(SIGINT,takeAction);
  while(1)
  {
    printf("In Main...\n");
    sleep(2);
  }
}

Here application can handle the signal as per the requirements of the application.


text:
Q: Facebook getLoginStatus was not getting any response

Login with Facebook

As per facebook document to check user is already login or not we can use FB.getLoginStatus get the user is log in or not but in my cause i can"t able to get any response

A: try this instead. It will call the login function right after being initialized. In your current code

Login with Facebook


text:
Q: Fetching data for another variable react I have a question of something that looks pretty obvious but It's getting hard for me. I know that for fetching data that will get actually rendered in a component you need to use reacthooks and useState. However I am having a problem because I need to fetch some data and then store it in a variable that it's not part of the component rendering. This is my current code.
import React from 'react'
import { GoogleMap, useJsApiLoader } from '@react-google-maps/api';
import { GoogleMapsOverlay } from "@deck.gl/google-maps";
import {GeoJsonLayer, ArcLayer} from '@deck.gl/layers';
import axios from 'axios';
import {useState} from 'react';

const hasWindow = typeof window !== 'undefined';

function getWindowDimensions() {
  const width = hasWindow ? window.innerWidth : null;
  const height = hasWindow ? window.innerHeight : null;
  return {
    width,
    height,
  };
}

const center = {
  lat: 51.509865,
  lng: -0.118092
};

const deckOverlay = new GoogleMapsOverlay({
  layers: [
    new GeoJsonLayer({
      id: "airports",
      data: markers,
      filled: true,
      pointRadiusMinPixels: 2,
      opacity: 1,
      pointRadiusScale: 2000,
      getRadius: f => 11 - f.properties.scalerank,
      getFillColor: [200, 0, 80, 180],

      pickable: true,
      autoHighlight: true
    }),
    new ArcLayer({
      id: "arcs",
      data: markers,
      dataTransform: d => d.features.filter(f => f.properties.scalerank < 4),
      getSourcePosition: f => [-0.4531566, 51.4709959], // London
      getTargetPosition: f => f.geometry.coordinates,
      getSourceColor: [0, 128, 200],
      getTargetColor: [200, 0, 80],
      getWidth: 1
    })
  ]
});

export default function Map() {
  const { isLoaded } = useJsApiLoader({
    id: 'lensmap',
    googleMapsApiKey: "YOUR_API_KEY"
  })

  const onLoad = React.useCallback(function callback(map) {
    deckOverlay.setMap(map)
  }, [])

  const onUnmount = React.useCallback(function callback(map) {
  }, [])

  return isLoaded ? (
      <GoogleMap
        mapContainerStyle={getWindowDimensions()}
        center={center}
        zoom={10}
        onLoad={onLoad}
        onUnmount={onUnmount}
      >
        <></>
      </GoogleMap>
  ) : <></>
}

As you can see GoogleMapsOverlay receives a markers object in it's constructor, here I would get my markers doing a call to an API using axios but everything that I've tested ends in a 500 code when loading the page.

A: I assume that you're asking for a way to fetch the markers and make everything load in the correct order. I think you could store the deckOverlay instance in a ref, fetch the markers in a useEffect hook, update the layers with the markers data, and set a flag to hold from rendering the map until the layers are updated.
import React, { useState, useRef, useEffect, useCallback } from "react";
import { GoogleMap, useJsApiLoader } from "@react-google-maps/api";
import { GoogleMapsOverlay } from "@deck.gl/google-maps";
import { GeoJsonLayer, ArcLayer } from "@deck.gl/layers";
import axios from "axios";

const hasWindow = typeof window !== "undefined";

function getWindowDimensions() {
  const width = hasWindow ? window.innerWidth : null;
  const height = hasWindow ? window.innerHeight : null;
  return {
    width,
    height,
  };
}

const center = {
  lat: 51.509865,
  lng: -0.118092,
};

export default function Map() {
  const { isLoaded } = useJsApiLoader({
    id: "lensmap",
    googleMapsApiKey: "AIzaSyBmSBtlYQLH8jvAxrdgZErUdtdWLEs40gk",
  });
  const [markersLoaded, setMarkersLoaded] = useState(false);
  const deckOverlay = useRef(new GoogleMapsOverlay({ layers: [] }));
  const fecthMarkers = useCallback(async () => {
    try {
      const response = await axios.get(`someapi.com/markers`);
      // assuming API response will have a markers field
      const markers = response.data.markers;
      deckOverlay.current.setProps({
        layers: [
          new GeoJsonLayer({
            id: "airports",
            data: markers,
            filled: true,
            pointRadiusMinPixels: 2,
            opacity: 1,
            pointRadiusScale: 2000,
            getRadius: (f) => 11 - f.properties.scalerank,
            getFillColor: [200, 0, 80, 180],
            pickable: true,
            autoHighlight: true,
          }),
          new ArcLayer({
            id: "arcs",
            data: markers,
            dataTransform: (d) =>
              d.features.filter((f) => f.properties.scalerank < 4),
            getSourcePosition: (f) => [-0.4531566, 51.4709959], // London
            getTargetPosition: (f) => f.geometry.coordinates,
            getSourceColor: [0, 128, 200],
            getTargetColor: [200, 0, 80],
            getWidth: 1,
          }),
        ],
      });
      setMarkersLoaded(true);
    } catch (e) {
      // TODO: show some err UI
      console.log(e);
    }
  }, []);

  useEffect(() => {
    fecthMarkers();
  },[]);

  const onLoad = React.useCallback(function callback(map) {
    deckOverlay.current?.setMap(map);
  }, []);

  const onUnmount = React.useCallback(function callback(map) {
    deckOverlay.current?.finalize();
  }, []);

  return markersLoaded && isLoaded ? (
    <GoogleMap
      mapContainerStyle={getWindowDimensions()}
      center={center}
      zoom={10}
      onLoad={onLoad}
      onUnmount={onUnmount}
    >
      <></>
    </GoogleMap>
  ) : (
    <></>
  );
}

A: While it's a good idea to use a ref in most cases, it's not technically needed in this case, if there's just 1 instance of the component on the page. The important part is that you use an effect, which can run any JS and interact with any function / variable that is in scope.
Also important to know is that you need to add setMarkersLoaded(true); at the end to ensure a new render happens, if you want one to happen. If you don't need a render to happen (e.g. here if the map was already displayed regardless of whether the markers loaded), you can remove this part.
diedu's answer uses useCallback to create the async handler (fetchMarkers) used in useEffect, however you don't need to use this hook here. The function is written to ever be called just once, and is not passed to any component. useCallback is only for when you find a new function being created causes a component to re-render that otherwise wouldn't.
It's better to define the data fetching function outside of the component, so that you can keep the effect code simple and readable. You can even map it to layers in that function, and so remove another large chunk of logic out of your Map component.
useEffect(() => {
  (async () {
    const layers = await fetchMarkerLayers();
    deckOverlay.current.setProps({layers});
    setMarkersLoaded(true);
  })();
},[]);

Because the argument of useEffect can not be an async function, you need put a self invoking async function inside. If you don't like that syntax, you could also chain promises with .then. Both syntaxes are a bit hairy, but because we extracted the complex logic out of the component, it's still readable.
Full code
I kept some parts of diedu's snippet, like how the ref is used, as they didn't need changes.
import React, { useState, useRef, useEffect, useCallback } from "react";
import { GoogleMap, useJsApiLoader } from "@react-google-maps/api";
import { GoogleMapsOverlay } from "@deck.gl/google-maps";
import { GeoJsonLayer, ArcLayer } from "@deck.gl/layers";
import axios from "axios";

const hasWindow = typeof window !== "undefined";

function getWindowDimensions() {
  const width = hasWindow ? window.innerWidth : null;
  const height = hasWindow ? window.innerHeight : null;
  return {
    width,
    height,
  };
}

const center = {
  lat: 51.509865,
  lng: -0.118092,
};

const fetchMarkerLayers = async () => {
  try {
    const response = await axios.get(`someapi.com/markers`);
    // assuming API response will have a markers field
    const { markers } = response.data;
    return [
        new GeoJsonLayer({
          id: "airports",
          data: markers,
          filled: true,
          pointRadiusMinPixels: 2,
          opacity: 1,
          pointRadiusScale: 2000,
          getRadius: (f) => 11 - f.properties.scalerank,
          getFillColor: [200, 0, 80, 180],
          pickable: true,
          autoHighlight: true,
        }),
        new ArcLayer({
          id: "arcs",
          data: markers,
          dataTransform: (d) =>
            d.features.filter((f) => f.properties.scalerank < 4),
          getSourcePosition: (f) => [-0.4531566, 51.4709959], // London
          getTargetPosition: (f) => f.geometry.coordinates,
          getSourceColor: [0, 128, 200],
          getTargetColor: [200, 0, 80],
          getWidth: 1,
        }),
      ]
  } catch (e) {
    // TODO: show some err UI
    console.log(e);
  }
};

export default function Map() {
  const { isLoaded } = useJsApiLoader({
    id: "lensmap",
    googleMapsApiKey: "AIzaSyBmSBtlYQLH8jvAxrdgZErUdtdWLEs40gk",
  });
  const [markersLoaded, setMarkersLoaded] = useState(false);
  const deckOverlay = useRef(new GoogleMapsOverlay({ layers: [] }));

  useEffect(() => {
    // Use a self invoking async function because useEffect's argument function cannot be async.
    // Alternatively you can chain a regular Promise with `.then(layers => ...)`.
    (async () {
      const layers = await fetchMarkerLayers();
      deckOverlay.current.setProps({layers});
      setMarkersLoaded(true);
    })();
  },[]);

  const onLoad = React.useCallback(function callback(map) {
    deckOverlay.current?.setMap(map);
  }, []);

  const onUnmount = React.useCallback(function callback(map) {
    deckOverlay.current?.finalize();
  }, []);

  return markersLoaded && isLoaded ? (
    <GoogleMap
      mapContainerStyle={getWindowDimensions()}
      center={center}
      zoom={10}
      onLoad={onLoad}
      onUnmount={onUnmount}
    >
      <></>
    </GoogleMap>
  ) : (
    <></>
  );
}


text:
Q: Exchange 2010 send from multiple domains We have a Windows 2008 Enterprise R2 SP1 server with multiple accepted domains configured on our Exchange 2010 console.
Configuration of exchange 2010:
In exchange console, under organization configuration > hub transport > accepted domains, we have:
domain1 > authoritative > default = true
domain2 > authoritative > default = false
domain3 > authoritative > default = false
domain4 > authoritative > default = false

We are able to RECEIVE e-mails on ALL the above domains.
Just to be clear: I can receive emails to userX@domain1.com , userX@domain2.com, userX@domain3.com and userX@domain4.com without any problems. I am able to send email from userX@domain1.com (the default domain). However, when trying to send emails from userX@domain2.com, userX@domain3.com, and userX@domain4.com, I receive the following error:
Delivery has failed to these recipients or groups:

destination_example_email You can't send a message on behalf of this
  user unless you have permission to do so. Please make sure you're
  sending on behalf of the correct sender, or request the necessary
  permission. If the problem continues, please contact your helpdesk.

If I change the primary email address for userX to userX@domain3.com , I am able to send as userX@domain3.com and only from that mail.
The question:
How can I enable sending emails from ALL the authoritative domains at any single moment without having to manually change the default email address of the user?

A: We've found a work-around in the meanwhile.
If we split up the accounts into 4 different accounts, and grant the correct permissions, we are able to send as any user.
However this is a very pale solution. this would multiply the number of accounts in both AD and Exchange
Still searching for a official fix on this.

A: As far as I am aware each mailbox can have only one primary email address, this is the reply address the recipient will receive, even if each mailbox has multiple alias email addresses.
I would create a mailbox for each domain. Then give the user full mailbox access to the domain2.com, domain3.com and domain4.com mailboxes, and add these as additional mailboxes in the Outlook profile.
When the user sends an email they will then be able to choose each the relevant email addresses from the from field.
To complement this I would set an autoforward from the additional domains to the domain.com mailbox so the user doesn't have to check each mailbox.
It's not a perfect solution but will do the job.

A: This answer assumes that you are attempting to use Outlook as your mail client.
This is a common problem that I have run into. The way to do it is to setup a dummy account in Outlook as a POP3 account and SMTP with the alias/alternate email. Then turn off the automatic checking of mail for the POP3 account by removing it from the default receive group. An authenticated SMTP session can send email as any alias that the user has. This also changes the "From" field in new emails to a drop down that can be changed.
This is a good article on setting this up: http://www.thirdtier.net/how-to-configure-outlook-so-you-can-send-from-an-alias/

A: In an Exchange environment an user can only send emails using a sender address he/she owns (unless delegation is used); if an user has a primary address user@domain1.com and secondary addresses user@domain2.com and user@domain3.com, all of them will work; of course, it's up to the user to select the right sender address in Outlok or OWA: if nothing is explicitly selected, the primary address will be used.
But if an user doesn't have an address assigned to him/her, Exchange will refuse to send a message using that sender address.
If you want all your users to have an email address in all your SMTP domains, you'll need to update your address policy to give each user an address in all domains; this will allow them to use any of their addresses as the sender address when sending a message. It doesn't matter if an address is primary or not: an user will be able to send messages using any address he/she owns.


text:
Q: How to use a regex to organize song lists, changing their order from "Song - Artist" to "Artist - Song"? I have a long list of songs in the format "Artist - Song", but I want them to be listed as "Artist - Song". How to change all items automatically with a regular expression, preferably on Notepad++?

A: On Notepad++:

*

*Click before the first letter in your file for the search to run throughout the complete list

*Press CTRL + H to open the text editor Replace dialog

*Check the Regular expression search mode

*Type (.*?)\s-\s(.*) in the "Find what" field. It means "select and save everything until a hyphen preceded by a space" and then "everything after the hyphen followed by a space"

*Type \2 - \1 in the Replace with field to insert the two sets reversed

*Click on Replace all
Note: if it doesn't work, make sure that the list uses the same hyphen character as the one you typed into the Find what field.


text:
Q: Registro de fechas de creación y modificación en una tabla de usuarios Estoy creando una base de datos sobre una tienda de abarrotes (productos de primera necesidad) por lo tanto tengo una tabla llamada usuario donde cada usuario debe tener distintos permisos, la cuestión es que quiero almacenar cuando se cambie un usuario o se modifique cierto usuario, ¿cómo debería hacer en ese caso?
CREATE TABLE usuario(
  id int primary key not null,
  Nombre varchar (25),
  Apellido varchar (50),
  Direccion varchar (100),
  Telefono varchar (20),
  Login varchar (20),
  psw varchar (6),
  fecha_creacion datetime,
  fecha_actualizacion datetime,
  Usuario_creacion datetime,
  Usuario_actualizacion datetime
 );

A: Como el tema de disparadores es relativamente complejo, te adelanto la solución en este fiddle: https://dbfiddle.uk/63dtpoyu Pero es importante que tengas en cuenta que intentar dar con una solución es mucho más que crear una tabla. Tendrías que haber ido al manual e intentar escribir algo de código.
La idea es crear una tabla para los datos históricos historico_usuario, los modificados, porque los nuevos los tendrás en la tabla usuario:
CREATE TABLE IF NOT EXISTS historico_usuario(
  id int not null,
  Nombre varchar (25),
  Apellido varchar (50),
  Direccion varchar (100),
  Telefono varchar (20),
  Login varchar (20),
  psw varchar (6),
  fecha_creacion datetime,
  fecha_actualizacion datetime,
  Usuario_creacion datetime,
  Usuario_actualizacion datetime,
  f_mdf datetime
);

A continuación creas el procedimiento almacenado que, dado un id, te copie el dato al histórico:
CREATE PROCEDURE rellena_historico_usuario(v_id int)
BEGIN
  DECLARE n int;
  SELECT
    COUNT(*) INTO n
    FROM usuario
    WHERE id = v_id;
  IF n>0 THEN
    INSERT INTO historico_usuario
      SELECT *,NOW() FROM usuario
        WHERE id=v_id;
  END IF;
END;

Una vez este punto, ya puedes definir los disparadores de antes del cambio, ya sea actualización o borrado:
CREATE TRIGGER usuario_update_before
  BEFORE UPDATE ON usuario
  FOR EACH ROW
  CALL rellena_historico_usuario(OLD.id);

CREATE TRIGGER usuario_delete_before
  BEFORE DELETE ON usuario
  FOR EACH ROW
  CALL rellena_historico_usuario(OLD.id);

Ahora únicamente te queda hacer las comprobaciones:
INSERT INTO usuario (id,Nombre) VALUES (1,'Julián'),(2,'Pedro');
UPDATE usuario set Nombre='Paco' WHERE id=1;
DELETE FROM usuario WHERE id=2;

Y ver si obtienes el resultado que esperabas: https://dbfiddle.uk/63dtpoyu


text:
Q: Shipping 1.2 million records with an iPhone app I have a data set of 1.2 million key-value pairs. The keys are a string (a sequence of numbers up to 22 characters in length), and the values are strings.
What's the best way to ship this so a value can be looked up and retrieved quickly?
I suspect a plist is not the way to go for a data set this size.
I have the data set stored in two ways - a CSV, and a mySQL database table with 2 columns. I
ll go forward using whatever method gets the data into the app the best.

A: Core Data and SQLite are two good options for dealing with very large data sets in iOS. It's not difficult to create a Core Data model for the kind of data you're talking about. You can then copy that model into a little command line program that you'll write to move the data into a Core Data store. You can then move the resulting data file into your iOS app's resources.
A third option, particularly useful if the data is likely to change often, is to build a web service to provide the data from the service. I don't think this is what you're asking about, but it's something to consider if the data set is very large and/or subject to frequent change.

A: a collection of text files could work well. you can:

*

*divide them into multiple files (e.g. by leading character range).

*order pairs appropriately (e.g. by character number)

*and quickly/easily read incrementally/portions as appropriate.

*balance resources between file reads and memory usage well.

*choosing the right encoding for the strings can also help (i'd start with utf8 if it's mostly in ascii).

if distribution size is also your concern, you could compress/decompress these files.
or you can just take this approach and use a custom serialized class to represent a subsets of the collection if that sounds like too much parse and read implementation.
if you're using objc types for storage and/or parsing, then it would be good to keep those files small. if you use c or c++, then it would help to profile the app.
your data set will require up to 30 MB using an 8 bit per character single byte encoding. one large file  (again, ordered) which you mmap would also be worth consideration. see [NSData initWithContentsOfMappedFile:path];.

A: My personal experience is with a plist file that has only thousands of records and I can say that it isn't it so fast. So my options for this amount of data you have are:

*

*A database.

*Or if you have a sorting criteria for those keys and prefer plist
files split it in many files and keep a reference dictionary with the start key of every file. For ex. all keys that begin with 'abc' go in a.plist etc.

(I don't know if it's the case with your app but you can consider moving the data to a server and search via a webservice, specifically if your data will grow.)

A: A sqlite file is probably your best bet. You can create it on the desktop using either the command-line sqlite3 or any sqlite gui. Make sure you index the key column.
Import the csv file as described here: Importing csv files into sqlite
Then just add the database to your project/target. If you want to modify the database at runtime, however, you'll have to copy it out into your Documents or cache directories.
For an objective-c wrapper around sqlite, I like fmdb


text:
Q: Show Data of CollectionView On Start so I am using a collection view to show an image from my Parse server. When that image is clicked I have two labels on the bottom of the page that show more information (also from the server). The only problem is that these labels are not included in the CollectionView so the user has to tap on the cell for the data to fill those labels. How may I automatically fill those labels with the cell that is presented on the screen? Thank you!
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

PFObject *selectedObject = [labelFileArray objectAtIndex:indexPath.row];
    titleLabel.text = selectedObject[@"labelText"];

    PFObject *selectedObject2 = [mainTextArray objectAtIndex:indexPath.row];
    mainTextLabel.text = selectedObject[@"mainTextLabel"];

}

A: If I understand your question correctly, your problem is that you want to access the contents of the selected cell so you can put that content in the labels at the bottom of the screen.
In your didSelectItemAtIndexPath, you can use something like:
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
if (cell)
{
    titleLabel.text = cell.(wherever your content is in the cell)
}

If you need to you can put a tag on the particular content you're interested in and find that view using the tag value.  If you want to update your post with the dequeue method I could provide a little more detail if you want it.


text:
Q: How can I hide the X-Axis in D3 (DynamicDataDisplay) Plotter? I would like to be able to hide the X-Axis (Labels, Ticks, etc) in the ChartPlotter of D3 (DynamicDataDisplay). The amount of documentation available for D3 is basically non-existent.
Any help would greatly be appreciated.

A: As far as I can see in the sources the AxisBase is a ContentControl so you should be able to make it invisible.
That might be too crude so you could also take a look at the default style/template, copy it and change it to hide/remove those part that you want to hide.

A: plotter.HorizontalAxis.Remove();

in code-behind. Just done it in my WPF app.


text:
Q: Behavior of data in indexes based on fill factor Let's say you have a database where the default fill factor is 20.  Whenever data is inserted, does it only create pages filled up to 20%?
From my understanding, when the data is inserted there will be roughly 20% of data in the pages.  When the data is updated, however, it will expand to more than 20% of the index, upto filling it and generating a page split, right?

A: Fill factor only comes into play when an index is created or rebuilt.  It is the amount of consumption for the index of the leaf level pages that are filled during these operations. (see the note below for more clarification on affected page levels)
When there is a DML command to data (INSERT, UPDATE, and/or DELETE), it will happen to the corresponding affected indexes.  In other words, if you have a page that is 20% filled and you insert data into that page, the page will contain more than 20% of the data (let's say 35% just for example's sake).  Do another insert, now the page is 64% filled.  Rebuild the index, and the leaf level pages will now relatively contain the space percentage that you specify (or implicitly the default value for the server).
(Note, when you don't specify PAD_INDEX to be ON, fill factor is only applied to leaf level pages.  But when you set PAD_INDEX = ON, the fill factor will be taken into account for intermediate-level pages of the index.  The default is OFF)
The reason to adjust fill factor (instead of using the default 100/0) is so that you minimize page splits when inserting or updating data.  But keep in mind, nothing is for free.  The lower the fill factor, the more space data would normally take up.  If you keep an 80% free page space for your indexes, they will consume a relatively larger amount of disk space, which can lead to more reads.

From my understanding, when the data is inserted there will be roughly 20% of data in the pages. When the data is updated, however, it will expand to more than 20% of the index, upto filling it and generating a page split, right?

When data is inserted it will insert into the appropriate indexes at the appropriate page.  This could and most likely would very well cause the page consumption to be higher than the fill factor.
A page split will happen when new data is added to a full index page.  SQL Server will then split the page and approximately place half of the data from the full page into a new page.  Again, fill factor does not come into play here.
A legitimate reason to lower fill factor would be to minimize page splits, therefore minimizing index page fragmentation.


text:
Q: How to use zonedSchedule notification by flutter_local_notifications when fold the app I am implementing my application (Alarm notification) I user flutter_local_notifications lib
I use zonedSchedule method to set Schedule it's work on forground bu when background it's not working.
I when to show notification on background.
I don't konw if someone have solution please tell me.
I no way out rightnow or you have another solution of Schedule on background plese tell me
Thanks.
This is my function call it work on forground
Future<void> showSchedulNotification(
      {required int id,
      required String title,
      required String body,
      required int seconds}) async {
    final details = await _notificationDetails();

    await _flutterLocalNotificationsPlugin.zonedSchedule(
        id,
        title,
        body,
        tz.TZDateTime.from(
            DateTime.now().add(Duration(seconds: seconds)), tz.local),
        details,
        androidAllowWhileIdle: false,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }


text:
Q: Function returns a undefined value I have something that I don't understand. I try to fetch some data from my database using a mongoose model. Here is the code:
function dot(property) {
  const result = Temp.findOne({tempHash: property}).exec( (er,result) =>  result);
}

function verify(req,res,next) {
 console.log(dot(req.query.id), dot(req.query.id));

 if (req.get('host') == dot(req.query.id).host) {
    console.log("Domain is matched. Information is from Authentic email");

    if(req.query.id == dot(req.query.id).tempHash) {
      // ...

My dot function fetch the values, when I use the console.log inside the exec callback I have a full object (result).
But when I try to access the object' properties from the verify function I have an undefined. For example when I want to log the result.host or result.tempHash I would have my value, not an undefined.

A: Your dot method does not return anything, that's why your result is undefined.
Start by making the dot method returns the result:
async function dot(property) {
  return Temp.findOne({ tempHash: property });
}

Now that dot returns a Promise you just have to call the method and then wait for the result:
function verify(req, res, next) {
  dot(req.query.id)
    .then(result => {
      if (!result) return;

      if (req.get('host') === result.host) {
        console.log("Domain is matched. Information is from Authentic email");
        if (req.query.id === result.tempHash) { // this condition is useless
          // ...
        }
      }
    })
    .catch(next);
}

A: You are working with asynchronous process, mongoose models executes asynchronously, i.e, they return promises that executes later and not instantly. to find more about JavaScript asynchronous programming, you can check out this MDN async post and promises
The following code would do what you are trying to achieve:.
const dot = function(property) {
    return Temp.findOne({tempHash: property}).exec();
};

const verify = async function(req, res, next) {
    //note that result can be null when no match exists in the db
    const result = await dot(req.query.id);
    if (result && req.get('host') == result.host) {
        console.log("Domain is matched. Information is from Authentic email");
    }
};


text:
Q: Why is SQLite syntax error reported I have an app that contains SQLite database. I created table and inserted value in to table but when I fetch data from table then it give me error that says
near "Dhanani": syntax error

Here my fetch data method:
-(void)getTextFromDb
{
    NSLog(@"Method Called");
    NSString *docsDir;
    NSArray *dirPaths;
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];

    _databasePath = [[NSString alloc]
                     initWithString: [docsDir stringByAppendingPathComponent:
                                      @"QpinData.db"]];
    const char *dbpath = [_databasePath UTF8String];
    sqlite3_stmt    *statement;
    if (sqlite3_open(dbpath, &_myDatabase) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat:@"SELECT QpinName,Address,Lat,Long,Type FROM QPINTABLE WHERE UserName=Ramesh Dhanani"];
        const char *query_stmt = [querySQL UTF8String];

        if (sqlite3_prepare_v2(_myDatabase, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            [self.qpinname removeAllObjects];
            [self.qpinType removeAllObjects];
            [self.address removeAllObjects];
            [self.latitude removeAllObjects];
            [self.longitude removeAllObjects];
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                NSString *QpinName = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)];
                NSString *Address = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 1)];
                NSString *latitude = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 2)];
                NSString *longitude = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 3)];
                NSString *Type = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 4)];
                [self.qpinname addObject:[NSString stringWithFormat:@" %@ ", QpinName]];
                [self.address addObject:[NSString stringWithFormat:@"%@ ",Address]];
                NSLog(@"self.address %@",self.address);
                [self.latitude addObject:[NSString stringWithFormat:@"%@",latitude]];
                [self.latitude addObject:[NSString stringWithFormat:@" %@",longitude]];
                [self.qpinType addObject:[NSString stringWithFormat:@" %@",Type]];
            }
            NSLog(@"%s",sqlite3_errmsg(_myDatabase));
            sqlite3_finalize(statement);
        }
        NSLog(@"%s",sqlite3_errmsg(_myDatabase));
        sqlite3_close(_myDatabase);
        [self.personalTable reloadData];
    }
}

Any help would be appreciated.

A: You have a value in your SQL that is not quoted. So you either:

*

*Put quotes around the user name value:
NSString *querySQL = @"SELECT QpinName,Address,Lat,Long,Type FROM QPINTABLE WHERE UserName='Ramesh Dhanani'";

*If the user name can change, you'd want to use ? placeholder in your SQL and then bind a value using sqlite3_bind_text:
-(void)getTextFromDb
{
    NSString *docsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *path = [docsDir stringByAppendingPathComponent:@"QpinData.db"];
    const char *dbpath = [path UTF8String];

    sqlite3_stmt    *statement;
    if (sqlite3_open(dbpath, &_myDatabase) == SQLITE_OK) {
        const char *query_stmt = "SELECT QpinName,Address,Lat,Long,Type FROM QPINTABLE WHERE UserName=?";

        if (sqlite3_prepare_v2(_myDatabase, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
            if (sqlite3_bind_text(statement, 1, [self.username UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
                NSLog(@"problem binding value: %s", sqlite3_errmsg(_myDatabase));
            }

            // clear out the model objects

            while (sqlite3_step(statement) == SQLITE_ROW) {
                NSString *qpinName = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)];
                NSString *address = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 1)];
                NSString *latitude = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 2)];
                NSString *longitude = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 3)];
                NSString *type = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 4)];

                // populate the model objects
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(_myDatabase);
        [self.personalTable reloadData];
    }
}

A: You must use,
NSString *querySQL = [NSString stringWithFormat:@"SELECT QpinName,Address,Lat,Long,Type FROM QPINTABLE WHERE UserName='Ramesh Dhanani'"];
Because any string in query must be in single quote.


text:
Q: Handling CRLF on a per project basis in Windows 10 / WSL with git? I got the following warning when trying to add my .rdl file to a project in git:
leeand00@SOMEWINBOX:/mnt/c/Users/leeand00/source/repos/ProdCompsFromCAPSReport$ git add ./ProdCompsFromCAPSReport/ProdComp_Simph_SSRS2014.rdl
warning: CRLF will be replaced by LF in ProdCompsFromCAPSReport/ProdComp_Simph_SSRS2014.rdl.
The file will have its original line endings in your working directory

Is there a way to tell git that I'd like to handle CRLF for windows instead of for Linux?  AKA using CRLF for my project instead of LF, but only for this project?  Should my core.autocrlf setting it go in .gitattributes for the project?


text:
Q: how to read and store variable from txt in c (unknown number of variables) the project should read any configuration txt file in the right format.
There is a different number of variable in each configuration file. The variables exist in the form of:
variable name = variable content or variable name=variable content
e.g. Name = Bob
how to read and store these variables for future use?


text:
Q: Detecting substring between strings with special characters I have 6 types of strings (after performing strip() on them):
string_1= 'This is a \'working draft\' sequence. It currently consists of 10 contigs. Gaps between the contigsare represented as runs of N. The order of the piecesis believed to be correct as given, however the sizesof the gaps between them are based on estimates that haveprovided by the submittor.This sequence will be replacedby the finished sequence as soon as it is available andthe accession number will be preserved.\n???UPDATE FROM "This record contains 83 individual sequencing reads that have not been assembled intocontigs. Runs of N are used to separate the readsand the order in which they appear is completelyarbitrary. Low-pass sequence sampling is useful foridentifying clones that may be gene-rich and allowsoverlap relationships among clones to be deduced.However, it should not be assumed that this clonewill be sequenced to completion. In the event thatthe record is updated, the accession number willbe preserved."???'

string_2= '???INSERT information???\n\nPlasmid; n/a; 100% of reads'

string_3= '???INSERT information???\n\ngap of      100 bp'

string_x= "This is a 'working draft' sequence. It currently consists of 10 contigs. Gaps between the contigsare represented as runs of N. The order of the piecesis believed to be correct as given, however the sizesof the gaps between them are based on estimates that haveprovided by the submittor.This sequence will be replacedby the finished sequence as soon as it is available andthe accession number will be preserved."

string_y= 'Plasmid; n/a; 100% of reads'

string_z= 'gap of      100 bp'

I am trying to make it so that:
if string_x in string_1:
    print("true")

if string_y in string_2:
    print("true")

if string_z in string_3:
    print("true")

However, this would not work even if I strip all the strings.
How should I go about doing this?

A: First you need to understand what str.strip() method does. It returns a copy of the string with the leading and trailing characters removed.
Syntax : str. strip([chars])
Example 1
>>> '   spacious   '.strip()
'spacious'
>>> "AABAA".strip("A")
'B'
>>> "ABBA".strip("AB")
''
>>> "ABCABBA".strip("AB")
'C'

Example 2
>>> 'www.example.com'.strip('cmowz.') # this example extracts web address
'example'

For more you can read the Official Documentation.

A: You can try to shape your strings to one format
string_1 = ''.join([x for x in string_1  if x.isalpha() or x == ' '])
string_x = ''.join([x for x in string_x  if x.isalpha() or x == ' '])


text:
Q: Divisors of a number in Python I've tried to write a peice of  code in python that prints all the divisors of a number including itself. it doesn't work correctly can anyone see why?
def divisors(num):

    for x in range (1, num):
        if (num % x) == 0:
            print(x)

print("Divisors of 6 are")

print(divisors(6))

A: range() excludes the upper bound and therefore should read range(1, num+1).

A: you can also try this
num=int(input("please eenter a number "))
a=[]
for x in range(1,num+1):
if num%x==0:
a.append(x)
print(a)