text:
Q: How to obtain value of auto_increment field in Access linked to MySQL? I'm trying to modify and existing Access application to use MySQL as a database via ODBC with the minimal amount of recoding.
The current code will often insert a new record using DAO then obtain the ID by using LastModified.  This doesn't work with MySQL.  Instead I'm trying to use the approach using
SELECT * FROM tbl_name WHERE auto_col IS NULL

Suggested for Access in the MySQL documentation.  However if I set up a sample table consisting of just an id and text data field and execute this
CurrentDb.Execute ("INSERT INTO tbl_scratch (DATA) VALUES ('X')")
Set rst = CurrentDb.OpenRecordset("SELECT id FROM tbl_scratch WHERE id IS NULL")
myid = rst!id

Id is returned as null.  However if I execute
INSERT INTO tbl_scratch (DATA) VALUES ('X');
SELECT id FROM tbl_scratch WHERE id IS NULL;

using a direct MySQL editor then id is returned correctly, so my database and approach is fine but my implementation inside Access must be incorrect. Frustratingly the MySQL documentation gives the SQL statement to retrieve the id as an example that works in Access (as it states LAST_INSERT_ID() doesn't) but gives no further details.
How might I fix this?

A: Solved (and blogged) as below
I've been implementing an upgrade for a set of Access databases to replace the Access file database with MySQL linked by ODBC.  Everything seems to be going remarkably smoothly except for the common concept of inserting a record into a table with an auto-increment id column and retrieving the value of the id just created.  Of course on PHP or the like one would just use the
SELECT LAST_INSERT_ID()
Function  to retrieve the ID. However the MySQL documentation itself says that this doesn't work for certain ODBC applications such as Delphi or Access and suggests using
SELECT * FROM tbl WHERE auto IS NULL;
Unfortunately this simply didn't work for me when called from inside the Access application I was working with, and there seems to be several comments around the web that indeed this is unreliable as Access may drop the data connection and reconnect behind the scenes - thus invalidating the call.
As an alternative I decided to use a MySQL function to add a blank record to the table, returning the id which Access would then use to update the record (which fits well with the code-style of the existing application).  Unfortunately this apparently straightforward work-around fails to be simple either as long-standing bugs in MySQL make finding valid code that can both send and return a variable something of a challenge.  Several examples on the web will work within the limited domain of using either just IN or OUT variables but fail to work with both.
My final solution, which works on the MySQL 5.1 and Access 2003 combination I am deploying, is as follows
MySQL procedure
DELIMITER $$

CREATE
    PROCEDURE `alicedata`.`sp_ins_identity`(IN tablename VARCHAR(50))
    BEGIN
    SET @result = 0;
    SET @sqlproc = CONCAT("INSERT INTO ",tablename," () VALUES ();");
    PREPARE s1 FROM @sqlproc;
    EXECUTE s1;
    DEALLOCATE PREPARE s1;
    SELECT LAST_INSERT_ID();
    END$$

This procedure is useful in that it will insert a row and return the id for any table where a row contains all null fields or non-null fields with defaults defined.  To call this I use the following function:
Public Function InsertMySQLIdentityRow(DSN As String, Tablename As String) As Integer
On Error GoTo Err_InsertMySQLIdentity

Dim cnnSQL As New ADODB.Connection
Dim cmdSQL As ADODB.Command
Dim pid As Integer
Dim rs
Dim strSQL As String

    ' initialize
    pid = 0

    ' set up ADO connection
    Set cnnSQL = New ADODB.Connection
    cnnSQL.Open DSN

    ' execute the procedure - note that assembling by parameter fails to handle IN or OUT correctly

    Set cmdSQL = New ADODB.Command
    cmdSQL.ActiveConnection = cnnSQL

    strSQL = "call sp_ins_identity('" & Tablename & "');"
    Set rs = CreateObject("ADODB.Recordset")
    Set rs = cnnSQL.Execute(strSQL)

    If Not rs.EOF Then
      pid = rs(0)
    End If

    ' clean up
    Set rs = Nothing
    Set cmdSQL = Nothing
    cnnSQL.Close
    Set cnnSQL = Nothing

Exit_InsertMySQLIdentity:
    InsertMySQLIdentityRow = pid
    Exit Function

Err_InsertMySQLIdentity:
    MsgBox Err.Number & Err.Description
    Resume Exit_InsertMySQLIdentity
End Function

This code is somewhat unusual in that normally, on MSSQL, you would use a parametrized  procedure call, but due to bugs in the MySQL ODBC (or at least incompatibilities with Access) the above seems to be the only way that allows both data to be passed and returned.


text:
Q: My PLSQL trigger is not looping through the table I have a group project and we are using PLSQL to make a shopping cart application. We are creating a trigger in order to cancel a shopping cart and return all of the items back to stock. As it is now, if you add multiple items to your cart, when the trigger runs, it only adds back the stock of one product, not all, so for some reason, the trigger is not looping through. Our project is due tomorrow so please help!
create or replace TRIGGER Cancel
Before delete on sc_cart
For each row

DECLARE
ws_prod_id number(3,0);
ws_item_quantity_in_cart number(7,0);

BEGIN

/*product and quantity in cart*/
select max(item_product_id), max(item_quantity_in_cart) into ws_prod_id, ws_item_quantity_in_cart
from sc_items
where item_cart_id = :old.cart_id;

update sc_product set prod_quan_avail = prod_quan_avail + ws_item_quantity_in_cart where ws_prod_id = prod_id;
update sc_product set prod_quan_sold = prod_quan_sold - ws_item_quantity_in_cart where ws_prod_id = prod_id;

delete from sc_items
where :old.cart_id = item_cart_id;

END;

We need the code to go through each row of the table and return each item in the cart back to stock.

A: I urge you to not put all this code in a trigger, but instead create a cancel_order procedure like this:
CREATE OR REPLACE PROCEDURE cancel_card (cart_id_in IN INTEGER)
IS
   ws_prod_id                 NUMBER (3, 0);
   ws_item_quantity_in_cart   NUMBER (7, 0);
BEGIN
   /*product and quantity in cart*/
   SELECT MAX (item_product_id), MAX (item_quantity_in_cart)
     INTO ws_prod_id, ws_item_quantity_in_cart
     FROM sc_items i
    WHERE i.item_cart_id = cancel_card.cart_id_in;

   UPDATE sc_product p
      SET prod_quan_avail = prod_quan_avail + ws_item_quantity_in_cart,
          prod_quan_sold = prod_quan_sold - ws_item_quantity_in_cart
    WHERE p.prod_id = cancel_card.ws_prod_id;

   DELETE FROM sc_items o
         WHERE i.cart_id = cancel_card.cart_id_in;

   DELETE FROM sc_cart c
         WHERE c.cart_id = cancel_card.cart_id_in;
END;

You then call this procedure as needed, but not from inside a trigger.
You should avoid SQL statements inside triggers. There is too much potential for side effects and mutating table errors.

A: When you do this:
   SELECT MAX (item_product_id), MAX (item_quantity_in_cart)
     INTO ws_prod_id, ws_item_quantity_in_cart
     FROM sc_items i
    WHERE i.item_cart_id = cancel_card.cart_id_in;

You are just selecting ONE (1) product => max(item_product_id)
So, thats the only product updated, and to make things worse, it will be updated with max(qty) eventually from another product...
You need a cursor of cart products and for each product, do the necessary updates.
Triggers are not bad or good, but as a base rule, I completely agree with the comment of Steven Feuerstein, you should avoid them. But sometimes you cant.
Maybe a beter design would be a mixed one:
- Build a stored proc that clears a cart based on cart id
- Call that procedure from trigger (if you really must), or from outside (cart management process) as a better option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy Data from many workbooks to a master using column headers Below code is working beautifully for copying data from ONE workbook to my master (Source.xlsx). Can I modify this code to do the same for many workbooks?
I need data from many files in one directory to be appended to that table, using the column headers in the source. Files I am copying from always have the headers I am looking for, but in different columns.
It would be super useful to save the file name that the data was copied from along with the subfolder and subfolder2 saved in added columns (master file location > subfolder > subfolder2 > files to copy from).
Can you please help me StackOverflow gurus?
Sub CopyByHeader()

    Dim CurrentWS As Worksheet
    Set CurrentWS = ActiveSheet

    Dim SourceWS As Worksheet
    Set SourceWS = Workbooks("vavc1.valor.carnival.com_2017-10-30.xls").Worksheets(1)
    Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
    Dim SourceCell As Range

    Dim TargetWS As Worksheet
    Set TargetWS = Workbooks("Source.xlsx").Worksheets(1)
    Dim TargetHeader As Range
    Set TargetHeader = TargetWS.Range("A1:K1")

    Dim RealLastRow As Long
    Dim SourceCol As Integer

    SourceWS.Activate
    For Each Cell In TargetHeader
        If Cell.Value <> "" Then
            Set SourceCell = Rows(SourceHeaderRow).Find _
                (Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
            If Not SourceCell Is Nothing Then
                SourceCol = SourceCell.Column
                RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
                SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
                If RealLastRow > SourceHeaderRow Then
                    Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
                        SourceCol)).Copy
                    TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
                End If
            End If
        End If
    Next

    CurrentWS.Activate

End Sub

A: So you need to wrap your code that works in a loop. For each workbook in folder.files, run your code.
This post will tell you how to iterate over the workbooks in a folder:
Loop through files in a folder using VBA?


text:
Q: Proper way of using large array static member
*

*I want a class to have ownership over a large array (at least 100000 elements).

*I have a class called BaseProduct (with members like name , price , cost , print()...)

*I have a class BasicProductContainer that will control the array of BaseProducts.

*I tried having a shared pointer member to an array in my BasicProductContainer:
private:
    std::shared_ptr<std::array<BaseProduct, NUMBER_OF_PRODUCTS>> m_ptrArrProductContainer;

I want to avoid the array definition in the header file, so I did this in the class constructor in my .cpp:
static std::array<BaseProduct, NUMBER_OF_PRODUCTS> ProductContainer;

BasicProductContainer::BasicProductContainer() {
    m_ptrArrProductContainer = std::make_shared<std::array<BaseProduct, NUMBER_OF_PRODUCTS>>(ProductContainer);
}

This "works" but I'm wondering if there a better way? or a better looking one?  Is the pointer-to-array a good idea?

