text:
Q: Can you contrive a simple example in MySQL where clustered index is the solution, instead of normal index? I don't see the point of clustered index, when will we benefit?

A: Clustered indexes
A clustered index means that the records are physically stored in order (at least near each other), based on the index. Clustered indexes are most important when you are retrieving various columns from each record, in order, because the database engine does not have to jump around to get the next record. Instead, the records are stored sequentially, therefore the seek time between records is at its minimum.
Clustered indexes are most important when reading multiple records that appear near each other in the index.
By default, with InnoDB, your primary index is a clustered index.
Use case for clustered indexes
If you were doing an incremental search like the Google and Yahoo search, where as you start typing, you see the first few records that match what you've typed so far, performance is paramount. If you were returning just a single indexed column in the result set, you wouldn't need a clustered index, but let's pretend that you also want to return the number of hits for each key_word, forcing the database engine to access the actual row. Since you want to return sequential rows, you should store them sequentially for optimal performance.
SELECT key_word, hits FROM keywords
WHERE key_word LIKE 'britney s%'
ORDER BY key_word
LIMIT 10

You'd want your primary key (clustered index) to be on key_word.
Comparison to nonclustered indexes
All indexes are physically stored in order (a btree actually, but basically), so if you are returning just the column that is stored in the index, you're still getting the same benefit. That is because the indexed column's actual value is stored in the index, therefore MySQL will use the index value instead of reading the record. However, if you start retrieving columns that aren't part of the index, this is where you'd also want the actual records stored in order, such as they are with a clustered index.
MySQL Documentation on clustered indexes

Accessing a row through the clustered
  index is fast because the row data is
  on the same page where the index
  search leads. If a table is large, the
  clustered index architecture often
  saves a disk I/O operation when
  compared to storage organizations that
  store row data using a different page
  from the index record. (For example,
  MyISAM uses one file for data rows and
  another for index records.)
In InnoDB, the records in nonclustered
  indexes (also called secondary
  indexes) contain the primary key
  columns for the row that are not in
  the secondary index. InnoDB uses this
  primary key value to search for the
  row in the clustered index. If the
  primary key is long, the secondary
  indexes use more space, so it is
  advantageous to have a short primary
  key.

MySQL Clustered and Secondary Indexes

A: The best example I can think of is a reporting table that is queried regularly on date of transaction(s). I would put a clustered index on the TransactionDate column and add any other required indexes based on query optimization.
So queries like select sum (amount) from transactiondetails where TransactionDate > 'jan 01 2010' and TransactionDate < 'feb 01 2010' will use the clustered index to do seeks and will come up with results in a more efficient way.

A: A real address book (a dead tree edition), ordered by first name, resembles a clustered index in its structure and purpose.
Clustered indexes can greatly increase overall speed of retrieval, but usually only where the data is accessed sequentially in the same or reverse order of the clustered index, or when a range of items are selected.
Since the physical records are in this sort order on disk, the next row item in the sequence is immediately before or after the last one, and so fewer data block reads are required.
Source: Wikipedia: Database Index - Clustered

A: Look here, half way down the page it says:

Accessing a row through the clustered
  index is fast because the row data is
  on the same page where the index
  search leads. If a table is large, the
  clustered index architecture often
  saves a disk I/O operation when
  compared to storage organizations that
  store row data using a different page
  from the index record. (For example,
  MyISAM uses one file for data rows and
  another for index records.)

speed sounds like an excellent reason to me .. or am missing your point?
The advantage of the clustered index is that it can be accessed (and thus searched through) with fewer io operations than 'normal' indexes. Knowing this you can optimize your DB accesses and thus your application, by placing the clustered index where it will benefit you most.


text:
Q: Do we have to use fact table for reports? I am working on building a data mart for reporting purpose.
I am new to this field and looking for help.
I have a fact table and two dimension tables.
The fact table has only 3 fields, its primary key and foreign key references to two dimension tables.
The two dimension tables have data related to 1)phonenumbers and 2)extension numbers.
(I cannot combine these dimension tables because they have different information)
As you see my fact table does not have any quantitative columns.
I want to generate a report that displays phonenumbers and corresponding extensions.
I can get this information by performing a join on the two dimension tables.
So my question is do I have to use fact table for the report? i.e Should I first get the key from phonenumber table, perform join on fact table, get extension key and perform join on extension table?
OR
Simply join the two dimension tables to generate the report because it is possible in this case?
Do we have to involve the fact table?
Thanks for reading.
Any help is appreciated.

A:
do I have to use fact table for the report? i.e Should I first get the key from phonenumber table, perform join on fact table, get extension key and perform join on extension table?

Often, this is necessary.

Simply join the two dimension tables to generate the report because it is possible in this case?

Sometimes, this works, also.

Do we have to involve the fact table?

Depends on the relationships.
If you have a "hierarchy" of dimensional information, then the two dimensions could be directly related.  In this case, the fact table doesn't tie them together.  The fact ties to the detailed dimension; the detailed dimension ties to the summary.  This is rare.
Dimensions change.
If you have two or more Slowly Changing Dimensions, then your dimensions may include lots of "previous" relationship information.
Fact 1: Phone xxx-xxx-xxxx, Extension yyyy
Fact 2: Phone xxx-xxx-xxxx, Extension zzzz

Then, another load applies an SCD rule to modify zzzz to aaaa, as of 7/1/11  You may have the old dimension values available, as well as the new dimension values, with an applicable date range.
Now, the fact (and the date range) are required to define which copy of the dimension value you're going to get.
Fact 2: Phone xxx-xxx-xxxx, Extension zzzz, from beginning to before 7/1/11.
Fact 2: Phone xxx-xxx-xxxx, Extension aaaa, from 7/1/11 to end.

So, you may need the fact, dimensions and time to sort out the relationships.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Search Documents from two collections in MarkLogic In Marklogic, I want to search between two collections by joining the id element of doc from collection1 to id element of doc from collection2. When it is matched i need the resulting document from both collections.
I have the below code, but it is very slow. How to use cts:search or search:search to achieve the same
for $i in collection('demographic')/individual,
    $j in collection('membership')/membership[enrolleIndividualId/id/text() = $i/individual/id/text()])
return {$i,$j}

A: Update:
I should note that your sample is not valid XQuery: return element root { $i, $j } would be valid. Also, you should not use the /text() node selector, as it's behavior can be counterintuitive. You can compare elements directly in an XPath predicate ([enrolleIndividualId/id eq $i/individual/id]). Use /fn:string() in place of /text() if you need the contents of an element as a string. I'd also recommend using the atomic equality operator eq in place of the sequence equality operator = when directly comparing individual elements.
Original Answer:
There are several approaches to implementing joins in MarkLogic, but I would first question your data model. From the names of the elements in your sample query, it looks like you are using a relational model (individuals have memberships). MarkLogic is a document database, and it's optimized for denormalized documents. You will be much better served to process your data and generate new individual documents that each contain the relevant membership data.
That being said, here's how you could join your documents:
First, you will need range indices to write performant joins. If the id element from your sample query is not unique to individuals, you will need path range indices on enrolledIndividualId/id and individual/id, otherwise, a simple element range index on id will do.
The most common join pattern in MarkLogic uses a "shotgun-OR" query; first retrieving values from the lexicon backing a range index, and then constructing an or-query from those values to retrieve the relevant documents. This won't work directly in your case, as you want to retrieve both sides of the join. You can either run a search for each pair of documents, or run a single search for one side, and then an additional document read for each document.
pairs:
for $value in cts:values(cts:path-reference("individual/id"))
return
  cts:search(/,
    cts:or-query((
      cts:and-query((
        cts:collection-query("demographic"),
        cts:path-range-query("individual/id", "=", $value))),
      cts:and-query((
        cts:collection-query("membership"),
        cts:path-range-query("enrolledIndividualId/id", "=", $value))))),
    "unfiltered")