A: If the array is not shared, I don't think it should be shared_ptr. Have you tried a unique_ptr?
There is also the pimpl idiom which is often used to avoid the definition of data in a header file:
// BasicProductContainer.h
class BasicProductContainerImpl; // forward declare pimpl
class BasicProductContainer {
private:
    std::unique_ptr<BasicProductContainerImpl> m_impl;
}

// BasicProductContainer.cpp
class BasicProductContainerImpl {
public:
  std::array<BaseProduct, NUMBER_OF_PRODUCTS>> arrProductContainer;
}

BasicProductContainer::BasicProductContainer()
  : m_impl(std::make_unique<BasicProductContainerImpl>())
{
    // m_impl->arrProductContainer to access the array
}

Note that the array is not static, but your comment on the main post that each BasicProductContainer should have its own container suggests that you don't want the static.


text:
Q: Calling onSaveInstanceState on Activity I inherited a project, trying to understand and solve an old bug.
When I start an activity and let it sit for a bit (sometimes it's almost immediate), but it appears to go into a pause state or something and attempts to reload the activity and gets an error.
"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String ... ' on a null object reference"
I found that when I add this to my activity:
@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
  //super.onSaveInstanceState(savedInstanceState);
}

It appears to work perfectly.
However, when I uncomment the line above to super.onSaveInstanceState(savedInstanceState);, I get the error again.
My activity is extending the ActionBarActivity, if that is helpful.
Any help would be appreciated.  Thank you!
Related Code:
@Override
protected void prepareLayout() {
  textMessage = (TextView) findViewById(R.id.textMessage);
  textNotes = (EditText) findViewById(R.id.textNotes);

  textMessage.setText(getOneOfMyItems().getText());
  // ... the above line is where the problem error is thrown.
}

Stack Trace:
    Process: com.myproj.myproj, PID: 9272
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myproj.myproj/com.myproj.activities.MyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.myproj.data.MyItems.getText()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3288)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3384)
        at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5433)
        at android.app.ActivityThread.access$1200(ActivityThread.java:226)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1810)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7270)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.myproj.data.MyItems.getText()' on a null object reference
        at com.myproj.xyz.MyFragment.prepareLayout(MyFragment.java:44)
        at com.myproj.fragments.BaseFragment.prepareAndSetView(BaseFragment.java:49)
        at         at com.myproj.xyz.BaseMyFragment.onCreateView(BaseMyFragment.java:21)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1268)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2143)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:2089)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1129)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1286)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1268)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2143)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:615)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1266)
        at android.app.Activity.performStart(Activity.java:6943)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3384)
        at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5433)
        at android.app.ActivityThread.access$1200(ActivityThread.java:226)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1810)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7270)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)


text:
Q: webassembly load time is too long I am working with face detection model which is in .wasm format. I am reading and executing it in JavaScript. Everything works fine. But it takes too much time to complete the WebAssembly.instantiate() method with an array buffer output.
The wasm file is 8.6MB in size and it is taking 3 seconds to finish the execution after loading the file.
Application load time is delaying because of this. Is there any way to reduce the size of the .wasm file or improving the file execution time?
Any help is appreciated.

A: WebAssembly.instantiate() is officially not a recommended way.
Use the newer WebAssembly.instantiateStreaming(). This will load a wasm file more efficiently. Note that you should use a response object from fetch() than an ArrayBuffer to load wasm file.
Also, 8.6MB is pretty big for a wasm file. So you might still feel it is a bit slow to load. Have you compiled the project using optimization flags?


text:
Q: symfony monolog writing logs to different files according to channels In my Symfony app I am using monolog to log errors and I got different channels. I need to write different channels to different files. I got the following monolog config:
//app\config\config.yml
monolog:
channels: ['my_channel', 'my_channel2']
use_microseconds: false
handlers:
    file:
        type:   stream
        path:   %kernel.logs_dir%/prod_info.log
        level:  info
        channels: [!my_channel2]
    file_2:
        type:   stream
        path:   %kernel.logs_dir%/mylogfile_2.log
        level:  info
        channels: [my_channel2]
    file_errors:
        type:   stream
        path:   %kernel.logs_dir%/cms_errors.log
        level:  error
        channels: [!my_channel2]

my config.prod config
monolog:
handlers:
    main:
        type:         fingers_crossed
        action_level: debug
        handler:      nested
        channels: [!my_channel2]
    nested:
        type:  stream
        path:  "%kernel.logs_dir%/main_%kernel.environment%.log"
        level: debug
        channels: [!my_channel2]
    console:
        type:  console

I can access my_channel2 in the code like this:
$logger = $this->get('monolog.logger.my_channel2');
$logger->debug('Some message here');

but still all my_channel2 messages are written to main_prod.log file instead of mylogfile_2.log. Any ideas how to fix it would be welcome. Thank you.

A: just needed to change action level from info to debug for the required channel
file_2:
    type:   stream
    path:   %kernel.logs_dir%/mylogfile_2.log
    level:  debug // <== change from info to debug here
    channels: [my_channel2]


text:
Q: Mimic a pick-up coil to drive a CDI ignition I'm researching why an ignition coil passes ohm's testing but doesn't work. Installed on the vehicle and the engine doesn't run correctly. At first stages of bench testing and I'm still not finding anything amiss.
UPDATE I will continue editing and updating the question through the design process. Once I believe I have answered my own question, I will create an Answer in the hopes that this might help someone else.

Full disclosure: I sell these coils: I buy them from China and for a decade, they've been great. Now this is happening sometimes and I want to catch bad coils rather than have customers find out they're bad and get frustrated.
I have FB photo album here about the testing thus far. I'm thinking a great start will be to use an Arduino to simulate the pick-up coil. Rather than test just the coil, I'm wanting to keep the CDI igniter module in the system. I've observed the coil "fires" with very little current. The system works on leading and trailing edges.
This is what I'm going to try tomorrow. Unless someone has another idea. What could possibly go wrong?

simulate this circuit – Schematic created using CircuitLab
I'm thinking when I set both D6 and D7 to HIGH, there will be little or no current across R2 as a steady state. Then set D6 to LOW and we'll start a pulse. Reset D6 immediately to HIGH and I start dwell. Then delay for dwell and toggle D7 LOW->HIGH to end the signalling event.
5V dropping across any one resistor lets 5 mA through. So with D7 at 0V and D6 at 5V, D6 could be drawing 10 mA. Arduinos are supposed to be good up to 40 mA on any pin. Hopefully the transients I observed on the working circuit aren't too harsh. My parts bin doesn't have lots of transistors or large capacitors, but I've got 1N4007 diodes and a good selection of resistors - so I'm trying to keep this simple.

There are very few examples on the Net.  There are forms of H-bridge circuits and one person shows a 555 timer with pin 3 driving a CDI but also has inductance on the output to CDI:

Update #1: The above circuit made pulses as I hoped it would: alternating pulses with a variable "RPM" based on the potentiometer. I had three 2k ohm resistors handy, so they were employed and the above drawing updated. However, when sent to the CDI module, it only "fired" once. A 8V spike happened on the monitored line and then no more activity until I reset the Arduino. (gist of source code)
Does anyone have recommendations on conditioning that signal line?

And the signal captured when hooked up to the CDI:

Update #2: The aforementioned design was only able to produce one "fire" of the coil and then the Arduino would lock up. The MCU "locked up" enough that it required reprogramming to come back to life. I tried variations with capacitors and diodes but at most, I would get one spark and then maybe or maybe not the Arduino lost its mind.
I still believe it should be possible to use the digital output of an embedded controller to excite the CDI by emulating the inductor which feeds it.
My next phase of testing was to use a relay to provide switching. Although I know from testing fuel injectors that a relay can function at engine speeds, I know the pulsewidth and duty cycle of triggering the CDI was on the edge of possibility. As it turns out, the relay can emulate idle speeds quite well. there is a video here. The relay became silent when the simulation approached 1400 rpm and then by 1600 rpm, the relay was absolutely silent and the firing of the coil became intermittent even though the o'scope still showed pulses.
Design:
The relay is one of 4 on a shield intended to fit above a typical Arduino. The shield uses opto-couplers to drive the coils and there is a separate power supply input to the shield for the relays. I used the same 12V as supplied by the battery to the ignition system. The relay shield has jumpers allowing the routing of any digital pin to drive any of the 4 relays. I jumped D8 to drive relay 1.
R1 is a 1/4W resistor and R2 is 2W or 5W, so it's ok to drop all 12VDC at 24 mA. In normal state, the relay is closed and there is no voltage across the CDI input. When Arduino D8 goes high, relay 1 triggers and the NC contact opens, enabling R1 to be voltage divider with R2, and putting 2V across the CDI input. In the video, you can see the relay bouncing.

Digging through the new parts bin, I found a JE170 PNP transistor. Since focussing on programming in my 5th semester, I have quite forgotten BJT design. But I think this next design might do the trick:

I'll now use the Arduino Nano that I started with and use D5 to drive the signal. When D5 is HIGH, the transistor should be shut off, as the emitter is 2V and the base is 5V and thus reverse biased. And the input to the CDI should be 2V. When D5 goes LOW, the transistor should saturate and then the input to the CDI should be Vce at saturation, which is approaching 0. I suspect I will need to invert the polarity of the pulses from the relay part of this design.
So long as the CDI doesn't feed spikes back into the Arduino, I'm hoping this will work and switch fast enough to enable analysis of spark advance and better understanding of the system's functioning beyond "it works".

A: The solution is to best eliminate the voltage spikes and EMI that the MCU was experiencing. While the relay was successful, its latency meant the RPM simulated was still very low. The next stage using a BJT amplifier showed potential, however, with much trial and error, a successful combination of capacitances and resistances remained unfound.
A transformer was cannibalized from a fax modem PCB from a multifunction printer. Once employed as coupling, the circuit's behavior improved dramatically. A pair of 1N4007 diodes did help yet the circuit remained buggy and the MCU would lock up. Critiquing the PCB the transformer was sourced from, the pair of large diodes with glass envelopes were added to the secondary and the MCU became steady. R3's value of 100 Ω was chosen because that is what the original pick-up coil's resistance measures.
Further helping stability was employing the resistor spark plug cap and using an actual spark plug (NGK DR9EA). This made the testing much more quiet as opposed to the spark plug cable ending near a ground conductor.
With the physical circuit stabilized, the MCU's programming was improved with LCD readout and setting up TIMER5 for a PWM output rather than manually bit banging the pulse output from the loop() function. The code I used to set up the timer in my Arduino Mega is in my Arduino QA explanation.
There is video on our Facebook Page. Keen observers might notice the Hz reported on the LCD isn't exactly dead on - that's because it is an approximation without using floating points. The timer is set on microseconds and is remarkably accurate when read on the o'scope. (more discussion below the drawing)

Below is a curious o'scope capture. CH1 is the yellow upper trace (and is depicted in green in the drawing above) and is what one would expect for a digital output. Before this latest physical circuit, spikes could be observed on the trace at one of the transitions.
Yes that is a 120 Volt spike Everyone knows about spikes and inductors but this was unexpected. CH2 is the blue trace at 20 V per division and is on the CDI to coil primary circuit. The input pulse to the CDI is calculated to be 26° of rotation so is 26/360 * period. You can see that the CDI driver is approaching 100% duty cycle, so some tweaks will be needed: the 26°, although measured as the width of the crankshaft trigger, is too long since the coil stops firing above this setting and there are still another 1000 rpm to go.


text:
Q: What are "reciprocal radii/radiuses"? in a novel I found the phrase "reciprocal radii". What exactly does this phrase mean? Can you explain it even for non-mathematicians, maybe in a more philosophical way (by connecting this phrase to a world view?) ?
Kind regards!
EDIT: Due to the commentary:
Ok, since the text is written in german I hope that I am translating the words correctly: together with that phrase comes

*

*"graphic representation of functions with complex variables"

*"the single human being as the unitary circle, in which Everything is reflected and twisted and contracted"

*"infinity becomes the deepest inner midpoint; and through this midpoint humans have crossed their coordinates."

*The author had some knowledge about Diophant, Euclid and Fermat; he very often writes about the earth being a circle or a globe. He also mentions Riemann occasionally.

maybe those information can help you and me :)


text:
Q: Eigenvalues of a matrix with binomial entries I am trying to determine the eigenvalues of the following matrix:
$$M_{ij} = 4^{-j}\binom{2j}{i}$$
where it is understood that the binomial coefficient $\binom{m}{k}$ is zero if $k<0$ or $k>m$. Here $i,j$ go from $0$ to $N$, therefore the matrix is $(N+1)\times(N+1)$.
If an exact expression is not available, I would content myself with approximations valid for large $N$.
Moreover, I am mostly interested in the largest positive eigenvalue and its corresponding eigenvector.

A: Clearly 1 is an eigenvalue for the eigenvector $(1,0,\dots,0)$.
On the other hand it is the largest eigenvalue, since the 1-norm of the operator corresponding to the matrix is 1. In fact, (see https://en.wikipedia.org/wiki/Matrix_norm)
$$
\|M\|_1=\sup_{\|x\|>0}\frac{\|M(x)\|_1}{\|x\|_1}=\max_{0\le j\le N}\sum_{i=0}^N|M_{ij}|=1
$$
The last equality follows from the fact that the equality is attained for $j=0$ and in general
$$
\sum_{i=0}^N|M_{ij}|\le \sum_{i=0}^{2j}|M_{ij}|=\frac{1}{2^{2j}}\sum_{i=0}^{2j}\binom{2j}{i}=1
$$
The absolute value of an eigenvalue cannot be greater than $\|M\|_1=1$, since
$$
|\lambda|\|x\|_1=\|Mx\|_1\le \|M\|_1\|x\|_1=\|x\|_1.
$$


text:
Q: Merging multiple Images I'm trying to merge multiple Images into one image. Problem is that most libraries with such functionality are not available in a Windows 8.1 App. I'd prefer to not have to use external libraries such as WriteableBitmapEx
This is my current code which unfortunately doesn't work:
int count = 4;
int size = 150;
WriteableBitmap destination = new WriteableBitmap(300, 300);
BitmapFrame frame = await (await BitmapDecoder.CreateAsync(randomAccessStream)).GetFrameAsync(0);
PixelDataProvider pixelData = await frame.GetPixelDataAsync();
byte[] test = pixelData.DetachPixelData();
MemoryStream mem = new MemoryStream();
for (int row = 0; row < frame.PixelHeight; row++) {
    for (int i = 0; i < count; i++)
    {
        mem.Write(test, row * (int)frame.PixelWidth * 4, (int)frame.PixelWidth * 4);
    }
}
mem.Seek(0, SeekOrigin.Begin);
BitmapImage bmp = new BitmapImage();
bmp.SetSourceAsync(mem.AsRandomAccessStream());

If I set the bmp as the source of an Image UIElement nothing happens.
My Idea was to get the Pixeldata as a byte array and to write it line by line (pixel row of each image, so they'd be next to each other) to a memory stream which is then used as the source of the BitmapImage.
Solved
Thanks to Aditya and Romasz I could solve this.
The problem was that I had to encode the pixel data back to an image.
If anyone has the same Problem the following class merges the pixel data of multiple images and returns a BitmapImage:
public class ImageMerger
{
    public static async Task<BitmapImage> MergeImages(int singleWidth, int singleHeight, params byte[][] pixelData)
    {
        int perRow = (int) Math.Ceiling(Math.Sqrt(pixelData.Length));
        byte[] mergedImageBytes = new byte[singleHeight * singleWidth * perRow * perRow * 4];
        for (int i = 0; i < pixelData.Length; i++ )
        {
            LoadPixelBytesAt(ref mergedImageBytes, pixelData[i], (i % perRow) * singleWidth, (i / perRow) * singleHeight, perRow * singleWidth, singleWidth, singleHeight);
        }
        InMemoryRandomAccessStream mem = new InMemoryRandomAccessStream();
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, mem);
        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)(singleHeight * perRow), (uint)(singleWidth * perRow), 91, 91, mergedImageBytes);
        await encoder.FlushAsync();
        BitmapImage bmp = new BitmapImage();
        bmp.SetSourceAsync(mem);
        return bmp;
    }

    private static void LoadPixelBytesAt(ref byte[] dest, byte[] src, int destX, int destY, int destW, int srcW, int srcH)
    {
        for (int i = 0; i < srcH; i++)
        {
            for (int j = 0; j < srcW; j++)
            {
                if (src.Length < ((i * srcW + j + 1) * 4)) return;
                for (int p = 0; p < 4; p++)
                    dest[((destY + i) * destW + destX + j) * 4 + p] = src[(i * srcW + j) * 4 + p];
            }
        }
    }
}

This takes any number of images and puts them next to each other with around as many images from left to right as from top to bottom.
I.e. for 4 images it would return an image with them aligned like this:
1     2

3     4

Works for all of my images but one. There is one image that looks pretty weird after getting merged with others. Didn't figure out why yet.

A: This should do it :
byte[] PutOnCanvas(byte[] Canvas,byte[] Image,uint x,uint y,uint imageheight,uint imagewidth,uint CanvasWidth)
{
    for (uint row = y; row < y+imageheight; row++)
       for (uint col = x; col < x+imagewidth; col++)
          for (int i = 0; i < 4; i++)
              Canvas[(row * CanvasWidth + col) * 4 + i] = Image[((row-y) * imagewidth + (col - x)) * 4 + i];

    return Canvas;
}

Now say I want to put two images (pixelbytes in Image1 and Image2) of 30x30 side by side and have a vertical margin of 10px in between them. I would call the function in the following way:
byte[] Canvas = new byte[30 * 70 * 4];
Canvas=PutOnCanvas(Canvas,Image1,0,0,30,30,70);
Canvas=PutOnCanvas(Canvas,Image2,40,0,30,30,70);

Then convert pixel bytes to BMP and you should be done!
Edit:
And this is the correct way to convert pixel bytes to image:
memStream.Size = 0;
var encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, memStream);
encoder.SetPixelData(
    Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
    Windows.Graphics.Imaging.BitmapAlphaMode.Straight,
    CanvasWidth, // pixel width
    CanvasHeight, // pixel height
    96, // horizontal DPI
    96, // vertical DPI
    PixelData);

try { await encoder.FlushAsync(); }
catch { }
memStream.Dispose();

A: Tried this method awhile ago and it worked for me.
http://www.codeproject.com/Articles/502249/Combineplusseveralplusimagesplustoplusformplusaplu

A: One option is to draw them in a Canvas like you normally would and then render that Canvas out. The only problem with this is that they must all be on the screen at the same time.
Unfortunately, that's about it as far as simple solutions without something like WriteableBitmapEx goes. Their BitmapContext class abstracts away a lot of the more complex math that goes on when changing an image's width. You can check out WinRTXamlToolkit's blit implementation here, but it has the limitation that the source and destination files must be the same width (due to the annoying math).
One option may be to try and up the size of the images without scaling, hopefully creating some whitespace in the proper spot, then layering them together using a facsimile of that blit implementation, but this seems like it will be a lot of trouble as well.
Your best bet, IMO, is to cut out the chunks of WriteableBitmapEx that you need, specifically their BitmapContext and the Blit Extensions that they provide, then create a blank image and overlay each image onto the destination image (as you are attempting to do now).
This is not legal advice.
WriteableBitmapEx is Microsoft License, which is very permissive, so you should be okay to do this.
Anyway, it'd likely be easier to just add the reference, but if it's necessary that you don't, you can still cut out the parts that you need (in this case) and use them 'a la carte'.


text:
Q: no shutdown, kubuntu 16.04.2 I looked for many topics about this, but I didn't succeed in fixing this problem. I decided to upgrade Kubuntu 14.04.5 32 bits --> 16.04.2 32 bits - I have no uefi (using a live-usb, but this problem just appeared after... When I try to shutdown my laptop (Acer Aspire V5-531 series Windows 7 64 bits / Kubuntu 16.04 LTS 32 bits, écran 15,6", 500go DD, 4go RAM, Intel pentium CPU 967 processor, Intel HD graphics 4000), I have those information:
here
I tried to edit /etc/default/grub by 1) adding 2) replacing "quiet splash" (Ubuntu 16.04 hangs on shutdown/restart)
Same thing for /etc/default/halt (replace HALT=poweroff by HALT=shutdown). sudo poweroff -f, shutdown -h now...
What is the source of the problem, I don't even exactly know... I think about creating a script to shutdown. What's wrong?

A: Had a similar problem: it is a Bios issue. try THIS and specifically look at "Turning off USB 3.0 legacy mode in the BIOS worked for me"
if it does not work try manipulating other usb settings.


text:
Q: Why do I get duplicate toolbar entries? The django-cms cms_toolbar has duplicate items -

It happens for me on django-cms 2.2 and the develop branch (2.2.post0). I'm running python 2.7.2, django 1.3.1
Any suggestions?

A: I got this problem, it was because, I had {% render_block "js" %} this coding two times in the template.