shotgun-OR plus iteration:
for $doc in
  cts:search(/,
    cts:and-query((
      cts:collection-query("demographic"),
      cts:path-range-query("individual/id", "=",
        cts:values(cts:path-reference("individual/id"))))),
    "unfiltered")
return
  cts:search(/,
    cts:and-query((
      cts:collection-query("membership"),
      cts:path-range-query("enrolledIndividualId/id", "=", $doc/individual/id))),
    "unfiltered")

As you can see, each approach requires I/O proportionate to the number of docs/values you want to join. If you only needed the shotgun-OR (ie, a query for documents based on criteria from other documents), you would only need to make two requests, the initial cts:values() call to retrieve values from a lexicon, and the cts:search() call using a query built from those values.
Note: the cts:query objects used in these examples could be used in conjunction with the Search API by means of the search:resolve() function.
Given your apparent data model, you will be much better served by processing your data into individual, de-normalized documents.


text:
Q: Deleting a row in a table mysql hiberhate Deleting a row in a table delete(id) - id highlights red (… cannot be applied to (javafx.scene.control.TableColumn)
I want to delete a row from the database table.
               //delete button
            button_del.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEvent -> {

                int selectedIndex = tableView_tableAll.getSelectionModel().getSelectedIndex();
                if (selectedIndex >= 0) {
                    // tableView_tableAll.getItems().remove(selectedIndex);
                    delete(id);
                } else {
                    // Nothing selected
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setTitle("Ошибка");
                    alert.setHeaderText("No row selected for deletion");
                    alert.setContentText("Select row in table");
                    alert.showAndWait();
                }
            });
        }
    }

    private void delete(Integer id ) {
        Session session = utils.HibernateSessionFactory.getSessionFactory().openSession();
        session.beginTransaction();
        ProductEntity productEntity =(ProductEntity) session.get(ProductEntity.class,id);
        session.delete(productEntity);
        session.getTransaction().commit();
        session.close();
    }

A: ProductEntity selectedItem = tableView_tableAll.getSelectionModel().getSelectedItem();
delete(selectedItem.getId());

or remove deletion by the identifier and immediately delete through the entity
private void delete(ProductEntity entity)
...
ProductEntity selectedItem = tableView_tableAll.getSelectionModel().getSelectedItem();
delete(selectedItem);


text:
Q: php mysql sum if exists in another table How do I do this?
I have this table:
Table1
|--ID--|--Stars--|--Name--|
|   1  |    3    |  Pe    |
|   2  |    5    |  Me    |
|   3  |    7    |  Fe    |
|------|---------|--------|

Table2
|--ID--|--Teams--|--Age---|--Name--|
|   1  |    A    |  20    |  Pe    |
|   2  |    A    |  20    |  Me    |
|   3  |    A    |  20    |  Pe    |
|------|---------|--------|--------|

I want the sum of stars in Table1 where Name exists in Table2 and Teams=A and Age=20. (3+5=8stars)
I use this, but how do I only count the stars where the name in Table1 matches the name in Table2?
$result = mysql_query("SELECT SUM(Stars) AS starsum FROM Table1 WHERE EXISTS (select * from Table2 WHERE Teams = 'A' AND Age = '20')");
$row = mysql_fetch_assoc($result);
$antalstjernerhold = $row['starsum'];

A: Try this query
   SELECT SUM(t1.Stars) AS starsum
   FROM Table1 t1 INNER JOIN Table2 t2
   ON t1.Name=t2.Name AND t2.Teams='A' AND t2.Age=20

You have to use inner join to get desired results.

A: You can write your query this way:
SELECT SUM(Stars) AS starsum
FROM Table1 t1
WHERE
  EXISTS (
    SELECT *
    FROM Table2 t2
    WHERE
      T2.Name=T1.Name
      AND T2.Teams='A'
      AND t2.Age=20
  )