text:
Q: C++ Redefining Class Method for Specific Objects I have a class foo that has a method doesSomething(). I construct multiple objects of said class, but for a few specific ones I want doesSomething() to do something else. How do I redefine the body of that method dynamically after construction?
I believe this is exactly what I'm looking for, but it's in Java.

A: If you want to "overwrite" a previous class definition, you can use virtual functions, and use a derived class.
Here you have some examples, particularly under the "Virtual members" title.
Good luck.

A: struct nasty_object {
  nasty_object()
  : _something_do { std::bind(&nasty_object::normal_thing, this) }
  {
  }

  void normal_thing() {
    // the stuff to do in the default case
  }

  void do_other_thing() {
    // the stuff to do in the alternate case
  }

  void do_something() {
    if(_something_do) {
      _something_do();
    }
  }

  // replace the meaning of 'do_something()'
  void set_do_something(std::function<void()> f)
  {
    _something_do(std::move(f));
  }

private:
  std::function<void()> _something_do;
};

now you can create objects and change the meaning of do_something() at run time like this
auto n1 = nasty_object{};
auto n2 = nasty_object{};
auto n3 = nasty_object{};
n2.set_do_something(std::bind(&nasty_object::do_other_thing, &n2));
n3.set_do_something([&n3] {
  // do something totally different!
});
n1.do_something(); // does something
n2.do_something(); // does the other thing
n3.do_something(); // does whatever was in your lambda

Note: just because you can do this with c++ does not mean you should. This kind of irresponsible behaviour is best left to script-jockeys and other people up to no good.

A: In C++, objects don't have references to methods, they have references to "virtual function tables" aka "classes".  So you'd need to involve another class to do it the way you envisage. But you also said you want to change it after the object has been constructed - and that means you can't do it using virtual functions. Instead you should use function pointers or even just a simple boolean:
class C {
    bool isSpecial;

    void doesSomethingNormal() { ... }
    void doesSomethingSpecial() { ... }
    void doesSomething() {
              if (isSpecial)
                  doesSomethingSpecial();
              else doesSomethingNormal();
    }
};


text:
Q: Spring MVC - Read file from my controller I'm looking for a way to get a file placed in my WEB-INF directory from my controller. I need this file to validate my XML.
Here is my project architecture :

I need to get the rg19.xsd file from my Controller method.

A: I have not done that kind of thing myself, I usually use resources to do that, But I think you can autowire ServletContext and call
@Autowired
ServletContext servletContext;

//inside controller:
new File(servletContext.getRealPath("/WEB-INF/xsd/rg19.xsd"))

Give it a try and let me know
Edit for the comment:
By putting files inside main/resourses I access it by using @Value magic:
@Value("classpath:xsd/rg19.xsd")
Resource resourceFile;

After that, its easy to getFile from resourceFile


text:
Q: Java-client-api to trigger jenkins job from java.. works on local jenkins but fails on remote server I m executing a java programme to run a jenkins job ( name "terraform-example" ) which runs on the same machine it works fine.
But when I point to a remote Jenkins server it throws exception though port is open and web URL can be accessed from remote
Here is the code
 import java.net.URI;
 import com.offbytwo.jenkins.JenkinsServer;
 import com.offbytwo.jenkins.model.BuildWithDetails;

 public class Main {
      public static void main(String args) {

      try
       { JenkinsServer jenkinsServer = new
                                          JenkinsServer(new

         URI("http://localhost:8080/"),"admin","apitoken");
        // JenkinsServer jenkinsServer = new JenkinsServer(
               URI.create("http://192.168.1.207:8080/")
              ,"admin","apitoken");

           JenkinsTriggerHelper triggerHelper = new
           JenkinsTriggerHelper(jenkinsServer);
            BuildWithDetails
                          details =      triggerHelper.triggerJobAndWaitUntilFinished("terraform-example");
      if (details!=null)
           System.out.println("LOGS " +
           details.getConsoleOutputText());
      else
           System.out.println("details not found " ); }
      catch (Exception e)

             {
               e.printStackTrace();
             }
          }
          }

exception    org.apache.http.conn.HttpHostConnectException: Connect to
192.168.1.207:8080 [/192.168.1.207] failed: Connection
timed out: connect


text:
Q: How can I build this XML structure in JSON through JavaScript? I have this XML structure that I wish to construct in JSON format using JavaScript - preferably using dot notation all the way if possible. :)
Here is the XML - note this is a pseudo structure, to keep it simple! :)
<Items>
   <Item>
      <Name>Item 1</Name>
      <SubItems>
         <Item>
           <Name>Sub Item 1</Name>
         </Item>
      </SubItems>
   </Item>
   <Item>
      <Name>Item 2</Name>
   </Item>
</Items>

So, when I convert my JSON to XML (on the server), the output should be like above.
I need help getting started with this. I Google'd around and I couldn't find any examples on how to do this.
Thanks in advance!
EDIT: I am using NewtonSoft JSON for .NET to convert from JSON to XML!
EDIT 2: Ok, I figured out the Raw JSON structure to get the convertion to XML right - here it is:
var json = {
        "Items":
            {
                "Item":
                    [
                        {
                            "Name": "Test 1" ,
                            "SubItems":
                            {
                                "Item":
                                    [
                                        {
                                            "Name":"Test 1"
                                        },
                                        {
                                            "Name":"Test 2"
                                        }
                                    ]
                            }
                        },
                        {
                            "Name":"Test 2"
                        }
                    ]
            }
    };

That will produce the exact same XML structure as defined above.
Now, how would I go about building this structure using dot notation?
EDIT 3: With the help of Nikhil & Darin, I figured it out, however this only answers the pseudo-question. However I will mark this as answered and create a new question. :)
EDIT 4: I posted my extension to the marked answer. :)

A: this should do it:
var items = [
              {"name":"Item 1","subitems":[
                {"name":"Subitem 1"}
              ]},
              {"name":"Item 2"}
            ];

A: var items = [ ];

var item1 = { };
item1.Name = 'Item 1';
item1.SubItems = [ ];
var subItem = { };
subItem.Name = 'Sub Item 1';
item1.SubItems.push(subItem);
items.push(item1);

var item2 = { };
item2.Name = 'Item 2';
items.push(item2);

A: var json = {};
json.Items = {};
json.Items.Item = new Array();

var item1 = {};
item1.Name = "Test 1"
item1.SubItems = new Array();

var subItem1 = {};
subItem1.Item = new Array();
subSubItem1 = {};
subSubItem1.Name = "Test 1";
subSubItem2 = {};
subSubItem2.Name = "Test 2";
subItem1.Item.push(subSubItem1);
subItem1.Item.push(subSubItem2);
item1.SubItems.push(subItem1);
var item2 = {};
item2.Name = "Test 2";
json.Items.Item.push(item1);
json.Items.Item.push(item2);

Output of the above code is
{
    "Items": {
        "Item": [
            {
                "Name": "Test 1",
                "SubItems": [
                    {
                        "Item": [
                            {
                                "Name": "Test 1"
                            },
                            {
                                "Name": "Test 2"
                            }
                        ]
                    }
                ]
            },
            {
                "Name": "Test 2"
            }
        ]
    }
}

that should do it :)

A: Nikhil answered the question, and has gotten the magic tick. :) - I am extending his answer with the code I wrote to get the result I was looking for.
My real problem, after receiving the answer to the pseudo problem, was that I have different item types in my structure, which all shared the Items root node.
Here is a pseudo example of how I solved the issue. Again, Nikhil's answer was the base of the solution, so many thanks to him :)
Say we have a rootnode, Fruits, and we have different types of fruit. Say, apple, and banana.
Here's how I got the JSON structure (and ultimately, the XML convertion output that I was needing):
// Create the JSON Object
var json = {};
// Create the Fruits Objects (Our root)
json.Fruits = {};
for (var i = 0; i < 3; i++){
    // Pseudo condition
    if (i == 0 || i == 1) {
        // Make sure we have an Apple array
        if(json.Fruits.Apple == undefined)
            json.Fruits.Apple = [];
        json.Fruits.Apple.push({
             "Color": "Green"
        });
     } else {
        // Make sure we have a Banana array
        if (json.Fruits.Banana == undefined)
            json.Fruits.Banana = [];
        json.Fruits.Banana.push({
             "Color": "Yellow"
        });
    }
}

This will output the following JSON:
{"Fruits":
   {"Apple":
      [
       {"Color":"Green"},
       {"Color":"Green"}
      ],
    "Banana":
      [
       {"Color":"Yellow"}
      ]
   }
}

And ultimately, the following XML:
<Fruits>
  <Apple>
    <Color>Green</Color>
  </Apple>
  <Apple>
    <Color>Green</Color>
  </Apple>
  <Banana>
    <Color>Yellow</Color>
  </Banana>
</Fruits>


text:
Q: Is it possible to see what's processing on the GPU? Is there a way to see what specifically is processing on the GPU, and namely which program running on the GPU is currently holding its reins?
"Process Monitor" on Windows shows what's happening behind the curtains as far as filesystem, registry, network, process activity, profiling, stack, etc. Obviously a GPU isn't doing all these things, I'm just wondering along the lines of "Of the five processes currently open and running on the GPU, program X is currently having Y activity processed on the GPU," or the like.
I know in Task Manager you can see what programs are processing on the GPU, but that only shows percentages, not what is actually being processed.
For reference, this is on Windows 10 Pro with an Nvidia GPU.


text:
Q: Copy and Paste JSON between Visual studio html files I am trying to copy JSON from one .html file into another in Visual Studio 2013 with Update 4 and the pasted result is stripping all the : between JSON properties and values giving me useless markup.

Spline

        <div ui-jq="plot" ui-options="
          [
            { data: {{d}}, points: { show: true, radius: 6}, splines: { show: true, tension: 0.45, lineWidth: 5, fill: 0 } }
          ],
          {
            colors: ['{{app.color.info}}'],
            series: { shadowSize: 3 },
            xaxis:{
              font: { color: '#ccc' },
              position: 'bottom',
              ticks: [
                [ 1, 'Jan' ], [ 2, 'Feb' ], [ 3, 'Mar' ], [ 4, 'Apr' ], [ 5, 'May' ], [ 6, 'Jun' ], [ 7, 'Jul' ], [ 8, 'Aug' ], [ 9, 'Sep' ], [ 10, 'Oct' ], [ 11, 'Nov' ], [ 12, 'Dec' ]
              ]
            },
            yaxis:{ font: { color: '#ccc' } },
            grid: { hoverable: true, clickable: true, borderWidth: 0, color: '#ccc' },
            tooltip: true,
            tooltipOpts: { content: '%x.1 is %y.4',  defaultTheme: false, shifts: { x: 0, y: 20 } }
          }
        " style="height:240px" >

is being turned into:

Spline

                    <div ui-jq="plot" ui-options="
                         [
                         { data {{d}} , points { show true, radius 6}, splines { show true, tension 0.45, linewidth 5, fill 0 } }
                         ],
                         {
                         colors ['{{app.color.info}}'],
                         series { shadowsize 3 },
                         xaxis:{
                         font { color '#ccc' },
                         position 'bottom' ,
                         ticks [
                         [ 1, 'Jan' ], [ 2, 'Feb' ], [ 3, 'Mar' ], [ 4, 'Apr' ], [ 5, 'May' ], [ 6, 'Jun' ], [ 7, 'Jul' ], [ 8, 'Aug' ], [ 9, 'Sep' ], [ 10, 'Oct' ], [ 11, 'Nov' ], [ 12, 'Dec' ]
                         ]
                         },
                         yaxis:{ font { color '#ccc' } },
                         grid { hoverable true, clickable true, borderwidth 0, color '#ccc' },
                         tooltip true,
                         tooltipopts { content '%x.1 is %y.4' , defaulttheme false, shifts { x 0, y 20 } }
                         }
                         " style=" height:240px">

Big Question mark.

A: This is a bit complex json to put directly into an argument, but anyway... if you press once undo after pasting, you can undo the auto formatting attempted by Visual Studio. Your semicolons will be restored too.


text:
Q: Copying first lines of multiple text files into single file Using single bash command (pipes, stdio allowed)
copy first line of each file whose name begins with ABC to file named DEF.
Example:
Input:
ABC0:
qwe\n
rty\n
uio\n

ABC1:
asd\n
fgh\n
jkl\n

ABC2:
zxc\n
bvn\n
m,.\n

Result:
DEF:
qwe\n
asd\n
zxc\n

Already tried cat ABC* | head -n1 but it takes only first line from first file, others are omitted.

A: You would want head -n1 ABC* to let head take the first line from each file. Reading from standard input, head know nothing about where its input comes from.
head, though, adds its own header to identify which file each line comes from, so use awk instead:
awk 'FNR == 1 {print}' ./ABC* > DEF

FNR is the variable containing the line number of the current line of the input, reset to 0 each time a new file is opened. Using ./ABC* instead of ABC* guards against filenames containing an = (which awk handles specially if the part before = is a valid awk variable name. HT William Pursell.)

A: Assuming that the file names don't contain spaces or newlines, and that there are no directories with names starting with ABC:
ls ABC* | xargs -n 1 head -n 1

The -n 1 ensures that head receives only one name at a time.
If the aforementioned conditions are not met, use a loop like chepner suggested, but explicitly guard against directory entries which are not plain files, to avoid error messages issued by head.


text:
Q: From list to nested dictionary there are list :

data = ['man', 'man1', 'man2']
key = ['name', 'id', 'sal']
man_res = ['Alexandra', 'RST01', '$34,000']
man1_res = ['Santio', 'RST009', '$45,000']
man2_res = ['Rumbalski', 'RST50', '$78,000']

the expected output will be nested output:

Expected o/p:- {'man':{'name':'Alexandra', 'id':'RST01', 'sal':$34,000},
                    'man1':{'name':'Santio', 'id':'RST009', 'sal':$45,000},
                    'man2':{'name':'Rumbalski', 'id':'RST50', 'sal':$78,000}}

A: Easy way would be using pandas dataframe
import pandas as pd

df = pd.DataFrame([man_res, man1_res, man2_res], index=data, columns=key)
print(df)
df.to_dict(orient='index')

           name      id      sal
man   Alexandra   RST01  $34,000
man1     Santio  RST009  $45,000
man2  Rumbalski   RST50  $78,000
{'man': {'name': 'Alexandra', 'id': 'RST01', 'sal': '$34,000'},
 'man1': {'name': 'Santio', 'id': 'RST009', 'sal': '$45,000'},
 'man2': {'name': 'Rumbalski', 'id': 'RST50', 'sal': '$78,000'}}

Or you could manually merge them using dict + zip
d = dict(zip(
    data,
    (dict(zip(key, res)) for res in (man_res, man1_res, man2_res))
))
d

{'man': {'name': 'Alexandra', 'id': 'RST01', 'sal': '$34,000'},
 'man1': {'name': 'Santio', 'id': 'RST009', 'sal': '$45,000'},
 'man2': {'name': 'Rumbalski', 'id': 'RST50', 'sal': '$78,000'}}

A: #save it in 2D array
all_man_res = []
all_man_res.append(man_res)
all_man_res.append(man1_res)
all_man_res.append(man2_res)
print(all_man_res)

#Add it into a dict output
output = {}
for i in range(len(l)):
  person = l[i]
  details = {}
  for j in range(len(key)):
    value = key[j]
    details[value] = all_man_res[i][j]
  output[person] = details
output