A: You can use the following code
$result = mysql_query("
SELECT SUM(Stars) AS starsum
FROM Table1
WHERE Name IN (
    SELECT DISTINCT t1.Name
    FROM Table1 t1, Table2 t2
    WHERE t1.Name = t2.Name
    AND t2.Teams = 'A'
    AND t2.Age = 20
)
");
$row = mysql_fetch_assoc($result);
$antalstjernerhold = $row['starsum'];

The query is using below subquery which will fetch the names belonging to both tables and have teams as A and Age 20 & then using those names we get the sum of stars
SELECT DISTINCT t1.Name
FROM Table1 t1, Table2 t2
WHERE t1.Name = t2.Name
AND t2.Teams = 'A'
AND t2.Age = 20


text:
Q: How to process a file in Perl - handling variables from Bash: disappearing "." character I need to find the age of a file in seconds but when I give my Perl line:
perl -e ' my @st=stat("$name"); print time -  $st[9];'

a variable from Bash with "." in the filename, it won't find the file and prints the systime instead. Otherwise, if I create a file with a name such "something", it works perfectly well.
I tried escaping the character with \ but that does not work. I really do not know Perl and I don't know how to figure this out.
Thanks for the help!
(Please, do not suggest any BASH only workarounds, lot of stuff here is old, truncated...)
EDIT: I found a workaround but I can't post an answer to my own question since I am a newbie, so here it is:
So I finally found a workaround.
You export the variable in Bash:
export name=".file.txt"

and then call it from the Perl like this: $ENV{name}
and it works just fine.
EDIT 2:
The export idea was just a temporary solution. Better one is using single quotes as perreal suggested.

A: You need to put the shell variable out of the single quotes:
perl -e ' my @st=stat("'"$name"'"); print time - $st[9];'

or pass it through arguments:
perl -se 'my @st=stat("$name"); print time - $st[9];' -- -name="$name"


text:
Q: Ordenar por subquery, hacer consulta con relaciones solo me trae un item en eloquent estoy obteniendo 4 usuarios.
esos 4 usuarios debe ser ordenados según los posts mas nuevos de cada usuario y que además esos posts tengan el estado de publicado, para eso estoy realizando un query de la tabla usuarios, donde:

al modelo User utilizo orderByDesc y le paso el modelo Post donde
hago otros filtros de state = published, al modelo de User le hago
un whereHas posts, ese whereHas tiene un filtro de state = published y
luego quiero obtener cada usuario con dos posts con state = published,
esos posts ordenados por updated_at de manera descendente

query resultante
        return User::query()
        ->orderByDesc(
            Post::select('updated_at')
                ->whereColumn('user_id', 'users.id')
                ->where('state', PostStateEnum::PUBLISHED)
                ->orderByDesc('updated_at')
                ->limit(1)
        )
        ->whereHas('posts', function ($query) {
            $query->where('state', PostStateEnum::PUBLISHED);
        })
        ->with('posts', function ($query) {
            $query->where('state', PostStateEnum::PUBLISHED)
                ->orderByDesc('updated_at')
                ->take(2)
                ->get();
        })
        ->take(4)
        ->get();

esto me devuelve un solo post por cada modelo de User que recibo, al imprimir dd($users[0]->posts) pero yo tengo muchos post en $users[0]
Como podría mejorar esta consulta?
Estoy usando Laravel 9


text:
Q: Interchangeable configuration files in Webpack I'm trying to bundle a react project that can run in multiple environments and needs different configurations to run on each one. I have it set up with browserify, but have recently been looking to move to webpack.
The idea goes like this: there's a js directory with a bunch of js files, of which main.js is the entry point. There is also a config folder with development.js, staging.js, production.js and so on. I am importing the configuration from all files using import config from './config'. So I want to be able to create a main.bundle.js file with all our code, and another config.js whose contents can be replaced with those of {environment}.js.
This allows us to choose the configuration for the app in deploy time, not at build time, just by copying over the contents of {environment.js}.
I have attempted to unsuccessfully use webpack's CommonsChunkPlugin, but it complains at bundle time that js/config.js is not there (obviously).

A: Why not make multiple builds, one with each config, and then deploy the one you want? There's different ways you could load the desired config for the build, but one very way would be to use the DefinePlugin to define constants for each environment, write a conditional against those constants to load the corresponding config, and let the Uglify plugin's dead code elimination pare down the conditional to the one valid case. I've used this approach in a number of places to handle per-environment conditionals without bloating the production code.


text:
Q: Multiple invalid stream header I have problems with ByteArray and Object streams. I'm creating a multiplayer card game via NIO server. I send the ArrayList private ArrayList<Card> cardsDropped through the method:
public void sendMessage(Object message) {
    if (message instanceof String) {
        messages.add(message + Config.MESSAGE_DELIMITER);
    } else {
        messages.add(message);
    }
    SelectionKey key = channel.keyFor(selector);

    key.interestOps(OP_WRITE);
}

With private final LinkedList<Object> messages that is the list of all objects sent in the stream through
-> Client methods:
protected void handleIncomingData(SelectionKey sender, byte[] data) throws IOException {
    ByteArrayInputStream byteObject = new ByteArrayInputStream(data);
    ObjectInputStream obj;
    in = null;

    try {
        obj = new ObjectInputStream(byteObject);   //HERE <--
        byteObject.close();
        in = obj.readObject();
        obj.close();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    handler.onMessage(in);
}

protected void write(SelectionKey key) {
    SocketChannel channel = (SocketChannel) key.channel();

    while (!messages.isEmpty()) {
        ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;

        try {
            oos = new ObjectOutputStream(byteObject);
            oos.writeObject(messages.poll());
            oos.flush();    //TODO ?
            oos.close();
            channel.write(ByteBuffer.wrap(byteObject.toByteArray()));
            byteObject.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    key.interestOps(OP_READ);
}

And Server methods:
protected void write(SelectionKey key) {
    ByteBuffer buffer = (ByteBuffer) key.attachment();
    SocketChannel channel = (SocketChannel) key.channel();

    try {
        channel.write(buffer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

protected void handleIncomingData(SelectionKey sender, byte[] data) throws IOException {
    for (SelectionKey key : selector.keys()) {
        if (key.channel() instanceof ServerSocketChannel) {
            continue;
        }

        if (key.equals(sender)) {
            continue;
        }

        key.attach(ByteBuffer.wrap(data));
        write(key);
    }
}

After some turns and cards sent, Client thread is sending me some "invalid stream header" here obj = new ObjectInputStream(byteObject);
Is this a problem related to how is the server/client code written? [The code is based on https://github.com/mpkelly/nio-chat ]
Thanks in advance!


text:
Q: Shouldn't "by the thousands" be "in the thousands"? I have this question about "in the thousands" and "by the thousands" here:

On Friday night, crowds swelled by the thousands in downtown Hong Kong to listen to speeches from organizers, signaling the pro-democracy movement still has momentum after calls for a big rally.

Shouldn't "by the thousands" be "in the thousands"?  Like, "people came in the thousands"?
If both "by the thousands" and "in the thousands" are valid English, how are they different?

A: In English one of the uses of "by" is to describe the quantities of batches.  It has two general forms.
First, in the most literal way, we would say that you can buy eggs by the dozen (dozen == 12); eggs come in cartons of 12 eggs each, you cannot buy arbitrary numbers of eggs, you can only buy them in cartons, each of which has twelve.  So at any given time, you can buy 12, 24, 36, etc.  We express this idea by saying that they are sold by the dozen.
Second, that locution has come to be used to indicate scale.  It is as if it implies, "these are the units you would find most convenient to count them in."  If someone says of a terrible famine, "people died by the score" (score == 20), they do not mean that people literally died in groups of twenty, but that approximately several or many twenties of people  died.  As a native speaker, I would understand that to mean approximately 80 +/- 40.  Or, for another example, "he smoked cigarettes by the pack" does not mean the smoker in question stuck twenty cigarettes in his mouth at once, but that he went through at least one, and possibly several, packs each day, or at least at a fast enough clip to recommend buying them more than one at a time.  If someone says "within weeks, they were selling the new flavor of jam by the ton", it doesn't usually mean the jam was sold in one ton increments, but that the total amount of orders would most naturally be indicated in tons.
With that explained, the passage you're asking about:

On Friday night, crowds swelled by the thousands in downtown Hong Kong to listen to speeches from organizers

is using the latter sense.  It was not the case that batches of one thousand people were showing up together, but rather some unspecified quantity of people showed up, which was some amount best represented by an approximation of a smallish integer and three zeros.

A: "People came in the thousands" means that thousands of people came.  "People came by the thousands" means the same thing, and is equally valid English.
"Crowds swelled by the thousands" means that the size of the crowd increased by thousands of people.  The word by is used to compare the size of the crowd before-versus-after the crowd "swelled".
"Crowds swelled in the thousands" is not correct English.

A: Crowds swelled by the thousands suggests that if you were counting the people coming in, you'd have to count them in groups of a thousand or more at a time to have an easy-to-count number of groups. This is a rather inexact measurement.
Crowds swelled in the thousands does not sound right, I'd guess it's non-standard English. Sometimes grew in the thousands is used, but means grew to the thousands, which is the same meaning as:
Crowds numbered in [or grew to] the thousands means that the total number of people in the crowd would be measured in the thousands. It does not suggest whether the crowd grew quickly or slowly.
To be more concise: by [unit]s suggests growth, in [unit]s suggests an end count.


text:
Q: Picturebox colour depending on a variable I want to begin with the fact I'm VERY new to coding, and I don't know a lot of stuff. I lack any real code to show for this question, I hope a question will do.
Anyway, I'm to make a simple game in windows forms. Without heading into details, my idea requires 36 colored squares. I guess empty pictureboxes will do.
The question is, how do I make the picturebox be one of four colours depending on a variable, and then change with a button click?
Like if a variable X is equal to 1, then colour of picturebox is black, if it's 2 it's green.
Is it possible?

A: It's possible of course. You have at least 2 possible ways to do this:

*

*Solution:
Save the color (or the number) of all PictureBoxes in an array or list. Update the values when you press the Button, and loop through all PictureBoxes.

*Solution:
Create a new object containing the PictureBoxes and add a method to change the color. Now create a list of all the PictureBox objects and change the values if you press the Button.
Edit:
Here is the code to create a list of Panels:
            List<Panel> PanelList = new List<Panel>();
        for (int i = 0; i < 36; i++)
        {
            Panel p = new Panel();
            p.Name = ($"Panel{i}");
            p.BackColor = Color.Black;
            PanelList.Add(p);
        }

Ah and take a Panel; a PictureBox is "too much".


text:
Q: Model Viewer API works for BIM 360 hub but not an ACC Hub? We are running a custom application where we use the Forge OAuth as well as the Model Viewer APIs. The viewer is working against projects in BIM 360 but not against project in the newer ACC hubs.  Any reason for this? Our application identifies the model in the project (BIM 360 File URN) and then the Revit element GUID.  Any insight is appreciated!

A: Updates:
It was caused by an incorrect URN and another Forge Help agent has helped resolve the problem.
==========
I had you raise a Forge Help ticket, and replied to you. It sounds like you forgot to set up the custom integrations for your ACC account. Please follow the instruction here to provision your client id in ACC.
https://petrbroz.github.io/forge-samples-docs/docs/intro/#provision-access-in-other-products

A: For me, the issue lied with having an incorrect configuration for the Forge Viewer. The app was already over 2 years old, and used an old method to load OTG (SVF2) files using the so-called 'fluent' API, which apparently only still worked for BIM360, not ACC.
I had the following:
var options = {
    env: 'FluentProduction',
    api: 'fluent', // for models uploaded to EMEA change this option to 'streamingV2_EU'
};

Which should be:
var options = {
    env: 'AutodeskProduction2',
    api: 'streamingV2', // for EU/EMEA change to 'streamingV2_EU'
};

Or, if you want the SVF2 format:
var options = {
    env: 'MD20ProdEU',
    api: 'D3S', // for EU/EMEA change to 'streamingV2_EU'
};

Sources: Autodesk Tutorial & Autodesk Blog Post


text:
Q: Converting Open-Drain to Active-High (low voltage, low power) In my design, I need an RTC (PCF85263A) to enable a boost converter (TPS61021A) after the RTC alarm triggers an interrupt. The interrupt pin on the RTC (INTA) is open-drain, but the enable pin on the boost converter (EN) is active-high. This is a problem.
When the alarm triggers the interrupt on the RTC, the INTA line is held at 0V, and when the interrupt isn't active, INTA is high-impedance. However, I need it the other way around: the EN pin needs to be held up to battery voltage when the alarm interrupt is active.
My first guess is to use an N-channel MOSFET logic inverter to achieve this. The input, of course, would have a pull-up resistor to VCC.

simulate this circuit – Schematic created using CircuitLab
However, the battery voltage VCC can go as low as 0.9V in this design. Another important requirement is that the power consumption be as low as possible while the RTC is "sleeping" - before the alarm triggers an interrupt. The RTC uses 300nA and the boost converter has a shutdown current of 500nA, so my power budget can take about 1-2μA more during sleep.
As such, I am not sure if this MOSFET inverter will be the most power-friendly option. Additionally, a MOSFET might not be the right choice for such low voltage - I assume that I must browse for VGS/VCE/VSAT choices at or below 0.9V.
What would be a power-friendly transistor choice to convert an open-drain, active-low output signal into an active-high signal for an input pin?
My design originally used the TPL5111 power gating timer instead of an RTC. It has a proper push-pull, active-high enable pin to wake the boost converter. Unfortunately, it can only "go to sleep" for up to 2 hours at a time. I thus want to migrate to an RTC so that my device can sleep for days or months instead; having the device wake up is a power-costly operation.
Edit: This PNP solution forgoes a pull-up at INTA. Credit to Tim Wescott.

simulate this circuit

A: The circuit simulator isn't working for me today (grr).
PNP.  Emitter to +V, base to RTC through a resistor (100k\$\Omega\$?).  Collector to boost converter, with resistor to ground (same as base resistor).  Size the resistor for a happy medium between turning on & off reliably, and not consuming too much current.  It should consume very little current when off.


text:
Q: Pycharm not showing the true plot generated I'm trying to generate a plot with no space between the subplots. I couldn't get it to work until I checked the saved figure and it turns out it had been working, but the plot Pycharm brings up is not the same as the plot saved.
This is a matplotlib example (https://matplotlib.org/3.2.1/gallery/subplots_axes_and_figures/ganged_plots.html) word for word. The image shown in the Pycharm interface and the one saved using plt.savefig are different.
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)

s1 = np.sin(2 * np.pi * t)
s2 = np.exp(-t)
s3 = s1 * s2

fig, axs = plt.subplots(3, 1, sharex=True)
# Remove horizontal space between axes
fig.subplots_adjust(hspace=0)

# Plot each graph, and manually set the y tick values
axs[0].plot(t, s1)
axs[0].set_yticks(np.arange(-0.8, 1.0, 0.4))
axs[0].set_ylim(-1, 1)

axs[1].plot(t, s2)
axs[1].set_yticks(np.arange(0.1, 1.0, 0.2))
axs[1].set_ylim(0, 1)

axs[2].plot(t, s3)
axs[2].set_yticks(np.arange(-0.9, 1.0, 0.4))
axs[2].set_ylim(-1, 1)

plt.show()

Is this a known bug with Pycharm? My Pycharm version is 2020.2.3 and I'm using python 3.8.


text:
Q: Finding index in array based on DIV text I have a DIV which has text in it:

  divText

I have a "header row" like this:
var headerRow = ["wrong","wrongAgain","divText"];

I also have an array like this:
var theArray = [["blah","blah","0"]["notIt","blahblah","1"],["unrelated","dontLook","0"]];

I want to find the index in theArray (2) based on the text within the div:
var theDiv = x.innerHTML;
for (i=0; i < headerRow.length; i++){
    if (headerRow[i] == theDiv){        <--never works
    if (headerRow[i] == x.innerHTML) {  <---never works
    if (headerRow[i] == "divText") {     <--works (i = 2)
}

How can I find the index based on the innerHTML of a div / variable (first two cases above)? Thanks!

A: You are using innerHTML where as which returns content of HTML element including spaces and new lines.Instead use innerText or use methods trim method on either innerHTML or textContent.
In your case the comparision is not successful because the text that you are extracting using innerHTML contains spaces and newline.

Note:If element ID is valid identifier it can be used directly as
  window.elementid  or just elementid but it's best practice to use getElementByID

var x = document.getElementById('x')
var theDiv = x.innerHTML.trim();
for (i=0; i < headerRow.length; i++){
    if (headerRow[i] == theDiv) {
              // your codes goes here
              console.log('works')
    }
}

or You can use
var theDiv = x.innerText

or
var theDiv = x.textContent.trim()

A:

    divText

Your if comparison doesn't work because of extra whitespace/new line in the div's innerHTML text. Thus you need to trim the string before comparing it with the contents of the header row array. Note that you can either use the indexOf method to get the index of the matching element, or you can just use the current value of i, which would also correspond to the index of that element. Hope this makes sense to you.

A: To get the text from div you should get element by id first
var theDiv = document.getElementById("x").innerHTML

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
It will work with 1sth array, and the 2nd nested array can be flattened first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat


text:
Q: Confused about where android stores my files. SDCard or internal storage? I've done a procedure to backup/restore user's DB into an external SD card. Theoretically it works fine, the file is being copied and restored every time I launch it.
What I don't understand is WHERE that file is copied. According to the message I receive when I do my backup, the archive is put inside "\storage\emulated\0" folder.
But .. Where is that folder? According to the documentation that should be my SD folder but actually, watching on my phone, that directory is INSIDE my phone's internal memory and that file is not present inside my SD card.
I even tried this path to understand where Android sees my SD :
     String state = Environment.getExternalStorageState();
     File sdPath = Enviroment.getExternalStorageDirectory();

*** The results are:***
- state : Mounted (so the SD can be read and written)
- sdPath: \storage\emulated\0

So, once again, the SD seems ok, can be written... but why It keeps writing on my internal phone's memory?

A: The path to SD Card is usually \storage\extSdCard\YourDir
You can get it By  :
String sdCardPath= System.getenv("SECONDARY_STORAGE");

A: Android take Mobile Storage as External Storage and Storage where application data stored as Internal Storage.
Devices which does not provide internal storage

A: If you write code like this then you can see your db files in your mobile inside sdcard
public DataBaseHandler(Context context)
    {
        super(context,"/sdcard/Folder/"+DATABASE_NAME,null,DATABASE_VERSION);
    }

One folder will be created inside your mobile sdcard, you can check. If it is just a file then change the extension with .db. After that copy it to desktop and open the sqlite browser, then click on open database, open this file and in sqlite browser you can see one option "browse". Now you can see your data is inserted or not. Enjoy !


text:
Q: How to change font color offsetbox TextArea from matplotlib.offsetbox import TextArea
rc('font',**{'family': 'Courier New, monospace', 'size' : 26})

fig, ax = plt.subplots()
txt = TextArea("Hello World!")
text = AnnotationBbox(txt, (0, 0, 0))
ax.add_artist(text)

Is there any way to change the colour of this text ?
Thank you !

A: The Textarea has an argument textprops which can be used to set the color of the text.
import matplotlib.pyplot as plt
from matplotlib.offsetbox import TextArea, AnnotationBbox

fig, ax = plt.subplots()
txt = TextArea("Hello World!", textprops=dict(color="crimson"))
text = AnnotationBbox(txt, (0.5, 0.5))
ax.add_artist(text)

plt.show()


text:
Q: How to play a sound file in a java game ok, Ive looked through some related questions but did not quite find exactly what i was looking for. Im making a small game in java with a spaceship that shoots a laser at enemies. uses graphics and KeyListener for keyboard input. I just want it to play a .WAV file clip when they press SPACE to shoot. Could I put the code for it in the if statement for VK_SPACE? Here's some of the code I have for the "Craft" class that controls input.
package Operation.Supernova;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;

public class Craft {

private String craft = "Craft.png";

private int dx;
private int dy;
private int x;
private int y;
private int width;
private int height;
private boolean visible;
private Image image;
private ArrayList lasers;

public Craft() {
    ImageIcon ii = new ImageIcon(this.getClass().getResource(craft));
    image = ii.getImage();
    width = image.getWidth(null);
    height = image.getHeight(null);
    lasers = new ArrayList();
    visible = true;
    x = 40;
    y = 60;
}

public void move() {

    x += dx;
    y += dy;

    if (x < 1) {
        x = 1;
    }

    if (y < 1) {
        y = 1;
    }
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}

public Image getImage() {
    return image;
}

public ArrayList getLasers() {
    return lasers;
}

public void setVisible(boolean visible) {
    this.visible = visible;
}

public boolean isVisible() {
    return visible;
}

public Rectangle getBounds() {
    return new Rectangle(x, y, 1400, 750);
}

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_SPACE) {
        fire();
    }

    if (key == KeyEvent.VK_LEFT) {
        dx = -2;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 2;
    }

    if (key == KeyEvent.VK_UP) {
        dy = -2;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 2;
    }
    }

    public void fire() {
    {
      lasers.add(new Laser(x + width, y + height / 2));
    }
}
public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_RIGHT) {
        dx = 0;
    }

    if (key == KeyEvent.VK_UP) {
        dy = 0;
    }

    if (key == KeyEvent.VK_DOWN) {
        dy = 0;
    }
}
}


text:
Q: i want use while loop in my-sql I have already using below code in SQL Server it is working fine, the same code I'm trying to use in mysql but i got error message

1064-you have an error in you sql systex; check the manual that corresponds to you mysql server version for the right systax to use Near'Declare @var Table (quantity int, width varchar(255) ) Insert @var Select at line 1

Declare @var Table
    ( quantity int, width varchar(255) )
Insert @var
SELECT DISTINCT
    vtiger_inventoryproductrel.quantity, vtiger_inventoryproductrel.width
From
    vtiger_inventoryproductrel

Declare @var1 Table
    ( quantity int, width varchar(255) )

Declare @Order_Item_Id varchar(10),@Qty int
Set @Order_Item_Id = ''
While @Order_Item_Id < (Select Max(id) From @var)

Begin
    Select @Order_Item_Id= Min(id) from @var where id > @Order_Item_Id
    Select @Qty = quantity From @var Where id = @Order_Item_Id
    While @Qty>0
    Begin
        Set @Qty = @Qty-1
        Insert into @var1 select * From @var Where id = @Order_Item_Id
    End
End

Select * From @var1

A: MySQL is not Microsoft SQL Server.
They have very different stored procedure languages.  In many ways, MySQL's stored procedure language is limited and less featureful compared to that of Microsoft.  Most users of MySQL don't write stored procedures at all, preferring to write business logic in the application layer in PHP, Ruby, Python, Java, C#, or other favorite language.
Here are a few points related to your example procedure:

*

*MySQL has no Table type.  You can't declare a variable as Table.

*Use SET to assign a value to a variable in a statement, not INSERT.

*Use SELECT...INTO to assign the result of a query to a variable.

*Each statement in a stored procedure needs a semicolon (;) terminator.

*You can't SELECT ... FROM @var.  Variables are not supported as table names.  You can do this by concatenating @var into a string, and then using that string as a prepared statement.
That's not a complete list of what you would need to change to get this procedure to work in MySQL, it's just a sample of the differences.

A: create a temporary table in mysql
create temporary table var( quantity int, width varchar(255) );
create temporary table var1(quantity int, width varchar(255));

insert data to temporary table
insert into var(quantity, width )
SELECT DISTINCT vtiger_inventoryproductrel.quantity, vtiger_inventoryproductrel.width From vtiger_inventoryproductrel

To read data from mysql table not be used while, cursor used.
Mysql Cursor Usage
also the temporary table in the var no contain column id


text:
Q: How can I change dialog title color in jquery ui? I have something like this:
$div = $('
');
$div.append('
Hi
');

$div.dialog({
    modal: true,
    maxHeight:500,
});

Can i change background color of dialog title somehow like this?:
 $div.dialog({
        modal: true,
        maxHeight:500,
    }).find(".ui-dialog-titlebar").css("background-color","red");

A: Use prev() instead of find() because that element is not inside $div:
$div.dialog({
    modal: true,
    maxHeight:500,
}).prev(".ui-dialog-titlebar").css("background","red");

Also I use background to override all other elements like background-image
Check this http://jsfiddle.net/Ad7nF/

A: Another method to do is to :
Define your styling class - myTitleClass
Define the css as
  . myTitleClass .ui-dialog-titlebar {
          background:red;
    }

and add the custom class to the dialog initialization function :
     $( "#dialog" ).dialog({
        autoOpen: false,
        dialogClass: 'myTitleClass'
     });

JSFiddle - (but with another sample code)
http://jsfiddle.net/khVYj/3/

A: Most simple way is this: -
.ui-dialog-titlebar {
      background:red;
}


text:
Q: Is there a convention for when to use synchronous functions in Node.js? I am making some modules in Node.js and wondered: "Is there a convention for when to use return statements in Node.js?".
From what I understand return statements should be avoided since they would make the process a blocking operation, but is there a guideline to when they should be used, and when one should stick to callbacks?

A: Whether something is "Blocking" or not is up to you -- does it take much time?
Any IO operation should be considered blocking, as it relies on something outside the script (which could take any amount of time).
If your own script were to say, loop over something a couple hundred times (And you know this to take more than a fraction of a second) you might consider it blocking.

*

*If a method is blocking, it should accept a 'callback' parameter, and
call that asynchronously.

*If a method is non-blocking, it should not
accept a 'callback' paramater, and should have at least one 'return'
statement.

Your convention should simply be that you know a function is asynchronous because it accepts a callback.

A: If it's a "cheap" operation, that's perfectly fine. Any operations which are performed multiple times where you're not doing CPU-intensive operations can (and often should) be refactored into a "normal" function. This is fine:
function add(x, y) { return x + y; }

This is not:
function fib(n) {
    if (n <= 1) return 1;
    // this may take a long time if n is large
    return fib(n - 1) + fib (n - 2);
}

A possible implementation of fib would take a function to return the result as a parameter, and spread the calculation over multiple calls. Something like the code below, from the book "Node Web Development":
function fib(n, done) {
    if (n <= 1) {
        done(1);
    } else {
        process.nextTick(function() {
            fib(n - 1, function(val1) {
                process.nextTick(function() {
                    fib(n - 2, function(val2) {
                        done(val1 + val2);
                    });
                });
            });
        });
    }
}

Where the thread wouldn't be blocked for long.
Yes, a better alternative would be to implement fibonacci in the iterative way, not the recursive one. But this is just to demonstrate how one could "split" a CPU-heavy function.


text:
Q: Query has no destination for result data My question is two fold. First, I have to evaluate the version of PostgreSQL in order to run the correct query. I have some servers running PostgreSQL 8.* and they have issues with using DO in my query below. The servers I have running 9.* (mostly I use a 9.2 server) are giving me an error "query has no destination for result data", when all I want is a print out of the select statement.
My query:
DO
$BODY$
BEGIN
IF (SELECT setting from pg_settings where name = 'server_version') >= '9.2' THEN
    SELECT pg_database.datname AS Database_Name, pg_authid.rolname AS Database_Owner,
    pg_authid.rolsuper AS IsSuperUser, pg_tablespace.spcname AS TableSpaceName,
    pg_catalog.pg_tablespace_location(pg_tablespace.oid) AS TableSpaceLocation
    FROM pg_database
    JOIN pg_authid on pg_database.datdba = pg_authid.oid
    CROSS JOIN pg_tablespace
    WHERE datistemplate = false
    AND pg_database.dattablespace = pg_tablespace.oid;
ELSE
    SELECT pg_database.datname AS Database_Name, pg_authid.rolname AS Database_Owner,
    pg_authid.rolsuper AS IsSuperUser, pg_tablespace.spcname AS TableSpaceName, pg_tablespace.spclocation AS TableSpaceLocation
    FROM pg_database
    JOIN pg_authid on pg_database.datdba = pg_authid.oid
    CROSS JOIN pg_tablespace
    WHERE datistemplate = false
    AND pg_database.dattablespace = pg_tablespace.oid;
END IF;
END;
$BODY$

So, if DO doesn't work pre-9.0 and I'm getting the error post 9.0 I'm kinda stuck on what I can do to satisfy both conditions.

A: The DO statement cannot return or output any data. The manual page for DO describes it thus:

The code block is treated as though it were the body of a function with no parameters, returning void.

Note that a function here is not like a stored procedure in other DBMS's: you cannot "output" a result set half-way through the function, but must explicitly return some particular value. To get a result set, you define the return type as SETOF something, and can then run SELECT * FROM some_set_returning_function('some_param');
Additionally, the DO statement was only added in Postgres 9.0, so testing for earlier versions inside such a statement is, as you have found, not going to work.
What you will need to do is either shift the procedural logic (the IF) into the calling application, or write a complete pl/pgSQL function for all or part of your query. If you make it return a SETOF RECORD you can use RETURN QUERY SELECT ... and put the whole query inside the body of the function. If you need to support Postgres 8.2 or lower, you will need to use a loop and RETURN NEXT instead.
Incidentally, note that PostgreSQL folds column names to lowercase on output unless explicitly quoted, so for instance TableSpaceLocation will return to your application as tablespacelocation. I would strongly recommend you use all-lowercase underscore-separated identifiers throughout to avoid confusion, e.g. table_space_location. If you must preserve case, use double quotes to escape the exact string, e.g. "TableSpaceLocation"; this is then treated as a distinct identifier from the unquoted or all-lower-case version.


text:
Q: Combination of smartphone's pattern lock. Note: Please do not mark this question as duplicate of Combination of smartphones' pattern password because no answer given there is correct and I have an extra question related to it.
This is a smartphone Pattern lock.

The rules are as follows:
1. At least 4 nodes should be selected.
2. The pattern should be continuous.
3. Cycles are not allowed.
4. Any node cannot be revisited.
So, if we choose only four nodes. The number of arrangements are $^9P_4$.
If we choose five, the number of arrangements are $^9P_5$ and so on.
But the total number of possible combinations is not $^9P_4 + ^9P_5 + ^9P_6 + ... + ^9P_9$.
The problem is here, that, if we choose an arrangement in which while connecting two points we go over another point, we are counting it twice. For example, if we choose the four point in the corners and join them cyclically, it goes over three more points so it comes under $^9P_4$ and also under $^9P_5$, $^9P_6$ and $^9P_7$.
What shall I do to remove these extra configurations? Is there any other problem with my method?


text:
Q: Waiting to volley response to arrive before returning it's response I built a login system that checks the input of the user and checks with the data if he can log in.
The server side of the application is working fine but I'm not able to stop the main thread of the application and wait for the response to arrive.
basically I'm using Volley library to communicate with my server. first of all, is send the username to check if such one even exists in the database, secondly, I check the combination of the password and username. and if these checks are fine I receive the user unique id which the user needs for the rest of the app.
This is the code that handles the java login process:
    public void toMainLobby(View view)
    {
        if(LoginIsValid()) //check if the user can log in
        {
            getUserID();
        }
    }

    /**
     * the function checks if the login details are correct
     * @return boolean whether the login details are correct
     */
    private boolean LoginIsValid()
    {
        pop_up_message.setText("");

        //check if the fields are empty
        if(username.getText().toString().equals("") || password.getText().toString().equals(""))
        {
            pop_up_message.setText("Please fill all fields");
            return false;
        }

        resetBooleans();

        Log.d("FinalDebug","send the request");

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                checkIfUsernameIsTaken(new VolleyCallBack() {
                    @Override
                    public void onSuccess() {
                        Log.d("FinalDebug","on success");
                    }
                });
            }
        });
        thread.start();

        waitForResponse();

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(!flag)
        {
            pop_up_message.setText("Username doesn't exist");
            return false;
        }

        resetBooleans();

        checkLogin(new VolleyCallBack() {
            @Override
            public void onSuccess() {
                hasChanged = true;
            }
        });

        waitForResponse();

        if(!flag)
        {
            pop_up_message.setText("Password incorrect");
            return false;
        }
        return true;
    }

    public void getUserID()
    {
        StringRequest getuserid = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if(jsonObject.has("ID"))
                    {
                        String value = jsonObject.getString("ID");
                        String newvalue = value.substring(2,value.length() - 2);
                        if(!newvalue.equals("0"))
                        {
                            id =  Integer.parseInt(newvalue);
                            Toast.makeText(getApplicationContext(),newvalue,Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(getApplicationContext(),iJam_Main_Lobby.class);
                            intent.putExtra("username",username.getText().toString());
                            intent.putExtra("id", id);
                            startActivity(intent);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("type_of_request","GET_USER_ID");
                hashMap.put("username",username.getText().toString());
                return hashMap;
            }
        };
        MySingelton.getInstance(this).addToRequestQueue(getuserid);
    }

    //private methods
    private void checkLogin(final VolleyCallBack volleyCallBack)
    {
        StringRequest checkLog = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if(jsonObject.has("isValid"))
                    {

                        String ans = jsonObject.getString("isValid"); //extracts the isValid value
                        //checks the response
                        String newString = ans.substring(1,ans.length() - 1);
                        Toast.makeText(getApplicationContext(),"login response: " + newString,Toast.LENGTH_LONG).show();
                        Log.d("result from server",newString);

                        if(!newString.equals("true"))
                        {
                            flag = false;

                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                volleyCallBack.onSuccess();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("type_of_request","LOGIN");
                hashMap.put("username",username.getText().toString());
                hashMap.put("password",password.getText().toString());
                return hashMap;
            }
        };
        MySingelton.getInstance(this).addToRequestQueue(checkLog);
    }

    private void resetBooleans()
    {
        flag = false;
        hasChanged = false;
    }

    private void checkIfUsernameIsTaken(final VolleyCallBack volleyCallBack)
    {
        StringRequest checkUsername = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    if(jsonObject.has("isValid"))
                    {

                        String ans = jsonObject.getString("isValid"); //extracts the isValid value
                        //checks the response
                        String newString = ans.substring(1,ans.length() - 1);
                        Toast.makeText(getApplicationContext(),"Response about username existence: " + newString,Toast.LENGTH_LONG).show();
                        Log.d("result from server",newString);
                        if(newString.equals("true"))
                        {
                            flag = true;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                hasChanged = true;
                volleyCallBack.onSuccess();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("type_of_request","CHECK_USERNAME_EXISTENCE");
                hashMap.put("username",username.getText().toString());
                return hashMap;
            }
        };
        MySingelton.getInstance(this).addToRequestQueue(checkUsername);
    }

    private void waitForResponse()
    {
        for(int i = 0; i < 10; i++)
        {
            if (!hasChanged)
            {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else
            {
                return;
            }
        }
        return;
    }

}

*disclaimer - the toasts and the log.d lines are for debugging purposes.


text:
Q: Why does DLookup not return the values updated during a transaction? I am using transactions in my MS Access VBA code. I update one of my fields, the Incoming_Pieces field in my Inventory table. Then, before committing the transaction, I use DLookup on the updated field. The DLookup function will return the value before the transaction, not the value updated during the transaction before committing.
Is this intended? There's no error message or any warning that the data I am retrieving is out of sync with the data being updated within the transaction.
Is the only workaround to generate a SELECT statement instead of DLookup?
Here's my testing code to prove this.
Public Function testTransaction()

    Dim pieces As Variant
    pieces = DLookup("Incoming_Pieces", "Inventory", "Code='MT-1-1000x1x1'")
    Debug.Print (pieces)    ' <------------ prints 0

    DAO.DBEngine.BeginTrans

    Dim sql As String
    sql = "UPDATE Inventory SET Incoming_Pieces = 10 WHERE Code='MT-1-1000x1x1'"
    CurrentDb.Execute (sql)
    pieces = DLookup("Incoming_Pieces", "Inventory", "Code='MT-1-1000x1x1'")
    Debug.Print (pieces)    ' <------------ prints 0

    DAO.DBEngine.CommitTrans

    pieces = DLookup("Incoming_Pieces", "Inventory", "Code='MT-1-1000x1x1'")
    Debug.Print (pieces)    ' <------------ prints 10

End Function

A: DLookUp is executed in the application scope, while BeginTrans only affects the database engine scope, and only DAO.
In queries, we can make distinctions between 2 scopes:

*

*Application. These queries can make use of user-defined functions and can refer to form-based parameters (such as WHERE MyField = Forms!SomeForm!SomeControl).

*Database engine (DAO/ODBC/Others): These queries can't refer to anything happening in the application, so can't use functions defined in VBA nor form-based parameters, but are affected by transactions if the connection/workspace they operate on starts one.

If we want to query what's happening inside a transaction, we need to be in the same scope. This means you need to rewrite your DLookUp to use recordsets.
pieces = CurrentDb.OpenRecordset("SELECT Incoming_Pieces FROM Inventory WHERE Code='MT-1-1000x1x1'")(0).Value

An even more minimal example to demonstrate this:
DAO.DBEngine.BeginTrans
CurrentDb.Execute "INSERT INTO Table1(Field1) VALUES(1)"
Debug.Print CurrentDb.OpenRecordset("SELECT COUNT(*) FROM Table1")(0) 'Prints 1 assuming the table was empty
Debug.Print DCount("*", "Table1") 'Prints 0
DAO.DBEngine.Rollback


text:
Q: How to run another serve after node server has started using shell script? I want to write a script which basically runs my node server first and after only node server has started I want to run another script. How can I implement this using shell script?
Right now I have done this so far
echo "Going inside NodeServer folder";
cd ./../Server-Node
echo "Starting Node Server";
npm start
echo 'Going inside Project Folder';
cd ./../ionicApp
ionic serve

A: A simple hack is to use npm start & add a sleep 15 on the line after it (or adjust accordingly to the avg time the start takes).
Note: to terminate the node process you might have to run a command to kill it stop all instances of node.js server
Otherwise you'll want to look at some stuff here NPM run parallel task, but wait until resource is available to run second task

A: I found out this later. adding modified script
echo "Going inside Server-Node";
cd ./../Server-Node
echo "Starting Node Server";
npm start & echo OK
echo 'Going inside ionic-Project';
cd ./../learn-ionic
echo 'Starting ionic server';
ionic serve


text:
Q: \pause in tikzpicture breaks footline I've discovered that you can \pause within a tikzpicture, which works well until I switched the theme to one with a footline.
I've created a "test case" that illustrates the problem.
\documentclass{beamer}
\providecommand\thispdfpagelabel[1]{} % Not sure what this does but our installation requires it.
\usepackage{tikz}
\usetheme{Madrid} % Has a footline.

\begin{document}
  \begin{frame}
    \frametitle{test}
    \begin{tikzpicture}
      \node at (0, 1) {Hello};
      \pause
      \node at (0, 0) {World};
    \end{tikzpicture}
  \end{frame}
\end{document}

This creates two slides, but the footline is only drawn on the second (the headline/title appears on both). Is there anything I can do about this?

A: I just stumbled over this issue and found another work-around that does not require nesting lots of paused elements in braces: Add \onslide<1-> at the end of the tikzpicture environment (strangely it does not work if you put it after the environment):
\documentclass{beamer}
\providecommand\thispdfpagelabel[1]{} % Not sure what this does but our installation requires it.
\usepackage{tikz}
\usetheme{Madrid} % Has a footline.

\begin{document}
  \begin{frame}
    \frametitle{test}
    \begin{tikzpicture}
      \node at (0, 1) {Hello};
      \pause
      \node at (0, 0) {World};
      \onslide<1->
    \end{tikzpicture}
  \end{frame}
\end{document}

A: I think the problem is that \pause isn't smart enough. The footline appears in the following:
\documentclass{beamer}
\providecommand\thispdfpagelabel[1]{} % Not sure what this does but our installation requires it.
\usepackage{tikz}
\usetheme{Madrid} % Has a footline.

\begin{document}
  \begin{frame}
    \frametitle{test}
    \begin{tikzpicture}
      \node at (0, 1) {Hello};
\onslide<2->{\node at (0, 0) {World};}
    \end{tikzpicture}
  \end{frame}
\end{document}

That is, if you put your text to appear on the second slide in a \onslide<2->{} it will work. Or for a little more automation, use \onslide<+->{} which automatically increments things.
Not quite as intuitive as the pause command, but it does allow you more control...

A: No guarantees that this won't break something else, but you could try this patch:
\documentclass{beamer}
\usepackage{tikz}
\usetheme{Madrid}
\AtEndEnvironment{tikzpicture}{\onslide<1->}
\begin{document}
  \begin{frame}
    \frametitle{test}
    \begin{tikzpicture}
      \node at (0, 1) {Hello};
      \pause
      \node at (0, 0) {World};
    \end{tikzpicture}
  \end{frame}
\end{document}


text:
Q: How to iterate over two lists at once in ocaml? Suppose I had the following two lists:
    let a = [1;2;3;4];;
    let b = [1;3;5;7];;
and I wanted a third list containing the index-wise sum of a and b; i.e
    let c = [2;5;8;11];;
The question is how would I do this using only functions from List.fold_right, List.fold_left and/or List.map?  (This is a homework problem, so I'm not allowed to use recursive functions or @.)

A: Since this is a homework problem, we can really only give hints.
Let's say you wanted to use List.map. The type of List.map is ('a -> 'b) -> 'a list -> 'b list. In other words, it works on one list. If you want to use it to solve your problem, you'll have to find your own way to combine your two lists into one list. You can't use List.map to do this, and whatever you do to combine the lists could probably just as well do the addition for you. So this doesn't seem promising.
Now let's say you wanted to use List.fold_left. The type of List.fold_left is('a -> 'b -> 'a) -> 'a -> 'b list -> 'a. The great thing about a fold is that it allows you to carry along arbitrary cumulative state of type 'a. And it allows you to perform arbitrary modifications to this cumulative state as you work through your list.
It seems to me you could treat one of your lists as part of this cumulative state as you work through the other list with your fold.

A: The map2 function does this:
let c = List.map2 (fun i j -> i+j) a b;;

A: (* with fold_left and  @ *)
let (_,c)=
  List.fold_left( fun (iPos,la) ia ->
    (iPos+1,la@[ia+List.nth b iPos])
  ) (0,[]) a ;;

(* with fold_left and without @ but rev *)
let (_,c)=
  List.fold_left( fun (iPos,la) ia ->
    (iPos-1,ia+List.nth b iPos::la)
  ) (List.length b-1,[]) (List.rev a);;

(* with fold_left and without @ *)
let (_,c)=
  List.fold_left( fun (iPos,la) _ ->
    (iPos-1,List.nth a iPos+List.nth b iPos::la)
  ) (List.length b-1,[]) a

(* with fold_right *)
let (_,c)=
  List.fold_right( fun ia (iPos,la) ->
    (iPos-1,ia+List.nth b iPos::la)
  ) a (List.length b-1,[])  ;;

(* with map *)
let c=
  let riPos=ref (-1) in
  List.map ( fun ia ->
    riPos := !riPos+1;
    ia+List.nth b !riPos
  ) a ;;

(* with mapi *)
let c=
  List.mapi ( fun iPos ia ->
    ia+List.nth b iPos
  ) a ;;

(* with map2 *)
let c=List.map2 (+) a b;;


text:
Q: PHP 5 and "& new" this statement:
$node_obj =& new someClass($somearg, $moreargs);

generate an error in the latest version of PHP right?
I have tried it on my machine (PHP >= 5.0.0 & <=5.2.17) and I get this error:

Deprecated: Assigning the return value of new by reference is deprecated in test.php on line 1108

A: Remove the &.
Objects are passed as reference by default in PHP 5, which is why using the & is deprecated in this context.

A: So, you've got this or similar error:
Parse error: syntax error, unexpected 'new' (T_NEW) in
/usr/share/php/PEAR/Config.php on line 650

Proper fix would be to upgrade all PEAR libraries. But since (as time of writing) there's none, here's how to fix all these errors in PEAR when running PHP 7.
Before the fix.
find /usr/share/php -type f -name \*.php | xargs grep '&new' | wc -l

Returns 77 occurrences.
Now comes sed magic
find /usr/share/php -type f -name \*.php | xargs sed -i 's/&new/new/g'
find /usr/share/php -type f -name \*.php | xargs sed -i 's/& new/ new/g'

After the fix
Previous code returns zero occurrences.
You may also want to add this somewhere in PEAR.php:
function set_magic_quotes_runtime() {}