A: The pandas dataframe answer provided by NoThInG makes the most intuitive sense. If you are looking to use only the built in python tools, you can do
info_list = [dict(zip(key,man) for man in (man_res, man1_res, man2_res)]
output = dict(zip(data,info_list))


text:
Q: Is this possible to validate a form created without formBuilder? As I say in the title. I have create a form in a twig file
<form action="{{ path('domain_confirm') }}" method="post" id="choose-domain-form">
   {% for domain, price in data %}

               {{ domain }}

{{ price }} €
           <input class="domain-purchase-checkbox" type="checkbox" name="domaintest" value="{{ domain }}" data-price="{{ price }}">

   {% endfor %}
</form>

How can I validate this form and get datas from this form inside my Controller ?
When I try to get these datas with
$request->request->get('form');

I get a null response
Do you have some ideas ?

A: As for the validation, you will have to create a form with the formBuilder and validate it that way. You can however, validate your input using the Symfony Validators, but this is not advised.
I strongly suggest using the provided form builder as it has alot of features you want such as CRSF and well... validation, aswel as auto mapping onto your entities.
As for getting the data in this specific case you will need to call :
$request->request->all();

However, i see all your checkboxes will have the same "name" attribute, you will need to change it from name="domaintest" to name="domaintest[]".
When you call :
$request->request->get('domaintest');

You will receive an array with values.


text:
Q: DataTables.net colvis: The list of available fields won't go away on losing focus I'm using DataTables.net (1.10.12) in my ASP.NET MVC web application with server-side processing (table loads, no problems with the data or controller). When I add the colvis button, I get the list of available fields and I can select and deselect the columns I want.
The problem comes in when I'm done selecting or deselecting fields - the list doesn't fade away on losing focus.
What am I missing?
here's my view:

            Field_A
            Field_B
            Field_C

when I look at the error captured in chrome, it says the following (not sure if that's meaningful to anybody):
Uncaught TypeError: d(...).parents(...).andSelf is not a function
at HTMLBodyElement.<anonymous> (dataTables.buttons.min.js:24)
at HTMLBodyElement.dispatch (jquery-3.1.1.js:5201)
at HTMLBodyElement.elemData.handle (jquery-3.1.1.js:5009)

A: welp, there was nothing wrong with my view - apparently datatables 1.10.12 and jQuery 3.1.0+ have issues. Specifically DataTables' buttons plugin below version 1.2.2 may have issues. Updated to datatables 1.10.13 with buttons 1.2.2 and all was well...
https://datatables.net/forums/discussion/36825/problem-with-jquery-3-1-0


text:
Q: Is the set of sum over a diagram is uncountable set? Consider the following diagram:
Let $0<x<\frac{1}{2}$

Note that $[.]$ is not box function
It is easy to see that $1$ split into $x$ and $(1-x)$. In next stage $x$ split into $x^2$ and $x(1-x)$ and $(1-x)$ split into $x(1-x)$ and $(1-x)^2$. Note that I do not write $x(1-x)$ twice, instead of that in this stage we have three values $x^2,x(1-x),(1-x)^2$. Continue this process in the next stage (see the diagram for more detail)
Now comes the important part:
Add take $1$ first. Then add either $x$ or $(1-x)$. If you added $x$ then next add either $x^2$ or $x(1-x)$ and if you added $(1-x)$ then up next add either $x(1-x)$ or $x^2$. Continue this process again.
For example you will get a value $1+\sum_{n=1}^{\infty}x^n$. Another one could be $1+\sum_{n=1}^{\infty}x(1-x)^{n-1}$. It depends on which path you choose. Every zigzag path will give you a $\color{red}{\text{different sums}}$.
$\color{red}{\text{different sums}}$ means sum over different zigzag path. Note that $\color{red}{\text{different sums}}$ does not mean two different path always give different values.
$\large{F}$or example $1+(1-x)\sum_{n=0}^{\infty}x^n$ and $1+x\sum_{n=0}^{\infty}(1-x)^n$ are two $\color{red}{\text{different sums}}$ but they yeilds same value $2$ i.e. $1+(1-x)\sum_{n=0}^{\infty}x^n=1+x\sum_{n=0}^{\infty}(1-x)^n=2$
Let say $T_x=\{\text{set of all $\color{red}{\text{different sums}}$ for a given $x$ }\}$
It can be easily seen there is uncountable number of $\color{red}{\text{different sums}}$.

Question: is there uncountable number of distinct elements in $T_x$ for a given $x$?

Observation:

*

*It can be easily seen that minimum element of $T_x$ is $\frac{1}{1-x}$ and maximum element of $T_x$ is $\frac{1}{x}$.

*$2\in T_x$ for every $x\in \Big(0,\frac{1}{2}\Big)$
But I could not find a way to prove or disprove uncountability. Any help would be appreciable.
$\blacksquare\space\space\blacksquare\space\space\blacksquare\space\space$ Thanks to MANMAID I am attaching a new diagram:
Let $0<x<1$

A: Formalization

*

*For $n \in \mathbb{N}$ let $\{ 0, 1 \}^n$ denote the set of $n$-element binary sequences, i.e. the set of functions $f : \{ 0, 1, \ldots, n-1 \} \to \{ 0, 1 \}$.

*Let $\{ 0, 1 \}^{\mathbb{N}}$ denote the set of infinite binary sequences, i.e. the set of functions $s : \mathbb{N} \to \{ 0, 1 \}$.

*For $s \in \{ 0, 1 \}^{\mathbb{N}}$ and $n \in \mathbb{N}$ (or $s \in \{ 0, 1 \}^m$ and $n \leqslant m$ respectively) by $s \upharpoonright n$ we denote the preffix of $s$ of length $n$, i.e. the restriction $s \upharpoonright \{ 0, 1, \ldots, n-1 \}$.

*For $f \in \{ 0, 1 \}^n$ let $\alpha(f) = \# \{ k < n : f(k) = 0 \}$ and $\beta(s) = \# \{ k < n : f(k) = 1 \}$ (the number of zeros and ones in $f$ respectively).

Note that any path in the diagram can be represented by an infinite binary sequence, so we may think of $\{ 0, 1 \}^{\mathbb{N}}$ as the set of all possible paths.
Fix $x \in \left( 0, \frac{1}{2} \right)$ and define $\varphi : \{ 0, 1 \}^{\mathbb{N}} \to \mathbb{R}$ as
$$\varphi(s) = \sum_{n=0}^{\infty} x^{\alpha(s \upharpoonright n)} \cdot (1-x)^{\beta(s \upharpoonright n)}.$$
Thus $\varphi(s)$ clearly represents the sum associated with the path $s$. So the question is: is $\varphi \left[ \{ 0, 1 \}^{\mathbb{N}} \right]$ uncountable?
Solution
On $\{ 0, 1 \}^{\mathbb{N}}$ there is a natural lexicographical order, given by $$s \prec t \iff (\exists n \in \mathbb{N}) \big[ s \upharpoonright n = t \upharpoonright n \wedge s(n) < t(n) \big].$$
In words: if $s, t$ are different, find the first position $n \in \mathbb{N}$ on which they differ, so $s(n) \neq t(n)$ and compare them by the value on that position. On your diagram, any two different paths diverge at some point and the one going to the left will be smaller with respect to this ordering.
The key observation is: let $s \prec t$. Then $\varphi(s) \leqslant \varphi(t)$ and $\varphi(s) = \varphi(t)$ if and only if there is $n \in \mathbb{N}$ such that $s$ and $t$ agree up to $n$ and then $s$ continues as $0, 1, 1, 1, \ldots$ and $t$ continues as $1, 0, 0, 0, \ldots$
Proof.
From the definition of $s \prec t$ we have $n$ such that $s$ and $t$ agree up to $n$ (exclusively) and then $0 = s(n) < t(n) = 1$. Let $s^*$ be an infinite sequence defined as $s \upharpoonright n$ followed by $0, 1, 1, 1, \ldots$ Similarly, let $t_*$ start with $t \upharpoonright n$ and continue as $1, 0, 0, 0, \ldots$
Note that for each $k \in \mathbb{N}$ we have $\beta( s \upharpoonright k) \leqslant \beta( s^* \upharpoonright k )$ since $s$ and $s^*$ agree up to $n+1$and then $s^*$ becomes constantly $1$. Therefore $\varphi(s) \leqslant \varphi(s^*)$ since multiplying things by $1-x$ makes them greater than multiplying by $x$. Similarly we prove that $\varphi(t_*) \leqslant \varphi(t)$.
It's also easy to see that if $u, v$ are infinite binary sequences and $f \in \{ 0, 1 \}^m$ is a finite binary sequence such that $u = f \frown v$ (where $\frown$ denotes contatenation), then

*

*if $k < m$, then $\alpha( u \upharpoonright k ) = \alpha( f \upharpoonright k )$ and $\beta( u \upharpoonright k ) = \beta( f \upharpoonright k ),$

*for $k \geqslant 0$: $\alpha( u \upharpoonright (m+k) ) = \alpha( f ) + \alpha( v \upharpoonright k )$ and $\beta( u \upharpoonright (m+k) ) = \beta( f ) + \beta( v \upharpoonright k ).$

Hence
$$\varphi(u) = \sum_{k=0}^{m-1} x^{\alpha(f \upharpoonright k)} (1-x)^{\beta(f \upharpoonright k)} + x^{\alpha(f)} (1-x)^{\beta(f)} \cdot \varphi(v).$$
Taking $f$ to be the common preffix of $s$ and $t$, i.e. $f = s \upharpoonright n = t \upharpoonright n$, we obtain
$$\varphi(s^*) = \sum_{k=0}^{m-1} x^{\alpha(f \upharpoonright k)} (1-x)^{\beta(f \upharpoonright k)} + x^{\alpha(f)} (1-x)^{\beta(f)} \cdot \varphi(0, 1, 1, 1, \ldots) \\[1ex]
\varphi(t_*) = \sum_{k=0}^{m-1} x^{\alpha(f \upharpoonright k)} (1-x)^{\beta(f \upharpoonright k)} + x^{\alpha(f)} (1-x)^{\beta(f)} \cdot \varphi(1, 0, 0, 0, \ldots).$$
Computing $\varphi(0, 1, 1, 1, \ldots) = 2 = \varphi(1, 0, 0, 0, \ldots)$ yields $\varphi(s^*) = \varphi(t_*)$, so $\varphi(s) \leqslant \varphi(t)$.
Now if $\varphi(s) = \varphi(t)$, then $\varphi(s) = \varphi(s^*)$ and $\varphi(t_*) = \varphi(t)$, which clearly implies $s = s^*$ and $t = t_*$, so the claim has been proved.
Now let $A \subseteq \{ 0, 1 \}^{\mathbb{N}}$ be the set of all infinite binary sequences eventually stabilizing at $1$. From the above fact, the restriction of $\varphi$ to $\{ 0, 1 \}^{\mathbb{N}} \setminus A$ is strictly increasing, hence injective. But $A$ is countable, so $|\{ 0, 1 \}^{\mathbb{N}} \setminus A| = \mathfrak{c}$, thus $\varphi \left[ \{ 0, 1 \}^{\mathbb{N}} \right]$ has cardinality $\mathfrak{c}$ so in particular is uncountable.
Further insight
In this section I will provide less details and concentrate on how it is rather than why it is true. Hopefully you can fill the gaps if you're interested.
The set $\{ 0, 1 \}^{\mathbb{N}}$ can be regarded as a metric space known as the Cantor set with the metric defined as
$$d( s, t ) = \begin{cases} 0 & \text{if } s = t \\ 2^{-\min \{ n : s(n) \neq t(n) \}} & \text{otherwise} \end{cases}$$
It's not hard to see that the map $\varphi$ is continuous, because if $s, t$ agree up to $n$, i.e. $s = f \frown u$ and $t = f \frown v$ for some $f \in \{ 0, 1 \}^n$ and $u, v$ infinite, then
$$|\varphi(s) - \varphi(t)| = x^{\alpha(f)} (1-x)^{\beta(f)} \cdot |\varphi(u) - \varphi(v)| \leqslant (1-x)^n \cdot \left[ \frac{1}{x} - \frac{1}{1-x} \right]$$
so the difference can be made arbitrarily small by making $n$ large. Now the fact proven above implies that $\varphi = \psi \circ p$ for some continuous $\psi : [0, 1] \to \mathbb{R}$, where $p : \{ 0, 1 \}^{\mathbb{N}} \to [0, 1]$ is the standard continuous surjection
$$p(s) = \sum_{n=0}^{\infty} \frac{s(n)}{2^{n+1}}.$$
Since $\psi$ is continuous, from the Darboux property it is onto $\left[ \frac{1}{1-x}, \frac{1}{x} \right]$, thus so is $\varphi$.
So every number $y \in \left[ \frac{1}{1-x}, \frac{1}{x} \right]$ can be obtained as a sum over a path $s \in \{ 0, 1 \}^{\mathbb{N}}$ which is unique up to the case described by the fact we have proven.

A: The more usual way to draw this is as a binary tree, so the downward paths do not come to the same vertex.  Then you have one vertex at the root, two at the next level, four at the next, and $2^n$ at level $n$.  As you traverse the tree you add a bit to the binary number that is the sum, $0$ if you take the left fork and $1$ if you take the right.  Then it is clear that you can have any number in $[0,1]$ as the sum, so there are an uncountable number of possible sums.  There are only countably many vertices in the tree, whether it is $1+2+3+4+\ldots$ or $1+2+4+8+\ldots$


text:
Q: Getting bad request in twitch helix api I'm trying to make twitch notifications for a discord server, but i get a bad request response of the twitch api. Here is my code:
from schildi import utils
from static import config
import requests
import json

client = utils.client

class stream_notifications(utils.cog):
    def __init__(self, client):
        self.client = client

    r = requests.post(
        f"https://id.twitch.tv/oauth2/token?client_id={config.CLIENT_ID}&client_secret={config.CLIENT_SECRET}&grant_type=client_credentials")
    r_json = r.json()
    print(r_json["access_token"])
    headers = {
        "Authorization": f"Bearer {r_json['access_token']}",
        "Client ID": config.CLIENT_ID,
    }
    twitch_info = requests.get(f"https://api.twitch.tv/helix/search/channels?query=sirellasama",
                             headers=headers)
    print(twitch_info.text)

    @utils.cog.listener()
    async def on_ready(self):
        print(1)

def setup(client)
    client.add_cog(stream_notifications())

As response i get 400 Bad Request, but the channel i am searcing for exists and i gave the required "query" parameter.
Can anyone help me with this error? I don't know what i am doing wrong

A: I've fixed the problem by myself, just by making a new application.


text:
Q: Add attributes to DataColumn I am creating a reporting component that takes an IEnumerable input and performs some transformations and aggregations and returns a new IEnumerable with a dynamic number of columns. I am using ADO.NET for this because it is easy to create a DataTable with the appropriate columns.
The transformed IEnumerable is sent to a reporting visualization component that uses information stored in Attributes to format the results nicely. It's not necessary to be able to remove or change the attributes once they have been applied.
My question is this:
Is it possible to associate an Attribute with a DataColumn so that the PropertyDescriptor emitted by the ADO.NET DataView includes these Attributes?
Follow-up question:
If this is not possible with ADO.NET are there other libraries that I can use to accomplish this?
Edit: Update for clarity
I would like to be able to do something like this:
DataTable dt = new DataTable();
DataColumn example = dt.Columns.Add("Test",typeof(double));

//This is the functionality I am looking for ideally
example.AddAttribute(new CustomAttribute("Hello"));

public class CustomAttribute : Attribute
{
}

A: See the ExtendedProperties property on DataColumns. This allows you to add custom data to a datacolumn. You would have to write the code that uses this custom data yourself, however - the formatting (or what ever you intend the data to be used for) isn't automatic.

A: To answer my own question: It's not possible to inject attributes into a DataColumn and have them appear in the PropertyDescriptor that DataView's implementation of ITypedList emits


text:
Q: Octave GNU: Undefined variable 'x' , even though it's defined as function input just trying to write a simple program to find the gcd of n numbers. I have no clue how to fix this error, i've read all of octaves function documentation and tried to find questions like this ... Just started programming in Octave btw.
Here's the code:
function divisor = gcd(x, y)
  q=0;
  r=0;
  l=0;
  h=0;
  if(x>y)
    h=x;
    l=y;
 elseif(x<y)
    h=y;
    l=x;
 else
    h=y;
    l=x;
 endif
 while(r != 0)
    q=floor(h/l);
    r = h-l*q;
    q=h;
    r=l;
 endwhile
 divisor = q;
 printf("%d", q);
 return;
endfunction

The Error:
error: 'x' undefined near line 6 column 6
error: called from
     gcd at line 6 column 3

A: Your code is a function definition. Your function is called gcd.
You have to save your code in a file called gcd.m and then create a new file so that you can call that function from it.
In the same directory you have saved gcd.m, create a file (for example: gcdtest.m) and put the following code in it:
test = gcd(40, 50)

Then save and run this file. If the output doesn't work as expected, restarting Octave should fix it.
The numbers I've chosen are only an example.

Explanation:
If all you have is the function definition file (i.e. gcd.m), when you hit "Save and run", Octave will itself call your function, but it's not clever enough and won't use any parameters in doing so. That's why you get  an "undefined variable" error. That would be similar to you having only test = gcd() in your test file.
If, however, you call the function with the arguments, they will initialize the variables x and y correctly and your code will work.
You can also simply call gcd(40, 50) from the Octave command line, for testing purposes.
The following are links to the Octave documentation regarding functions and function files (I know you said you read them, but newcomers might not have):
https://www.gnu.org/software/octave/doc/interpreter/Defining-Functions.html
https://www.gnu.org/software/octave/doc/interpreter/Function-Files.html

Now, I noticed a couple of issues in your code:

*

*while(r != 0) on line 16 - this won't run, not even once, since you define r as 0 in line 3 and don't assign a new value to it later.

*elseif(x<y) (line 9) and else (line 12) both do exactly the same thing. It would be better to remove the elseif condition entirely and only have else instead.

A: Octave assumes any code starting with the function keyword is a so-called "function file" that must only be called from a "script file". If you want to prevent this absurd confusion, just add anything above your code. For example:
1;
function foo = bar(baz)
    % do some stuff
end

More information here.


text: Q: Comic book about dinosaurs in space The comic book I'm talking about is about this one T. rex-like dinosaur being frozen in a cryo-pod after trying to rejoin his father on Earth, who was holding off some sort of black ooze from getting to the other dinosaurs. The dinosaurs were evacuating earth to escape from this black ooze. Eventually, humans dig up the remains of the battle and the cryopod. The group of humans want to excavate a fuel source from that area, and have hired or have forced a doctor to help them. The doctor brings along his daughter, who is the main companion for the t-rex dinosaur. The humans activate the cryopod and release the T. rex dinosaur. After a skirmish, the black ooze is also released. The ooze corrupts and absorbs the humans except for the doctor's daughter, and the dinosaur takes the daughter with him to protect her. I think that's what happens. Then a distress signal is sent out somehow, and a group of intergalactic dinosaurs come and rescue them. One of them is a grumpy triceratops. Another is a really tech-savvy, green, female dinosaur.


text:
Q: Cannot install Tensorflow 2.4.1 as a dependency for OpenVino When going through the process of installing OpenVino as documented here, I'm running:
sudo ./install_prerequisites.sh

and getting
ERROR: Could not find a version that satisfies the requirement tensorflow~=2.4.1 (from versions: 2.5.0rc0, 2.5.0rc1, 2.5.0rc2, 2.5.0rc3, 2.5.0, 2.5.1, 2.5.2, 2.6.0rc0, 2.6.0rc1, 2.6.0rc2, 2.6.0, 2.6.1, 2.6.2, 2.7.0rc0, 2.7.0rc1, 2.7.0, 2.8.0rc0)
ERROR: No matching distribution found for tensorflow~=2.4.1

As suggested in the documentation, you can configure frameworks individually if there are errors. However, even using pip it doesn't seem there is a matching distribution for Tensorflow 2.4.1:
pip install tensorflow==2.4.1

ERROR: No matching distribution found for tensorflow==2.4.1

How can you get Tensorflow 2.4.1 installed?

A: I've already shown you how to debug such problems. Well, let's see.
The list of available packages for tensorflow 2.4.1 includes wheels for Python 3.6-3.8. No 3.9 and no source code. Wheels for Python 3.9 are available starting from tensorflow 2.5.0rc0 — exactly like is said in the error message.
What can you do? 1) Downgrade once more, to Python 3.8. Or 2) Use more recent OpenVino source code; the current sources at GitHub list tensorflow~=2.5 as a dependency. Or 3) Find in your downloaded sources files requirements*.txt and replace version tensorflow~=2.4.1 with 2.5.0.


text:
Q: PHP Counter overwraps/overflows only 1 byte of data, counter resets (race condition) I know this is a simple question but I downloaded a PHP Counter script from http://www.stevedawson.com/scripts/text-counter.php
which is the first result on google for PHP counter scripts and it worked great as expected.
I tried to see if it messes up by holding refresh in my browser after 255 requests it overflowed back to 0. How would I fix this script? I think the culprit is the filesize() which probably gets only 1 byte of data but it doesn't make sense since 255 is actually 3 bytes of data right? since it saves in plain-text format?
Why would it overflow? it's even PHP it shouldn't overflow just automatically mutate into a bigger datatype.
<?php
    $orderCountFile = "order_num_count.txt";
    if (file_exists($orderCountFile)) {
        $fil = fopen($orderCountFile, r);
        $dat = fread($fil, filesize($orderCountFile));
        echo $dat+1;
        fclose($fil);
        $fil = fopen($orderCountFile, w);
        fwrite($fil, $dat+1);
    } else {
        $fil = fopen($orderCountFile, w);
        fwrite($fil, 1);
        echo '1';
        fclose($fil);
    }
?>

Yeah I started to remake the script into another purpose I want to use it to keep track of order numbers for my website.
For a fix I think I have to recast $dat into a bigger integer type but can you even cast in PHP?
Also those r and w are suppose to be strings i think but they are used as constants but it doesn't seem to cause any troubles afaik.

A: Use file_get_contents and file_put_contents instead. You still have to consider, that there is a hard limit for that counter as well (see PHP_INT_MAX), but it's significantly higher.
<?php
$file = "counter.txt";
$counter = 0;
if (file_exists($file)) {
  $counter = file_get_contents($file);
}

$counter = $counter + 1;
file_put_contents($file, $counter);
echo $counter;


text:
Q: Use of if (typeof(obj._source.url) !== 'undefined') expresion in jsontohtml I am consulting two different json data sources, job1 and job2, with the same code that runs with jsontohtml.
Each source has different labels, although with similar name, some have different name beetween them or different json structure.
I want to detect when a label is defined to show it in html, while if is undefined not show it.
The problem is when I check if the corresponding parameter-object is already defined by next command
if (typeof(obj._source.file.url) !== 'undefined')

I get the following error
Uncaught TypeError: Cannot read property 'url' of undefined

the complete code is

    <meta charset='UTF-8' />
    <title>JSON Visualizer</title>

<link rel="stylesheet" href="./tablaX.css">

if you comment the code of the following line, which is the one that gives me the error, my jsontohtml code will work without problem
if (typeof(obj._source.file.url) !== 'undefined') { http = obj._source.file.url.replace("file://", ""); return("" + http + ""); };    //job 1 source

The source data of the source job1 is
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 5,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "2e2ed07786c01e9fd845b62fb86a693a",
        "_score" : 1.0,
        "_source" : {
          "content" : """hola
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-03T11:57:45.673+0000",
            "last_modified" : "2020-04-23T07:33:50.725+0000",
            "last_accessed" : "2020-04-23T07:33:50.725+0000",
            "indexing_date" : "2020-04-23T10:33:46.954+0000",
            "filesize" : 4,
            "filename" : "fichero0_borrador.txt",
            "url" : """file://C:\TMPM\carpeta0\99.Borrador\fichero0_borrador.txt"""
          },
          "path" : {
            "root" : "4cface21f575d5e5985e4e3889c278a3",
            "virtual" : "PM/carpeta0/99.Borrador/fichero0_borrador.txt",
            "real" : """C:\TMPM\carpeta0\99.Borrador\fichero0_borrador.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "6f475ff7ac21fc59f4edc34761d09",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadena0 A
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-14T09:30:20.218+0000",
            "last_modified" : "2020-04-14T09:46:02.930+0000",
            "last_accessed" : "2020-04-14T09:46:02.930+0000",
            "indexing_date" : "2020-04-23T10:33:47.533+0000",
            "filesize" : 9,
            "filename" : "fichero0_A.txt",
            "url" : """file://C:\TMPM\carpeta0\fichero0_A.txt"""
          },
          "path" : {
            "root" : "c073f96a8d16ebb2e604bebd4fe8b40",
            "virtual" : "PM/carpeta0/fichero0_A.txt",
            "real" : """C:\TMPM\carpeta0\fichero0_A.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "7dfb102f2e64e99740a89b1cff7d92a3",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadena1
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-03T11:56:21.165+0000",
            "last_modified" : "2020-04-03T12:23:23.872+0000",
            "last_accessed" : "2020-04-03T12:23:23.872+0000",
            "indexing_date" : "2020-04-23T10:33:47.568+0000",
            "filesize" : 7,
            "filename" : "fichero1.txt",
            "url" : """file://C:\TMPM\carpeta1\fichero1.txt"""
          },
          "path" : {
            "root" : "7ff4e7b0e0c3172dbd29a23861ab2125",
            "virtual" : "PM/carpeta1/fichero1.txt",
            "real" : """C:\TMPM\carpeta1\fichero1.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "74f0e8c1cccf2f32b4d43673cfdca0",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadena2
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-03T11:56:30.524+0000",
            "last_modified" : "2020-04-03T12:23:35.029+0000",
            "last_accessed" : "2020-04-03T12:23:35.029+0000",
            "indexing_date" : "2020-04-23T10:33:47.579+0000",
            "filesize" : 7,
            "filename" : "fichero2.txt",
            "url" : """file://C:\TMPM\carpeta2\fichero2.txt"""
          },
          "path" : {
            "root" : "fd0c8ae8a885725cfcaee774c72be43",
            "virtual" : "PM/carpeta2/fichero2.txt",
            "real" : """C:\TMPM\carpeta2\fichero2.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "8d6c56c0448bc4bfa17787923baa9c",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadenaX
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-14T15:12:56.632+0000",
            "last_modified" : "2020-04-14T15:34:53.139+0000",
            "last_accessed" : "2020-04-14T15:34:53.139+0000",
            "indexing_date" : "2020-04-23T10:33:47.587+0000",
            "filesize" : 7,
            "filename" : "fichero_X.txt",
            "url" : """file://C:\TMPM\carpetaX\fichero_X.txt"""
          },
          "path" : {
            "root" : "f43118a935c6c7ef81ea65307759fc",
            "virtual" : "PM/carpetaX/fichero_X.txt",
            "real" : """C:\TMPM\carpetaX\fichero_X.txt"""
          }
        }
      }
    ]
  }
}

Thanks in advance

A: According to the error file is undefined in obj._source.file.url. Try
if (typeof obj._source.file !== 'undefined') {
    if (typeof obj._source.file.url !== 'undefined') {
        http = obj._source.file.url.replace("file://", ""); return("" + http + "");
    };
};    //job 1 source

A: The code that I added was one of many tests that I have done, in which I left the famous incorrect parentheses. I'm aware that I am going to find my object obj._source.file in an undeclared and undefined state. Precisely because the json it will receive will change its definition and structure (it is a mix of several jsons). And precisely because of that, I used typeof obj._source.file! == 'undefined' as Google replied "Use the typeof operator: If you want to check whether a variable has been initialized or defined (ie test whether a variable has been declared and assigned a value) you can use the typeof operator."
Finally I used
 if (obj && obj._source && obj._source.file && obj._source.file.url) {...}

by Jared Farrish with good result. Thank you


text:
Q: Difference between @propertyWrappers, asserts/precondition, init? and error handling in imposing restrictions on Structs I was wondering how I can enforce the following restrictions on this struct:
struct QandA {
    let questions: [String]  // Question to be displayed per page
    let mcqs: [[String]]  // Prompts to be displayed per page
    let answers: [Int]  // Answer will be the correct index
}

*

*questions.count == mcqs.count == answers.count

*forEach mcq in mcqs, mcq.count == 4 (must only be 4 options per mcq)

*forEach answer in answers, answer < 4 (correct index must be 0...3)

The reason for this is that I think it would be very easy to perhaps, add an extra question, or even say the correct answer is 4 when I meant to put 3 (off by 1 error), and also add an extra prompt when there are only meant to be 4 multiple choices per question.
To protect myself from these errors here is what I think I can do:
Option 1
init?(questions: [String], mcqs: [[String]], answers: [Int]) {
        guard
            questions.count == mcqs.count && mcqs.count == answers.count,
            mcqs.allSatisfy({ $0.count == 4 }),
            answers.allSatisfy({ $0 < 4 })
        else {
            return nil
        }

        self.questions = questions
        self.mcqs = mcqs
        self.answers = answers
    }

Option 2
init(questions: [String], mcqs: [[String]], answers: [Int]) {
        assert(questions.count == mcqs.count && mcqs.count == answers.count)
        assert(mcqs.allSatisfy({ $0.count == 4 }))
        assert(answers.allSatisfy({ $0 < 4 }))

        self.questions = questions
        self.mcqs = mcqs
        self.answers = answers
    }

Option 3
Have my Views deal with these issues and have no management code for initialisation; perhaps use try-catch blocks somewhere?
Option 4
Just make sure I don't mess up when creating QandA's
My question is whether I should not allow a QandA instance to be initialised unless these restrictions are met (option 1); or should I add preconditions / asserts to not allow my code to continue if I mess up somewhere (option 2); or should my app just allow these things and me as a coder should take on the full responsibility of making sure the data is consistent, possibly making use of error handling (option 3 & 4). Perhaps using a @propertyWrapper may be the best option? What even are the pro's and con's of these different approaches?
I'm also wondering what is considered "best practice" for situations like this.
Thanks in advance.

A: If you really want to exclude invalid states, then you could consider modelling your quiz like this:
struct QandA {
    let question: String

    struct Right {
        let value: String
    }
    struct Wrong {
        let value: String
    }

    enum Options {
        case A(Right, Wrong, Wrong, Wrong)
        case B(Wrong, Right, Wrong, Wrong)
        case C(Wrong, Wrong, Right, Wrong)
        case D(Wrong, Wrong, Wrong, Right)
    }

    let options: Options
}

struct Quiz {
    let questions: [QandA]
}

Here you can't have more than 4 (3 wrong + 1 right), and you must have exactly one right answer in the options.
If you find that you have two collections, e.g. [A] and [B] and you need them to be the same size always, you probably mean to say you have an array of pairs of A's and B's, like [(A, B)], and often where you have tuples, like pairs, then there's a named Struct that's waiting to be created.
You almost always want to make your data structure smart so your algorithms don't have to be.  Use knowledge of "type algebra" to refactor invalid states out of existence - a classic example you can find online if you search, is the refactoring of the types in the completion handler of URLSession dataTask(with:completionHandler:) - some of which are not valid - into a type that make those invalid states inexpressible.  The key idea is that sum types (enum) and product types (structs) can be thought of just like algebra A+B and A*B, and can be literally refactored just the same.


text:
Q: firebase RTDB startAfter() is not a function I am trying to paginate a list of items with Vuefire, and for some reason I am getting an error with the below code (when I call startAfter(), the function works fine with startAt())
lastVisible is an object in my component's state with the property expire_date (a UNIX timestamp)
This is the error I get
Any idea what is wrong?
    async seeFurtherGames() {
      var games_ref = db.ref('games')
      console.log("GameBrowser.seeOlderGames()", this.lastVisible, games_ref)
      if (this.lastVisible) {
        var start = this.lastVisible.expire_date
        var query = games_ref.orderByChild('expire_date').startAfter(start).limitToFirst(this.item_limit)
        await this.$bind("games", query)
        this.setLastVisible()

      }
    }

Uncaught (in promise) TypeError: games_ref.orderByChild(...).startAfter is not a function
    at _callee3$ (webpack-internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/GameBrowser.vue?vue&type=script&lang=js&:257)
    at f (chrome-extension://bfnaelmomeimhlpmgjnjophhpkkoljpa/content_script/inpage.js:141)
    at Generator._invoke (chrome-extension://bfnaelmomeimhlpmgjnjophhpkkoljpa/content_script/inpage.js:141)
    at Generator.next (chrome-extension://bfnaelmomeimhlpmgjnjophhpkkoljpa/content_script/inpage.js:141)
    at asyncGeneratorStep (webpack-internal:///./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:9)
    at _next (webpack-internal:///./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:31)
    at eval (webpack-internal:///./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:38)
    at new Promise (<anonymous>)
    at eval (webpack-internal:///./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:27)
    at VueComponent.seeFurtherGames (webpack-internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/GameBrowser.vue?vue&type=script&lang=js&:270)

A: The startAfter and endBefore operations in the Firebase Realtime Database were introduced in version 8.2.7 of the JavaScript SDK.

A: I was able to fix this problem by upgrading firebase from v8 to v9


text:
Q: ASP.NET Session Problem in ASHX and using Google Chrome and Firefox Am not sure why when using IE, retrieving session values works just fine, but when using Google Chrome and Firefox, it's not returning any?
I have already included IRequiresSessionState/IReadOnlySessionState in generic handler class, but still did not work.
So my last resort was to add my session values as a query string in generic handler.
But I still want to know why and what's wrong in Chrome and Firefox? Thanks.
UPDATE:
here's the way I handle my Seesion SessionManager
It works perfectly in ASPX pages and in IE, Chrome, and Firefox
but when used in my ASHX page. sample code below

<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.IO;

public class Upload : IHttpHandler, IReadOnlySessionState
{
    SessionManager sm;

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;

        sm = new SessionManager();

        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];

            string uploadedas = string.Empty;
            if (context.Request.QueryString["as"] != null)
            {
                uploadedas = context.Request.QueryString["as"];
            }

            string username = sm.Username;
            string sessionid = sm.SessionID;

            //
            // MORE CODES HERE
            //

            context.Response.Write(response);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message + "\r\n\r\n" + ex.StackTrace);
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

sm.Username and sm.SessionID returns an emptry string when Chrome and Firefox is used.. but as I said earlier, those are working perfectly in ASPX pages even in different browsers.

A: A session is a type of cookie.  Make sure you have cookies enabled on all the browsers you are testing in.

A: How are you calling your ashx from your page? Can you give sample code?
Do you use Flash to call the ashx? Flash has a cookie bug that always sends IE cookies to the server whichregardless of which browser you are using which makes accessing ASP.NET Session hard since it relies on a cookie.


text:
Q: Bind kendo.data.datasource json data to kendo listview Category1 works but category doesn't. Both have same data. But category is a json response.
category is
{
    "d": [
        {"__type": "MenuData+Category", "id": 1, "name": "drinks"},
        {"__type": "MenuData+Category", "id": 2, "name": "fruits"}
    ]
}

Do I remove the d. If so how do i do it? If not whats wrong?

A: You have placed schema inside transport definition while it is member of DataSource.
Try:
category = new kendo.data.DataSource({
    serverFiltering: true,
    transport      : {
        read: {
            type       : "POST",
            url        : "http://localhost:60143/Mobile/Menu/MenuData.asmx/getCategory",
            contentType: "application/json; charset=utf-8",
            dataType   : "json",
            error      : function (xhr, ajaxOptions, thrownError) {
                alert("error " + xhr.responseText);
            }
        }
    },
    schema         : {
        data: "d"
    },
    type           : "json",
    parameterMap   : function (options) {
        return JSON.stringify(options);
    }
});


text:
Q: howto refresh all sheets after protect sheet in excel My excel file have 2 sheets
with named "A" and "B"
Both sheets showed the data from 6 queries (6 connection name) with view of sql server
Ordinary when I want to update the data in excel file,
I press "refresh all"
but when I protect sheet
"refresh all" can't process
How Do I refresh all sheets including those with protection.

A: check out this solution
How to protect cells in Excel but allow these to be modified by VBA script
https://stackoverflow.com/a/126032/6868389

A: my code is work if time for "refresh all" is a short time
but for my case
"refresh all" take time about 15 minutes
and "protect sheet" process is begin to process before "refresh all" process has done