text:
Q: Detecting that back pressure is happening My Akka HTTP application streams some data via server-sent events, and clients can request way more events than they can handle. The code looks something like this
complete {
  source.filter(predicate.isMatch)
   .buffer(1000, OverflowStrategy.dropTail)
   .throttle(20, 1 second)
   .map { evt => ServerSentEvent(evt) }
}

Is there a way to detect the fact that a stage backpressures and somehow notify the client preferably using the same sink (by emitting a different kind of output) or if not possible just make Akka framework call some sort of callback that will deal with the fact through a control side-channel?

A: So, I'm not sure I understand your use case. Are you asking about back pressure at .buffer or at .throttle? Another part of my confusion is that you are suggesting emitting a new "control" element in a situation where the stream is already back pressured. So your control element might not be received for some time. Also, if you emit a control element every single time you receive back pressure you will likely create a flood of control elements.
One way to build this (overly naive) solution would be to use conflate.
  val simpleSink: Sink[String, Future[Done]] =
    Sink.foreach(e => println(s"simple: $e"))

  val cycleSource: Source[String, NotUsed] =
    Source.cycle(() => List("1", "2", "3", "4").iterator).throttle(5, 1.second)

  val conflateFlow: Flow[String, String, NotUsed] =
    Flow[String].conflate((a, b) => {
      "BACKPRESSURE CONTROL ELEMENT"
    })

  val backpressureFlow: Flow[String, String, NotUsed] =
    Flow[String]
      .buffer(10, OverflowStrategy.backpressure) throttle (2, 1.second)

  val backpressureTest =
    cycleSource.via(conflateFlow).via(backpressureFlow).to(simpleSink).run()

To turn this into a more usable example you could either:

*

*Make some sort of call inside of .conflate (and then just drop one of the elements). Be careful not to do anything blocking though. Perhaps just send a message that could be de-duplicated elsewhere.

*Write a custom graph stage. Doing something simple like this wouldn't be too difficult.
I think I'd have to understand more about the use case though. Take a look at all of the off the shelf backpressure aware operators and see if one of them helps.


text:
Q: Application.ScreenUpdating won't change to false I'm pretty new to VBA, but I've found my way around by reading through these forums. I've never had a problem with Application.ScreenUpdating not working and after researching online, I can't find an answer to my problem.
I've created a Daily Checklist application in excel that gives a month view in the Daily Checklist. The tasks line up in rows and you simply select yes, no or N/a, for that task for the day on the calendar. You can save the checklist and it copies the information to a data sheet in a separate tab. Everything works perfectly except when saving the information the Application.Screenupdating isn't working and the user ends up seeing the flickering and jumping back and forth between the data sheet and the calendar view.
Any ideas or guidance on why Application.ScreenUpdating is not changing to false? I've tried moving it around in different areas, but nothing seems to work.
Here's the Save checklist sub:
Sub Save_Checklist()

Dim Checklist_Date
Dim Completed As Long
Dim Left_to_Complete As Long
Dim Database_Date As Range
Dim Database_Row As Long
Dim bScrUpdate

bScrUpdate = Application.ScreenUpdating
If bScrUpdate = True Then Application.ScreenUpdating = False

Worksheets("Database").Unprotect Password:="youngC"

If MsgBox("This button will save this month's checklist data into the database. All previous information will be overwritten. Would you like to continue?", vbYesNoCancel, "Reset the Calender") = vbYes Then

Checklist_Date = Worksheets("Daily Checklist").Range("E4").Value
Add_to = Worksheets("Daily Checklist").Range("AL1").Value
Range("E55").Select
ActiveCell.Resize(2, Add_to).Select
Selection.Copy

    On Error Resume Next
    With Worksheets("Database").Activate
        Range("A1:A366").Select
        Selection.Find(What:=Checklist_Date, After:=ActiveCell, LookIn:=xlValues, LookAt:= _
            xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
            , SearchFormat:=False).Select
    On Error GoTo 0
        If Not Database_Date Is Nothing Then Application.Goto Database_Date, True
    End With

Selection.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True

Worksheets("Database").Protect Password:="youngC"

Else
    MsgBox ("Please be sure all information is correct before saving it.")
End If

If Not Application.ScreenUpdating = bScrUpdate _
    Then Application.ScreenUpdating = bScrUpdate

End Sub

This is the code I have running upon the workbook opening (I have grouping in the "Add Tasks to Month's Calendars" sheet):
Private Sub Workbook_Open()
    Worksheets("Main Menu").Activate
    With Worksheets("Add Tasks to Month's Calendars")
    .EnableOutlining = True
    .Protect Password:="youngC", _
    Contents:=True, UserInterfaceOnly:=True
    End With
End Sub

Any help at all would be greatly appreciated.
Thanks,
Chris

A: Personally I would just set the screenupdating property to false without checking it, once the VBA has finished running the screen will update as normal.
Also I think that the problem is that the second peice of code that runs when you open the worksheet does not turn screenupdating to false so you will see all the movements you described. Excel doesn't remember that the screenupdating was set to false by a previous macro and even if it did the code you have turns it back on anyway. You should be able to solve this by setting screenupdating to false on your first line, the modification is shown below.
Private Sub Workbook_Open()
    Application.ScreenUpdating = False
    Worksheets("Main Menu").Activate
    With Worksheets("Add Tasks to Month's Calendars")
    .EnableOutlining = True
    .Protect Password:="youngC", _
    Contents:=True, UserInterfaceOnly:=True
    End With
End Sub

A: If you print to debug during run the state of it, it will be false, but when you are in debug mode, then it will be always true as your code is in pause mode and this switches back to true automatically until you run it again in "fast" mode

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the rank of this well founded relation? Definition A tree is an ordered list of trees. (N.B these are finite objects and there is a very simple computable bijection of them with $\mathbb N$)
Examples [] and [[],[],[]] and [[[]],[[],[],[]],[[],[],[[]]]] but it's much better to think of them like this (can ignore the colors for now)
I was wondering what is the rank of the lexicographic order on trees?

Formally, we will write a:b for a list of trees whose first element is r and rest is b (r is red in the diagram and b is blue)
$(h:t) <_T (h':t')$ when

*

*$h=h'$ and $t <_T t'$

*$h <_T h'$ and $t$,$'t$ can be anything (e.g. $t$ could be enormously large compared to $t'$)

and this relation is well founded (I claim)

It is clear that the rank is bigger than $\omega$ since you can embed the naturals into 0=[], 1=[[]], 2=[[[]]], 3=[[[[]]], ... just long chains.
You easily embed $\omega+1$ because $[[],n] <_T [[[]],[]]$ for $n$ corresponding to any natural number tree - but by a similar idea we easily embed $\omega^2$. It seems like the rank of this is large.
Note, this is the same as the relation on http://math.andrej.com/2008/02/02/the-hydra-game/ and I expect has smaller rank.
I am not very comfortable with these notions, so I want to get a rigorous proof in the end - but for now I don't even know the answer.

A: Are you sure this relation is well founded? For clarity, let $\bot = []$, the empty list.
Consider the following sequence:
\begin{align}
T_0 &= \big[[\bot,\bot],\bot\big] \\
T_1 &= \big[\bot,T_0\big] = \Bigg[\bot,\bigg[[\bot,\bot],\bot\bigg]\Bigg]\\
&\ \vdots \\
T_k &= \big[\bot,T_{k-1}\big]
\end{align}
Assuming that $\bot <_T [\bot,\bot]$ (you haven't defined this case), we have
$$T_1 <_T T_0,$$
that is
$$\bot : T_0 <_T [\bot,\bot] : \bot,$$
hence
$$T_k <_T T_{k-1}$$
and we have an infinite strictly decreasing sequence.
I hope this helps ;-)


text:
Q: Task Manager Up Time differs from systeminfo System Boot Time In troubleshooting some issues with a Windows Server 2008 R2 box, I noticed that the Up Time in Task Manager was huge whereas the System Boot Time in systeminfo is seemingly correct. Can anyone tell me why these might be different? This is a virtual server.

A: It looks about right to me.

Different areas of the operating system may use different counters and slightly different arithmetical formulae and different levels of rounding/precision.  The "Task Manager" guy and the "systeminfo" guy probably aren't arriving at the same "up time" in exactly the same way.  But they're both "close enough."
I like this little blog post from Raymond Chen as an illustrative example of what I mean:
http://blogs.msdn.com/b/oldnewthing/archive/2014/11/13/10572050.aspx
Or maybe I overthought this and you simply thought that the "266" referred to days instead of hours.


text:
Q: Channel Views from YouTube API? I am looking to get the amount of channel views a YouTube channel has through their API.
I have been looking through the documentation and been googling but I cannot seem to find how.
Channel views aren't being shown on actual channels anymore but they are being shown on the mobile site (example) and also there are sites which are tracking them still (example) so I assume that they must be available via the API.
If anyone knows how they are available (preferably outputted with JSON) I would appreciate it, thanks.

A: I managed to figure it out for anyone wanting to know, this is using PHP and JSON, using Google's youtube channel as an example.
The URL is: http://gdata.youtube.com/feeds/api/users/Google?alt=json
To parse it you would do:
$json = file_get_contents("http://gdata.youtube.com/feeds/api/users/Google?alt=json");
$data = json_decode($json, true);
echo 'Channel Views: ' . $data['entry']['yt$statistics']['viewCount'];


text:
Q: Loop for Enums in Java I have some enums like this:
public enum Classification {
    UNKNOWN("Unknown"),
    DELETION("Deletion"),
    DUPLICATION("Duplication"), ....

but some of them have like 20 members, so currently in code I deal with them with huge if/else blocks like this:
int classification= rs.getInt("classification");
        if (classification == Classification.UNKNOWN.ordinal()) {
            variant.setClassification(Classification.UNKNOWN);
        } else if (classification == Classification.DELETION.ordinal()) {
            variant.setClassification(Classification.DELETION);

( rs is from JDBC tho).
Does Java have a better way this these big if/else blocks to do what I am doing? some sorting of looping through it?

A: If the db value is the ordinal of the Enum then:
int classification= rs.getInt("classification");
variant.setClassification(Classification.values()[classification]);

I'll leave bounds checking as an exercise for the reader.

A: You could use Enum#values() to get all enum values in an array. The ordinal maps 1:1 to the array index. Add the following method fo your Classification enum:
public static Classification of(int ordinal) {
    if (0 <= ordinal && ordinal < values().length) {
        return values()[ordinal];
    }
    throw new IllegalArgumentException("Invalid ordinal " + ordinal);
}

and use it as follows
Classification classification = Classification.of(rs.getInt("classification"));
// ...

However, using enum's ordinal for this is not the best practice. What if some developer rearranges the enum's values or adds/removes values? Even the javadoc warns that it has usually no use for developers. Rather give each enum value a fixed identifier. You could pass it in as an additional argument of the enum constructor argument. You could even use enum's String representation for that.
UNKNOWN(1, "Unknown"),
DELETION(2, "Deletion"),
DUPLICATION(3, "Duplication"),
// ...

Then use that value for DB instead and modify the of() method to walk through them in a foreach loop:
public static Classification of(int id) {
    for (Classification classification : values()) {
        if (classification.id == id) {
            return classification;
        }
    }
    throw new IllegalArgumentException("Invalid id " + id);
}

A: You can loop through an enumeration's values via the object the someEnum.values() method returns:
for (Classification clz : Classification.values()) doSomethingWith(clz);

found here
I don't know how exactly I can help you, since i don't know what rs.getInt(String) does.
It seems to give back an Integer representing a enum value of Classification, but why?

A: Use variant.setClassification(YourEnumClassHere.values()[classification]). Enum.values() returns an array of all the declared enums in that class.

A: Instead of storing ordinal, you can store the name and use the valueOf method to convert the String back to your Enum type.

A: If you willing and able to store a string representation (this is a good technique) of the ENUM in your database, see Reference from Gareth Davis in comments above.  If you are unwilling and/or unable to store a string representation and must continue with an ordinal representation, I suggest that a Map is called for.  Here is some example code:
public class EnumMap
{
    private enum FistSounds
    {
        Blam, Kapow, Zowie, Biff;

        private static Map<Integer, FistSounds> ordinalMap = new HashMap<Integer, FistSounds>();

        static
        {
            ordinalMap.put(Blam.ordinal(), Blam);
            ordinalMap.put(Kapow.ordinal(), Kapow);
            ordinalMap.put(Zowie.ordinal(), Zowie);
            ordinalMap.put(Biff.ordinal(), Biff);
        }

        public static final FistSounds getByOrdinal(final int enumIndex)
        {
            return ordinalMap.get(enumIndex);
        }
    }

    public static void main(String[] args)
    {
        FistSounds fistSound;

        for (int index = -1; index < 5; ++index)
        {
            fistSound = FistSounds.getByOrdinal(index);

            System.out.print("Ordinal: ");
            System.out.print(index);
            System.out.print(", FistSound: ");
            System.out.println(fistSound);
        }
    }
}

A: I'd recommend using a switch statement, if the logic to execute is different for each case....
do as @Gareth Davis instructs and then just have a switch statement and handle each case as required.

A: Enums are also eligible to be used in switch statements see here


text:
Q: Keras / NN - Handling NaN, missing input These days I'm trying to teach myself machine learning and I'm going though some issues with my dataset.
Some of my rows (I work with csv files that I create with some js script, I feel more confident doing that in js) are empty which is normal as I'm trying to build some guessing model but the issue is that it results in having nan values on my training set.
My NN was not training so I added a piece of code to remove them from my set, but now I have some issues where my model can't work with input from different size.
So my question is: how do I handle missing data? (I basically have 2 rows and can only have the value from 1 and can't merge them as it will not give good results)
I can remove it from my set, which would reduce the accuracy of my model in the end.
PS: if needed I'll post some code when I come back home.

A: You need to have the same input size during training and inference. If you have a few missing values (a few %), you can always choose to replace the missing values by a 0 or by the average of the column. If you have more missing values (more than 50%) you are probably better off ignoring the column completely. Note that this theoretical, the best way to make it work is to try different strategies on your data.


text:
Q: Print shortcode according to site language I'm creating my website with "elementor plugin". So I used to customize the default WordPress search result page since I couldn't access it with elementor.
Anyway, I tried to display my custom elementor footer using a short code:
<?php echo do_shortcode("[INSERT_ELEMENTOR id='319']"); ?>

The code above displays my footer in Arabic version.
<?php echo do_shortcode("[INSERT_ELEMENTOR id='3183"]'); ?>

And this one above is for English version.
How can I switch to any custom footer I want according to site language?

A: That's probably basic PHP. As all that's needed would be some kind of map/array and then switch use the id according to what get_locale() returns.
<?php

// Provide a map if locales and shortcode IDs.
$custom_footer = [
  'ar'    => '319',
  'en_US' => '3181',
  // ... and so on
];

// Get the current language.
$current_language = get_locale();

// Get the right shortcode ID.
$shortcode_id = $custom_footer[$current_language];

?>

<?php echo "Just for debugging, the current language is: " . $current_language; ?>

<?php echo do_shortcode("[INSERT_ELEMENTOR id='" . $shortcode_id . "']"); ?>


text:
Q: Paginating all collections on entity-relationships in JPA I have an entity that looks like the following:
@Entity
@Table(name = "FooTable")
public class FooEntity {
    private Collection<BarEntity> bar;

    @OneToMany(mappedBy = "fooField")
    public Collection<BarEntity> getBars() {
        return bar;
    }

    public void setBars(Collection<BarEntity> barByFooId) {
        this.bar = barByFooId;
    }
}

Basically a one-to-many relationship.
What I want, is that when I have an instance of FooEntity, I want to be able to return the assosciated Collection<BarEntity> in a paginated way using Spring Page.
I've set it up in this way in my repository:
@Override
@Query("select child from FooEntity p inner join p.barField child where p = :parent")
public Page<BarEntity> findBy(FooEntity parent, Pageable pageable)

Which works. For the one relationship.
However! Many of my entity models have a one-to-many relationship to the so-called BarEntity. What I need is a way to tell spring to Always paginate my related entities, because I'd rather not write a specific implementation for each entity that has this type of relation.
Is there any way I can specify this behaviour with minimal code repetition?


text:
Q: Sendfile on Jruby/JRack Tomcat I'm having an interesting issue when deploying an app to Tomcat. I'm
using the Acts_as_flying_saucer gem to convert html to PDF. What the
gem/plugin does is render an html view and then uses a java SAX
processor to render a standard PDF/1.4 compliant file in the server's
TMP directory.
The problem I'm having is when the plugin makes the call to send the
file to the browser. It sends a 0 Byte file. Looking at the Rails log,
it DOES say that it sent /tmp/41c986f5e6249ce24c7698b6494796e0.pdf
Tomcat log shows a 200 status as if it sent the file. But the file in
the /tmp/ directory has info in it and the one sent to the browser is
empty.
The best guess I have is that there is something flaky in the send_file
method.
It works great from webrick. I've deployed a WAR on a few different
Tomcat instances on both Linux and Windows... the logs all seem to show
things working fine.
Let me know if more info is needed or if anyone has any ideas on how I
could track down this problem.
Thanks,
-Jim

A: It appears that Tomcat does not understand 'X-Sendfile' the way other web servers do.
The "fix" is to comment out:
config.action_dispatch.x_sendfile_header = "X-Sendfile"

in your environments/production.rb
Hope this helps others.
-Jim

A: You can also add this middleware to your middleware stack.
https://gist.github.com/958096


text:
Q: How can i make a xml file from a multidimentional array in C#? im making a xml file as a report from the data stored in my multidimentional array, just something like this:
string[,] twoDimentionArray = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };

How can i make a xml file from this array in C#?
Thank you.

A: Use the XmlSerializer Class:

Serializes and deserializes objects into and from XML documents. The
  XmlSerializer enables you to control how objects are encoded into XML.

A: You could also use XDocument if you didn't want to make a class to represent the data in order to use the serialiser (although personally I would recommend you do because any data structure more complicated than the one you have in your sample will rapidly become a maintenance problem!)
Note this code is deliberately "long-hand" for clarity, you can probably do it in a single nested statement.
string[,] twoDimentionArray = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };
var doc = new XDocument();
var Couples = new XElement("Couples");
doc.Add(Couples);
for(int x=0;x<2;x++)
{
    var couple= new XElement("Couple");
    couple.Add(new XElement("Person1",twoDimentionArray[x,0]));
    couple.Add(new XElement("Person2",twoDimentionArray[x,1]));
    Couples.Add(couple);
}
Console.WriteLine(doc.ToString());

will produce
<Couples>
  <Couple>
    <Person1>Mike</Person1>
    <Person2>Amy</Person2>
  </Couple>
  <Couple>
    <Person1>Mary</Person1>
    <Person2>Albert</Person2>
  </Couple>
</Couples>


text:
Q: Aggregate avro object using KSQL via GroupBy operation and UDAF function I am trying to implement KSQL application where I want to group by all records and collect create the list and publish into output topic.
Example
KSQL
KSQL query for creating USER stream, user struct and then user aggregated view.
CREATE STREAM USER (
    ID VARCHAR KEY,
    NAME VARCHAR,
    EMAIL VARCHAR
) WITH (
    KAFKA_TOPIC = 'USER',
    VALUE_FORMAT = 'AVRO',
    KEY_FORMAT = 'KAFKA',
    PARTITIONS = 6
);

CREATE STREAM USER_STRUCT AS
  SELECT A.ID, STRUCT (NAME:= A.NAME, EMAIL:=A.EMAIL)  as USER_STRUCT
  FROM USER A EMIT CHANGES;

 CREATE TABLE USER_AGGREGATED_BY_EMAIL
  WITH (KAFKA_TOPIC = 'USER_AGGREGATED_BY_EMAIL',VALUE_FORMAT='AVRO')
  AS SELECT A.USER_STRUCT->EMAIL, USER_AGGREGATOR(A.USER_STRUCT) AS USERS from USER_STRUCT A group by A.USER_STRUCT->EMAIL
  EMIT CHANGES;

 CREATE TABLE USER_AGGREGATED_BY_EMAIL
  WITH (KAFKA_TOPIC = 'USER_AGGREGATED_BY_EMAIL',VALUE_FORMAT='AVRO')
  AS SELECT A.USER_STRUCT->EMAIL, UDAF(A.USER_STRUCT) AS USERS from USER A group by
  A.USER_STRUCT->EMAIL
  EMIT CHANGES;

CUSTOM UDAF FUNCTION
@UdafDescription(name = "user_aggregator", description = "Aggregate user")
public class UserAggregatorFunction {

    public static final String USERS = "USERS";
    public static final String EMAIL = "EMAIL";

    public static final Schema PARAM_SCHEMA = SchemaBuilder.struct().optional()
            .field("NAME", Schema.OPTIONAL_STRING_SCHEMA)
            .field("EMAIL", Schema.OPTIONAL_STRING_SCHEMA).build();

    public static final String PARAM_SCHEMA_DESCRIPTOR = "STRUCT<NAME STRING, EMAIL STRING>";

    public static final Schema AGRREGATED_SCHEMA = SchemaBuilder.struct().optional()
            .field(USERS, SchemaBuilder.array(Schema.OPTIONAL_STRING_SCHEMA).optional().build())
            .field(EMAIL, Schema.OPTIONAL_STRING_SCHEMA).optional().build();

    public static final String AGGREGATE_SCHEMA_DESCRIPTOR = "STRUCT<" +
            "EMAIL STRING," +
            "USERS ARRAY<STRING OPTIONAL>>";

    public static final Schema RETURN_SCHEMA = SchemaBuilder.struct().optional()
            .field(USERS, SchemaBuilder.array(Schema.OPTIONAL_STRING_SCHEMA).optional().build())
            .field(EMAIL, Schema.OPTIONAL_STRING_SCHEMA).optional().build();

    public static final String RETURN_SCHEMA_DESCRIPTOR = "STRUCT<" +
            "EMAIL STRING," +
            "USERS ARRAY<STRING>>";

    @UdafFactory(description = "Aggregate use on basis of email id",
            paramSchema = PARAM_SCHEMA_DESCRIPTOR,
            aggregateSchema = AGGREGATE_SCHEMA_DESCRIPTOR,
            returnSchema = RETURN_SCHEMA_DESCRIPTOR
    )
    // Can be used with table aggregations
    public static TableUdaf<Struct, Struct, Struct> userAggregator() {

        return new TableUdaf<Struct, Struct, Struct>() {

            @Override
            public Struct initialize() {
                Struct struct = new Struct(AGRREGATED_SCHEMA).put(USERS, new ArrayList<String>()).put(EMAIL, "");
                return struct;
            }

            @Override
            public Struct aggregate(final Struct newValue,
                                    final Struct aggregate) {
                if (newValue == null) {
                    return aggregate;
                }

                String emailId = newValue.getString("EMAIL");
                String name = newValue.getString("NAME");

                aggregate.put(EMAIL, emailId);
                List<String> names = aggregate.getArray(USERS);
                names.add(name);
                aggregate.put(USERS, names);
                return aggregate;
            }

            @Override
            public Struct map(final Struct aggregate) {
                Struct returnValue = new Struct(RETURN_SCHEMA);
                returnValue.put(EMAIL, aggregate.get(EMAIL));
                returnValue.put(USERS, aggregate.getArray(USERS));
                return returnValue;
            }

            @Override
            public Struct merge(final Struct agg1,
                                final Struct agg2) {

                List<String> nameList1 = agg1.getArray(USERS);
                List<String> nameList2 = agg2.getArray(USERS);

                List<String> aggreatedNames = new ArrayList<>();
                aggreatedNames.addAll(nameList1);
                aggreatedNames.addAll(nameList2);

                String email = agg1.getString(EMAIL);
                Struct struct = new Struct(RETURN_SCHEMA);

                struct.put(USERS, aggreatedNames);
                struct.put(EMAIL, email);
                return struct;
            }

            @Override
            public Struct undo(final Struct valueToUndo,
                               final Struct aggregate) {

                List<String> names = aggregate.getArray(USERS);
                String name = valueToUndo.getString("NAME");
                names.remove(name);
                return aggregate;
            }
        };
    }
}

How to create KSQL stream application which aggregate Avro record like struct, Avro object etc?


text:
Q: Submit more than one value to database I have an add to cart button in the homepage. After collecting their product to their cart, the user will submit (process) the list of the product in the form. Since there would be more than one product that they will submit, the form is going to be added automatically (I do this with foreach function).
        foreach ($_SESSION["products"] as $cart_itm) {
                    echo '<input name="product_name">'.$cart_itm["product_name"].'/>';
                    echo '<input name="product_price">'.$cart_itm["prduct_price"].'/>';
    }

My stack now is to think how to submit this multiple value in the form in one submit button. So what I want to achieve is like this:
INSERT INTO  `product` (  `productname` ,  `price` ,  `image`)
VALUES ('Product 1',  '$10',  'product-1.jpg'),
       ('Product 2',  '$20',  'product-2.jpg'),
       ('Product 3',  '$30',  'product-3.jpg');

Since I don't know how much the product they are going to submit which it also mean how many values that is needed to the sql, my question now is how to automatically add value based on the number of the input that is needed.
I hope anyone understand what I am going to achieve here.

[UPDATE QUESTION 1]
I have tried it like this as how Arif_suhail_123 suggested:
<?php
$mysql_hostname = "myhost.com";
$mysql_user = "myname";
$mysql_password = "mypassword";
$mysql_database = "database-one";

$connection=mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Can't connect to mysql");
mysql_select_db($mysql_database, $connection) or die("Can't Select Database");

for($i=0; $i<count($_POST['product_name']);$i++)
    {
        $product_name=$_POST['product_name'][$i];
        $product_price=$_POST['product_price'][$i];

        //Run your query here.

        $mysql_query="INSERT INTO  `member_cart` (  `product_cart_name` ,  `product_cart_price`)
                  VALUES ('$product_name',  '$product_price')";

        $result=  mysql_query($connection, $mysql_query)
                  or die(mysql_error($connection));//here $connection is your
       //database connection

    }
 ?>

My form:
    if(isset($_SESSION["products"])) {
    $total = 0;
    echo '
';
    echo '<form action="cart-post-config.php" method="POST">>';
    foreach ($_SESSION["products"] as $cart_itm) {
                    echo '
';
                    echo '	';
                    echo '<input type="text" name="product_name[]"value='.$cart_itm["name"].'/>	';
                    echo '<input type="text" name="product_price[]"value='.$cart_itm["price"].'/>	';
                    echo 'View Save Delete	';
                    echo '
';
    }
    echo '<input type="submit" name="submit" />';
    echo '</form>';//close the form
}
else {
    echo 'Your Cart is empty'; }

[UPDATE QUESTION 2]
I have tried it like this as how Umair suggested:
<?php
$mysql_hostname = "....";
$mysql_user = ".....";
$mysql_password = ".....";
$mysql_database = ".......";

$connection=mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Can't connect to mysql");
mysql_select_db($mysql_database, $connection) or die("Can't Select Database");

$query =  "INSERT INTO  `member_cart` (  `product_cart_name` ,  `product_cart_price`) VALUES";

$values = array();
$total_products=0;
foreach ($_SESSION["products"] as $cart_itm) {
        $values[] = "('{$cart_itm['product_name']}',  '{$cart_itm['product_price']}')";
        $total_products++;
    }

print "Total products are ".$total_products;
//final query
$query = implode(",",$values);

?>

But it always prints that Total products are 0 even though I have fetch some products in the all related inputs.
Please Help

A: You can achieve this by declaring static variable to count the items whenever any one add item to cart and decrease it when they remove the item from cart.
Then you can use this variable to find the number of items in cart and can run loop accordingly.
I hope, it helps.

A: As I can see a SESSION containing the Cart products. You can try something simlar to this.
$query =  "INSERT INTO  `product` (  `productname` ,  `price` ,  `image`) VALUES";

$values = array();
$total_products=0;
foreach ($_SESSION["products"] as $cart_itm) {
    $values[] =
               "('{$cart_itm['product_name']}',  '{$cart_itm['product_price']}',
                 '{$cart_itm['product_image']}')";
      $total_products++;
    }
print "Total products are ".$total_products;
//final query
$query .= implode(",",$valuse);

A: I think you are looking for this
Please read the comment in the answer
<?php
echo '<form action="Your_File_name" method="POST">';
foreach ($_SESSION["products"] as $cart_itm) {//store them in array
                    echo '<input type= "text" name="product_name[]" value='.$cart_itm["product_name"].'/>';
                    echo '<input type= "text" name="product_price[]" value='.$cart_itm["prduct_price"].'/>';
    }

    echo '<input type="submit" name="submit" />';
    echo '</form>';//close the form

        //use array filter to remove the empty value
$product_name=array_filter($_POST['product_name']);//remove the empty value
$product_price=array_filter($_POST['product_price']);//remove the empty value

for($i=0; $i<count($product_name);$i++)//run a for loop, on the new array.
    {

        $product=$product_name[$i];
        $price=$product_price[$i];
         $mysql_query="INSERT INTO  `member_cart` (  `product_cart_name` ,  `product_cart_price`)
                  VALUES ('$product',  '$price')"; //use the new variable to run the query

        $result=  mysql_query($connection, $mysql_query)
                  or die(mysql_error($connection));//here $connection is your
       //database connection

    }

A: Make it like this:
$query = "INSERT INTO  `product` (  `productname` ,  `price` ,  `image`) Values";

while(Statement){ //(Or a for statement)
       $query .= "(".$somevar1.",".$somevar2.",".$somevar3."),";
}

$query .= ";";
//execute your query here.

Adjust it to your code, so that it works properly for your code, you have to see what you can use the best, a for or a while loop. That's up to you.


text:
Q: properties of limit inferior Prove the following property:

If $x_n \le y_n$ for every $n\ge n_0$, then
  $$\liminf_{n\to\infty}x_n\le\liminf_{n\to\infty}y_n$$

I'm lost on that. Please, could you give me any help?

A: We have
$$\liminf_n x_n=\lim_{n\to\infty}\Bigl(\inf_{k\ge n}x_k\Bigr)=\lim_{\substack{n\to\infty\\ n\ge n_0}}\Bigl(\inf_{k\ge n}x_k\Bigr)$$
by definition.
Now if $ x_n\ge y_n$ for all $n\ge n_0$, there follows that $\;\displaystyle\inf_{k\ge n}x_k\ge\inf_{k\ge n}y_k$ for all $n\ge n_0$, so that this inequality is preserved when passing to the limit.


text:
Q: Html Can you run css code from javascript? I am making a canvas on my website that you can draw on. To achive this effect I draw a fillRect everytime the mouse moves, at the mouseposition. Everithin works fine but when i try to add a background image, it hides everything. I tried using canvas.drawImage();
Then I found that you can add Background image from CSS, using: background:url(pic1.jpg);
This workes fine, but I dont want to the image to be there from load, but load when the user clickes a button. Anny Idea how to do this? Can I call the CSS from Java like you can from HTML, or is there another way. Thanks for answers

A: You can use JavaScript to programmatically set the CSS that defines the background.
var img = "some_image.png";
element.style.backgroundImage = "url(" + img + ")";

Make sure to change the element with the actual HTML element you want to set the background image on.

A: You can use HTML DOM to do this like the code below
<button type="button"
 onclick="document.getElementById('id').style.backgroundImage = "url('image.png')"">
Click Me!</button>

A: You need something like that:

*

*handling the event (in thi example click)

*Append the new css property to the element target

function appendImg() {
  document.getElementById('result').style.backgroundImage = 'url(http://4.bp.blogspot.com/-Q13U4dlElI8/VSW78iey57I/AAAAAAAAI7k/HO3zYPaRYso/s1600/img_john_lennon2-500.jpg)';
}
#result {
  width: 500px;
  height: 400px;
  background-size: 100% auto;
  background-repeat: no-repeat;
  visibility: visible;
}
<button onclick="appendImg()">Imagine</button>


text:
Q: How to fix a white gap after Bootstrap 4 Cards (CSS3 multi-columns bug)(Chrome IE )? I have very annoying bug on Chrome and IE (On Fire Fox it looks fine). I am not really sure what element or elements are doing this.
About the bug:  If you scroll down, you can see where the Bootstrap cards end a big white gap between them and the footer.

URL where the bug is: I have to remove my URL (Stackoverflow rules...sorry guys)
I have been using Google Chrome Inspect to try to find where the problem is but I did not have luck. That is the reason why I am asking here because I can see where the problem is.
The only clues I have are:
-   The bug is not in any JS file or in any extern css file, I think there is something in my CSS is doing this.
-   It is not the position:relative or the overflow:hidden form the class dtl24, because I have tried to delete them and updated my CSS without them and the bug was still there.
Also, I would like to apologize to you. I have tried to create a snippet with the code but without the images, the bug not appreciable.
Do you know where is the bug and how I could fix it please?
Thanks

A: This is a known issue with CSS3 multi-columns that can cause a gap at the bottom. There are only workarounds for this issue, and depend on the specific layout.
You can try using...
.card-columns .card {
    display: flex;
    page-break-inside: avoid;
    break-inside: avoid;
}

But, you may need to ultimately use a large negative margin at the bottom of the container for Chrome / Webkit browsers:
.card-columns {
   -webkit-margin-after: -300px;
   overflow: hidden;
}

A: It is happening because of this styling.
column-gap: 1.25rem;


text:
Q: YA Urban Fantasy about a teenage male who becomes a wizard, cover may have had a raven, and title was like a Shakespeare saying An average teenage guy is working at some fast food place, somehow gets magic, and ends up in a cage with this werewolf girl and they get intimate. They get out and he eventually becomes pretty powerful I think. It was very modern and witty, though my description may make it seem otherwise. Urban fantasy for sure.

A: Nothing Shakespeare about it, but Hold Me Closer, Necromancer by Lish McBride fits every other point. Teen protagonist, working in fast food, winds up caged with a female werewolf, becomes powerful, snarky. Cover has a raven.

Take Samhain Corvus LaCroix — skateboarder, vegetarian, college dropout. He's also a fry cook at the fast-food restaurant Plumpy's and has no idea he's a necromancer until he plays a game of potato hockey in the parking lot and inadvertently plants a tuber into the tail-light of a stranger's Mercedes-Benz.
Sam isn't happy to be a fry cook. "Working here just proved that the only thing separating me from a monkey was pants," he quips in the book's opening chapter. He's even less happy to be roughed up then kidnapped by the Mercedes owner, who, unknown to him, is the most powerful necromancer in all of Seattle — a necromancer who forces Sam to train with him or be killed.
There's inherent humor in a teen who's leading an ordinary American life, suddenly discovering his world isn't what it seemed. Sam's mom is a witch, it turns out. His deadbeat dad? A necromancer. The girl with whom he finds himself caged? A "friendly but possessive nymphet" who happens to also be a werehound (half werewolf, half dog).
Similar to Rick Riordan's "The Lightning Thief" and "The Red Pyramid," "Hold Me Closer, Necromancer" exploits these comic juxtapositions, having Sam react the way any slacker would when confronted by what he learns: with sarcasm and sass. His interactions with co-workers, friends and enemies are chock full of humorous one-liners that are, more often than not, wittily matched by whomever he's talking to.

It was followed up by a sequel, Necromancing the Stone, where Samhain has to deal with an arranged marriage, dead werewolf royalty, sexy sasquatches, and gladiatorial gnomes.


text:
Q: winforms dynamic combobox default value Okay, so I have a two combo boxes, one filled with modifiers (ctrl, alt, shift, windows key) and the other one with keys (A-Z, F1-F12).
I want to change the default value of those combo boxes to the one saved in the "Properties.Settings.Default.*", only somehow it's not working.
Here is the code that fills the combo boxes:
private void Settings_Load(object sender, EventArgs e)
{
    KeyModifiers[] modifierArray = new KeyModifiers[] { KeyModifiers.Alt, KeyModifiers.Control,
                                                        KeyModifiers.Shift, KeyModifiers.Windows };

    var dataSourceModifiers = new List<KeyModifiers>();

    foreach(KeyModifiers modifier in modifierArray )
    {
        dataSourceModifiers.Add(modifier);
    }

    this.comboboxClickerModifier.DataSource = dataSourceModifiers;

    Keys[] keysArray = new Keys[] { Keys.A, Keys.B, Keys.C, Keys.D, Keys.E, Keys.F, Keys.G, Keys.H, Keys.I, Keys.J, Keys.K,
                                    Keys.L, Keys.M, Keys.N, Keys.O, Keys.P, Keys.Q, Keys.R, Keys.S, Keys.T, Keys.U, Keys.V,
                                    Keys.W, Keys.X, Keys.Y, Keys.Z, Keys.F1, Keys.F2, Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5,
                                    Keys.F6, Keys.F7, Keys.F8, Keys.F9, Keys.F10, Keys.F11, Keys.F12};

    var dataSourceKeys = new List<Keys>();

    foreach (Keys key in keysArray)
    {
        dataSourceKeys.Add(key);
    }

    this.comboboxClickerKey.DataSource = dataSourceKeys;

    // Down here are the ways I tried to set the default value
    comboboxClickerKey.Text = Properties.Settings.Default.Key.ToString();
    comboboxClickerKey.SelectedIndex = comboboxClickerKey.Items.IndexOf(Properties.Settings.Default.Key);
    comboboxClickerKey.SelectedItem = Properties.Settings.Default.Key;
    comboboxClickerModifier.SelectedItem = Properties.Settings.Default.Modifier;
}

At the bottom of the code you can see the ways I've tried to set the default value, but all of them failed to do so.
The Settings:

The window on start up:

A: I would recommend to store in Properties.Settings.Default.IndexModifier and Properties.Settings.Default.IndexKey (type int) just selected indices of corresponding ComboBox controls, like for e.g.:
Properties.Settings.Default.IndexKey=comboboxClickerKey.SelectedIndex;
Properties.Settings.Default.Save();

and respectively, operate with that index value to force back the ComboBox control to display the appropriate item, like:
comboboxClickerKey.SelectedIndex=Properties.Settings.Default.IndexKey
The code will be much cleaner, excluding that numerous type conversions. Also, here is a link to the article describing various ComboBox data binding technique (examples pertinent to ASP.NET could be easily adapted for WinForms app as well): http://www.codeproject.com/Tips/214418/Binding-DropDownList-to-various-data-structures.
Note: regarding your code snippet, the closest to working solution is the line:
comboboxClickerKey.Text = Properties.Settings.Default.Key.ToString();

Next 3 lines do not look right and most likely will cause the exception. It may work if you don't explicitly bind DataTextField and DataValueField; otherwise it may fail.
Hope this may help.


text:
Q: Socket.io connection issue I am using Socket.io for one to one chat. i used it before but never faced this kind of issue. My application getting crash after showing below error.
Error which i am getting
 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String okhttp3.MediaType.toString()' on a null object reference
        at io.socket.engineio.client.transports.PollingXHR$Request.onLoad(PollingXHR.java:271)
        at io.socket.engineio.client.transports.PollingXHR$Request.access$700(PollingXHR.java:148)
        at io.socket.engineio.client.transports.PollingXHR$Request$1.onResponse(PollingXHR.java:232)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:216)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:818)

What i have done till now?
try {
            val user_email = preferenceManager.getLoggedInUserEmail()
            val ioOption = IO.Options()
            ioOption.query = "username=anyemail"
            ioOption.secure =true
            ioOption.reconnection=true

            SocketConstants.socketIOClient = IO.socket(SocketConstants.SOCKET_URL, ioOption)
            SocketConstants.socketIOClient?.on(Socket.EVENT_CONNECT, object : Emitter.Listener {
                override fun call(vararg args: Any) {
                    SocketConstants.isSocketConnecting = false
                    Log.i(TAG, "Socket Connected Outside login check...."+args.size)
                }

            })
   SocketConstants.socketIOClient!!.connect()
        } catch (e: Exception) {
            e.printStackTrace()
        }

I am getting this Log before crash
Socket Connected Outside login check....
Could you please help me?

A: I got solution of my problem.I don't know if this solution will work for other facing same but this worked for me.
What i did is
val ioOption = IO.Options()
            ioOption.query = "username=$user_email"
            ioOption.secure = true
            ioOption.reconnection = true
            ioOption.transports = arrayOf(WebSocket.NAME)

            SocketConstants.socketIOClient = IO.socket(SocketConstants.SOCKET_URL, ioOption)

ioOption.transports = arrayOf(WebSocket.NAME)
This line solved my problem. Just add trasports as "WebSocket".
Hope this will work for other if they face same issue.

A: They release a new version 1.0.1 that fix the error https://github.com/socketio/engine.io-client-java/commit/6f065b7a62603730979d43cec71af0046ca4ab7c (29 days ago). Be careful if you try to use v2.0.0, I have troubles to receive the socket messages so I used 1.0.1


text:
Q: Unmarshalling JSON to certain type (string) always I have some JSON that can have either a number or a string as the first element.  I always want to be able to store this as a string value but instead I get a crash as it is reading it as quite rightly so a number type.
I tried to force the unmarshalling as a string but this was not successful.
string `json:",string"`

I am following this guide which seems to fit my data nicely.
How can I always get this element at [0] to always read and save as a string?
Code & Playground below...
https://play.golang.org/p/KP4_1xPJiZ
package main

import "fmt"
import "log"
import "encoding/json"

const inputWorking = `
["AAAAAA", {"testcode" : "Sss"}, 66666666]
`

const inputBroken = `
[111111, {"testcode" : "Sss"}, 66666666]
`

type RawMessage struct {
    AlwaysString        string `json:",string"`
    ClientData    ClientData
    ReceptionTime int
}

type ClientData struct {
    testcode string
}

func main() {

    var n RawMessage
    if err := json.Unmarshal([]byte(inputWorking), &n); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v\n", n)

    var o RawMessage
    if err := json.Unmarshal([]byte(inputBroken), &o); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v\n", o)
}

func (n *RawMessage) UnmarshalJSON(buf []byte) error {
    tmp := []interface{}{&n.AlwaysString, &n.ClientData, &n.ReceptionTime}
    wantLen := len(tmp)
    if err := json.Unmarshal(buf, &tmp); err != nil {
        return err
    }
    if g, e := len(tmp), wantLen; g != e {
        return fmt.Errorf("wrong number of fields in RawMessage: %d != %d", g, e)
    }
    return nil
}

A: You can create a universal receiver, i.e. of interface type, and then do a type assertion:
package main

import (
    "encoding/json"
    "fmt"
)

type RawMessage struct {
    UnknownType interface{} `json:"unknown_type"`
}

const inputString = `{"unknown_type" : "a"}`

const inputFloat = `{"unknown_type" : 123}` // Note: Unmarshals into a float64 by default!!!

func main() {

    var n RawMessage
    if err := json.Unmarshal([]byte(inputFloat), &n); err != nil {
        println(err.Error())
    }

    switch v := n.UnknownType.(type) {
    case string:
        fmt.Printf("Received a string: %v", v)
    case float64:
        fmt.Printf("Received a number: %v", v)
    default:
        fmt.Printf("Unknown type: %v", v)
    }
}

A: I had the same problem and so far the best I found was to make a type from string with a custom unmarshaller:
package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Stringish exists because api send back integers unquoted even if underlying type is string
type StringIsh string

func (f *StringIsh) UnmarshalJSON(data []byte) error {

    var receiver string
    if len(data) == 0 {
        return nil
    }
    if data[0] != '"' {
        quoted := strconv.Quote(string(data))
        data = []byte(quoted)
    }

    if err := json.Unmarshal(data, &receiver); err != nil {
        return err
    }
    *f = StringIsh(receiver)
    return nil

}

type Test struct {
    Foo StringIsh
}

func main() {
    dest := &Test{}
    _ = json.Unmarshal([]byte(`{"foo": "bar"}`), &dest)
    fmt.Println(dest)

    dest = &Test{}
    _ = json.Unmarshal([]byte(`{"foo": 123}`), &dest)
    fmt.Println(dest)
}

Try it yourself at https://goplay.space/#i0OVs9tnule

A: Try this if it resolve this issue, make a generic interface as user input is not defined
interface{} `json:",string"`

package main
import "fmt"
import "log"
import "encoding/json"

const inputWorking = `
["AAAAAA", {"testcode" : "Sss"}, 66666666]
`

const inputBroken = `
[111111, {"testcode" : "Sss"}, 66666666]
`

type RawMessage struct {
    AlwaysString        interface{} `json:",string"`
    ClientData    ClientData
    ReceptionTime int
}

type ClientData struct {
    testcode string
}

func main() {

    var n RawMessage
    if err := json.Unmarshal([]byte(inputWorking), &n); err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%#v\n", n)

    var o RawMessage
    if err := json.Unmarshal([]byte(inputBroken), &o); err != nil {
        log.Fatal(err)
    }


text:
Q: Python: Check if Program is being closed all.
Is there a way, using Python, to check if the script that is currently running is requested to close? For example, If I press the X-Button (close program button) on the top-right to close it, or end the script in any other way, can the script do some code before it ends? Example:
# script goes here...

if Script_To_Be_Closed: # replace this with an actual line of code.
    do_stuff

A: There are multiple options you may use, like trapping keyboardinterrupts, but the simplest is atexit, which executes a function whenever a scripts is ended (except of a hard process kill indeed).
import atexit

def my_exit_function(some_argument):
    // Your exit code goes here
    print(some_argument)

if __name__ == '__main__':
    atexit.register(my_exit_function, 'some argument', )

    // Your script goes here

A: You can use a shell script to do the job
You can see the script command shown below which calls itself after executing the command to run the python file. once the python file is closed the next line will force the python command to run again. you can also customise the behaviour the way you want.
main.py
#!/bin/bash
python3 ./main.py
source ./infiniteRun.sh

If you need to stop the job just edit the file and remove the last line source ./infiniteRun.sh and save the file.


text:
Q: 'Error: redirect_uri_mismatch' in Googe AdWords integration I am using XAMPP for Linux 5.6.30
I want to integrate 'Google Adwords API' in my project for display campaigns details.
I create new project in developer console with help of this guide
for 'Web client' and define Authorized JavaScript origins:http://localhost AND Authorized redirect URIs:https://localhost/googleads/
Also try Authorized JavaScript origins:http://report.myproject.com AND Authorized redirect URIs:http://report.myproject.com/googleads
I also refer some solutions on StackOverflow which discuss previously but I can't get a solution .
When i run `PHP GetRefreshToken.php' in the terminal, it generates one URL but when i open that URL is displayed error 'Error: redirect_uri_mismatch' with this message 'The redirect URI in the request,xxx.xxx.xxx can only be used by a Client ID for a native application. It is not allowed for the WEB client type.'
I also have developerToken and clientCustomerId of Google Adwords account.
Is am i doing right way or not?
is google adwords integration works in localhost server or i have to put it on my live server?
My project is already on live server i just integrate adwords api in local server

A: You can refer to below documentation.
Using OAuth 2.0 for Web Server Applications
Example for end-to-end OAuth2 using php is Given here.
Create authorization credentials
Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.

*

*Open the Credentials page in the API Console.

*Click Create credentials > OAuth client ID.

*Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses. For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080.

Google recommends that you design your app's auth endpoints so that your application does not expose authorization codes to other resources on the page.


text:
Q: How to attach debugger to a python subproccess? I need to debug a child process spawned by multiprocessing.Process(). The pdb degugger seems to be unaware of forking and unable to attach to already running processes.
Are there any smarter python debuggers which can be attached to a subprocess?

A: Building upon @memplex idea, I had to modify it to get it to work with joblib by setting the sys.stdin in the constructor as well as passing it directly along via joblib.
import os
import pdb
import signal
import sys
import joblib

_original_stdin_fd = None

class ForkablePdb(pdb.Pdb):
    _original_stdin = None
    _original_pid = os.getpid()

    def __init__(self):
        pdb.Pdb.__init__(self)
        if self._original_pid != os.getpid():
            if _original_stdin_fd is None:
                raise Exception("Must set ForkablePdb._original_stdin_fd to stdin fileno")

            self.current_stdin = sys.stdin
            if not self._original_stdin:
                self._original_stdin = os.fdopen(_original_stdin_fd)
            sys.stdin = self._original_stdin

    def _cmdloop(self):
        try:
            self.cmdloop()
        finally:
            sys.stdin = self.current_stdin

def handle_pdb(sig, frame):
    ForkablePdb().set_trace(frame)

def test(i, fileno):
    global _original_stdin_fd
    _original_stdin_fd = fileno
    while True:
        pass

if __name__ == '__main__':
    print "PID: %d" % os.getpid()
    signal.signal(signal.SIGUSR2, handle_pdb)
    ForkablePdb().set_trace()
    fileno = sys.stdin.fileno()
    joblib.Parallel(n_jobs=2)(joblib.delayed(test)(i, fileno) for i in range(10))

A: remote-pdb can be used to debug sub-processes. After installation, put the following lines in the code you need to debug:
import remote_pdb
remote_pdb.set_trace()

remote-pdb will print a port number which will accept a telnet connection for debugging that specific process. There are some caveats around worker launch order, where stdout goes when using various frontends, etc. To ensure a specific port is used (must be free and accessible to the current user), use the following instead:
from remote_pdb import RemotePdb
RemotePdb('127.0.0.1', 4444).set_trace()

remote-pdb may also be launched via the breakpoint() command in Python 3.7.

A: Winpdb is pretty much the definition of a smarter Python debugger. It explicitly supports going down a fork, not sure it works nicely with multiprocessing.Process() but it's worth a try.
For a list of candidates to check for support of your use case, see the list of Python Debuggers in the wiki.

A: This is an elaboration of Romuald's answer which restores the original stdin using its file descriptor. This keeps readline working inside the debugger. Besides, pdb special management of KeyboardInterrupt is disabled, in order it not to interfere with multiprocessing sigint handler.
class ForkablePdb(pdb.Pdb):

    _original_stdin_fd = sys.stdin.fileno()
    _original_stdin = None

    def __init__(self):
        pdb.Pdb.__init__(self, nosigint=True)

    def _cmdloop(self):
        current_stdin = sys.stdin
        try:
            if not self._original_stdin:
                self._original_stdin = os.fdopen(self._original_stdin_fd)
            sys.stdin = self._original_stdin
            self.cmdloop()
        finally:
            sys.stdin = current_stdin

A: I've been searching for a simple to solution for this problem and came up with this:
import sys
import pdb

class ForkedPdb(pdb.Pdb):
    """A Pdb subclass that may be used
    from a forked multiprocessing child

    """
    def interaction(self, *args, **kwargs):
        _stdin = sys.stdin
        try:
            sys.stdin = open('/dev/stdin')
            pdb.Pdb.interaction(self, *args, **kwargs)
        finally:
            sys.stdin = _stdin

Use it the same way you might use the classic Pdb:
ForkedPdb().set_trace()

A: Just use PuDB that gives you an awesome TUI (GUI on terminal) and supports multiprocessing as follow:
from pudb import forked; forked.set_trace()

A: An idea I had was to create "dummy" classes to fake the implementation of the methods you are using from multiprocessing:
from multiprocessing import Pool

class DummyPool():
    @staticmethod
    def apply_async(func, args, kwds):
        return DummyApplyResult(func(*args, **kwds))

    def close(self): pass
    def join(self): pass

class DummyApplyResult():
    def __init__(self, result):
        self.result = result

    def get(self):
        return self.result

def foo(a, b, switch):
    # set trace when DummyPool is used
    # import ipdb; ipdb.set_trace()
    if switch:
        return b - a
    else:
        return a - b

if __name__ == '__main__':
    xml = etree.parse('C:/Users/anmendoza/Downloads/jim - 8.1/running-config.xml')
    pool = DummyPool()  # switch between Pool() and DummyPool() here
    results = []
    results.append(pool.apply_async(foo, args=(1, 100), kwds={'switch': True}))
    pool.close()
    pool.join()
    results[0].get()

A: Here is the version of the ForkedPdb(Romuald's Solution) which will work for Windows and *nix based systems.
import sys
import pdb
import win32console

class MyHandle():
    def __init__(self):
        self.screenBuffer = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

    def readline(self):
        return self.screenBuffer.ReadConsole(1000)

class ForkedPdb(pdb.Pdb):
    def interaction(self, *args, **kwargs):
        _stdin = sys.stdin
        try:
            if sys.platform == "win32":
                sys.stdin = MyHandle()
            else:
                sys.stdin = open('/dev/stdin')
            pdb.Pdb.interaction(self, *args, **kwargs)
        finally:
            sys.stdin = _stdin

A: The problem here is that Python always connects sys.stdin in the child process to os.devnull to avoid contention for the stream. But this means that when the debugger (or a simple input()) tries to connect to stdin to get input from the user, it immediately reaches end-of-file and reports an error.
One solution, at least if you don't expect multiple debuggers to run at the same time, is to reopen stdin in the child process. That can be done by setting sys.stdin to open(0), which always opens the active terminal. This in fact is what the ForkedPdb solution does, but it can be done more simply and in an os-independent manner like this:
import multiprocessing, sys

def main():
    process = multiprocessing.Process(target=worker)
    process.start()
    process.join()

def worker():
    # Python automatically closes sys.stdin for the subprocess, so we reopen
    # stdin. This enables pdb to connect to the terminal and accept commands.
    # See https://stackoverflow.com/a/30149635/3830997.
    sys.stdin = open(0) # or os.fdopen(0)
    print("Hello from the subprocess.")
    breakpoint()  # or import pdb; pdb.set_trace()
    print("Exited from breakpoint in the subprocess.")

if __name__ == '__main__':
    main()

A: If you are on a supported platform, try DTrace. Most of the BSD / Solaris / OS X family support DTrace.
Here is an intro by the author. You can use Dtrace to debug just about anything.
Here is a SO post on learning DTrace.


text:
Q: reference to overloaded methods in scala I was playing around on the simplyscala.com REPL and tried to get references to methods of objects. It is working with Strings but not with Integeres as I expected and I am a little confused, so help would be appreciated.
This...
"abc".+ _
res0: (Any) => java.lang.String =

...works as expected. I would like it better if it would show the function body after the = sign (maybe in a shortened form) but it gives me the method reference instead of calling the (empty) method as I expect.
However this...
42.+ _

error: missing parameter type for expanded function ((x$1) => 42.0.+(x$1))
   42.+ _
        ^

...gives me a strange error. How exactly does _ work here? I also tried it more explicit by using parentheses to create an Integer and not having it interpreted as a floating:
(42).+ _

error: ambiguous reference to overloaded definition,
both method + in class Int of type (x$1: Char)Int
and  method + in class Int of type (x$1: Short)Int
match expected type ?
       (42).+ _
            ^

It gives me another unexpected error though, but I understand that the compiler does not know which of the overloaded methods I want have a reference to.
So my question is: what does the error in my 2. code example tell me? And how do I make the compiler choose one of the methods in my 3. code example?
Thanks!

A: On a quick look it's the same issue, simply resolved differently by the compiler: it doesn't know which overload you're talking about. By the way, in scala 2.11 they both throw the same error, since you can't end a floating point literal with a . anymore)
If you need to pick one, you will have to be explicit:
(42: Int) + (_: Int)

or
val x: Int => Int = 42.+ _

They will both work.


text:
Q: Unbind loops in React My problem is the following. In React App, I have a sequence of nested loops like these:
`
 {Object.entries(data)?.map((log) => {
              const [item1, item2] = log ?? [];
              return (

{item1}

                  {Object.entries(item2)?.map((itemObj) => {
                    const [item2a, item3] = itemObj ?? [];
                    return (

{item2a}

                        {Object.entries(item3)?.map((item3Obj) => {
                          const [item3b, item4] =item3Obj ?? [];
                          return (

{item3b}

                          );
                        })}

                    );
                  })}

              );
            })}

`
Hello everyone!!
I need to create components for each element but I don't know how to do it without breaking the nested loops.


text:
Q: Got error when I try to install my WebService on Windows-XP I try to install my WebService on Windows XP but receive the following error:

The installation of
  C:\MyWS\MyWS_Setup.msi is not
  permitted due to an error in software
  restriction policy processing.
The object cannot be trusted

What might be causing this?

A: *

*Go to Control Panel>Administrative tools>Local Security Policy

*Right-click on "Software Restriction Policies", and click "Create New Policies". That will put a new policy in the right pane.

*Double-click on "Enforcement" in the right pane, and set the following values: "All software files" and "All users except local administrators".

I am pretty sure it will install now (I would try it now, and only do the following, if necessary), however, you may also opt to remove the file type of your program from "Designated File Types", and set "Trusted Publishers" to "Local computer administrators".
This all assumes you are a local administrator on your computer.


text:
Q: Chart binding in wpf i have big problem with binding Stacked Column Series to my chart.
I have public ObservableCollection Series property in my ViewModel and try by many ways but it still not working.
This is code from ViewModel to prepare Series: private void drawChart() { this.Series.Clear();
    var dataValues = new List<List<SimpleDataValue>>();

    int wartoscNiezalezna = 1;

    for (int i = 0; i < 2; i++)
    {
        dataValues.Add(new List<SimpleDataValue>());
    }

    foreach (var item in myCollection)
    {
        var param = someparam;

        dataValues[0].Add(new SimpleDataValue { IndependentValue = "Czujnik " + wartoscNiezalezna, DependentValue = 100 });
        //czerwone
        dataValues[1].Add(new SimpleDataValue { IndependentValue = "" + wartoscNiezalezna, DependentValue = 200 });

        wartoscNiezalezna++;

    }
    var stackedSeries = Activator.CreateInstance(typeof(StackedColumnSeries)) as DefinitionSeries;

    int itemnr=0;
    foreach (var item in dataValues)
    {
        var definicja = new SeriesDefinition();
        if(itemnr==0)
        definicja.Title = "Stan 1";
        else
            definicja.Title = "Stan 2";
        definicja.DependentValuePath = "DependentValue";
        definicja.IndependentValuePath = "IndependentValue";
        definicja.ToolTip = "asdas";
        definicja.ItemsSource = item;
        stackedSeries.SeriesDefinitions.Add(definicja);
        itemnr++;
    }
   Series.Add(stackedSeries);
}

I cant bind it to:
<charting:Chart x:Name="MyChart"  Padding="10,10,10,10">
    <charting:Chart.Series>
        <charting:StackedColumnSeries>
            <charting:SeriesDefinition ItemsSource="{Binding Series}" DependentValuePath="DependentValue" IndependentValuePath="IndependentValue">
            </charting:SeriesDefinition>
        </charting:StackedColumnSeries>
    </charting:Chart.Series>
</charting:Chart>

I was trying with SeriesDefinitions Collection and others. I will be very grateful to some help.

A: I can't find StackedColumnSeries in WPF so I will use Silverlight. As I see you create SeriesDefinition in code, in that case there is no point in binding, here is correct code:
Xaml without chart series:
<charting:Chart x:Name="MyChart" Padding="10,10,10,10" />

Code behind:
public class SimpleDataValue
{
    public string IndependentValue { get; set; }
    public int DependentValue { get; set; }
}

public partial class MainPage : UserControl
{
    private int[] myCollection = new int[10];
    private List<DefinitionSeries> Series = new List<DefinitionSeries>();

    public MainPage()
    {
        InitializeComponent();
        this.drawChart();
        this.Series.ForEach(this.MyChart.Series.Add);
    }

    private void drawChart()
    {
        this.Series.Clear();
        this.Series = new List<DefinitionSeries>();
        var dataValues = new List<List<SimpleDataValue>>();

        int wartoscNiezalezna = 1;

        for (int i = 0; i < 2; i++)
        {
            dataValues.Add(new List<SimpleDataValue>());
        }

        foreach (var item in myCollection)
        {
            dataValues[0].Add(new SimpleDataValue { IndependentValue = "Czujnik " + wartoscNiezalezna, DependentValue = 100 });
            //czerwone
            dataValues[1].Add(new SimpleDataValue { IndependentValue = "" + wartoscNiezalezna, DependentValue = 200 });

            wartoscNiezalezna++;
        }

        var stackedSeries = Activator.CreateInstance(typeof(StackedColumnSeries)) as DefinitionSeries;

        int itemnr = 0;
        foreach (var item in dataValues)
        {
            var definicja = new SeriesDefinition();
            if (itemnr == 0)
                definicja.Title = "Stan 1";
            else
                definicja.Title = "Stan 2";
            definicja.DependentValuePath = "DependentValue";
            definicja.IndependentValuePath = "IndependentValue";
            ToolTipService.SetToolTip(definicja, "asdas");
            definicja.ItemsSource = item;
            stackedSeries.SeriesDefinitions.Add(definicja);
            itemnr++;
        }
        Series.Add(stackedSeries);
    }

}

What about me, I would solve your problem in this way, because ViewModel mustn't contains anything form the View:
Xaml
<charting:Chart x:Name="MyChart"  Padding="10,10,10,10">
    <charting:Chart.Series>
        <charting:StackedColumnSeries>
            <charting:SeriesDefinition Title="Stan 1" ItemsSource="{Binding FirstCollection}" DependentValuePath="DependentValue" IndependentValuePath="IndependentValue" />
            <charting:SeriesDefinition Title="Stan 2" ItemsSource="{Binding SecondCollection}" DependentValuePath="DependentValue" IndependentValuePath="IndependentValue" />
        </charting:StackedColumnSeries>
    </charting:Chart.Series>
</charting:Chart>

Code-behind
public class ChartModel
{
    public List<SimpleDataValue> FirstCollection { get; set; }
    public List<SimpleDataValue> SecondCollection { get; set; }
}

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        this.MyChart.DataContext = new ChartModel
        {
            FirstCollection = Enumerable.Range(1, 10).Select(i => new SimpleDataValue { IndependentValue = "Czujnik " + i, DependentValue = 100 }).ToList(),
            SecondCollection = Enumerable.Range(1, 10).Select(i => new SimpleDataValue { IndependentValue = "" + i, DependentValue = 200 }).ToList()
        };

    }
}


text:
Q: Insert stored procedure is not compiling Visual studio 2005 is still asking me for a create or alter after writing create procedure. What could be wrong?
USE metroengineeringdatabase

GO
CREATE PROCEDURE dbo.InsertRecords (
@assetcodeId nvarchar(20),
@name_of_asset nvarchar(20),
@unit_no nvarchar(20),
@manufacturer nvarchar(20),
@make nvarchar(20),
@model nvarchar(20),
@capacity nchar(10),
@year_of_manufacture datetime,
@serial_no nvarchar(50),
@attach nvarchar(50),
@siteid nvarchar(50),
@location nvarchar(50),
@omid nvarchar(20),
@smid nchar(20),
@periodic_maintenance_required bit
)
AS
     INSERT assetdbase
     (
     assetcodeidtxt
     name_of_assettxt,
     unit_notxt,
     manufacturertxt,
     maketxt,
     modeltxt
     capacitytxt,
     year_of_manufacturetxt,
     attachtxt,
     siteidtxt,
     locationtxt,
     smidtxt,
     periodic_maintenance_requiredtxt
    )
     VALUES(
     @assetcodetxt
     @name_of_asset
     @unit_no
     @manufacturer
     @make
     @model
     @capacity
     @year_of_manufacture
     @attach
     @siteid
     @location
     @smid
     @perodic_maintenance_required

     )
    RETURN
GO

A: You're missing the comma after the first column in the INSERT list.
You're also missing commas between each value in the VALUES list.

A: Just to complete what other people are saying, here is the code, and I've added logic to make the script re-runnable, so you won't get a creation error with the script after you run it the first time.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

USE metroengineeringdatabase
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InsertRecords]') AND type in (N'P', N'PC'))
BEGIN
exec sp_executesql N'CREATE PROCEDURE [dbo].[InsertRecords] AS SELECT ''PROCEDURE Template'''
END
GO

ALTER PROCEDURE dbo.InsertRecords (
@assetcodeId nvarchar(20),
@name_of_asset nvarchar(20),
@unit_no nvarchar(20),
@manufacturer nvarchar(20),
@make nvarchar(20),
@model nvarchar(20),
@capacity nchar(10),
@year_of_manufacture datetime,
@serial_no nvarchar(50),
@attach nvarchar(50),
@siteid nvarchar(50),
@location nvarchar(50),
@omid nvarchar(20),
@smid nchar(20),
@periodic_maintenance_required bit
)
AS

INSERT assetdbase
         (
         assetcodeidtxt,
         name_of_assettxt,
         unit_notxt,
         manufacturertxt,
         maketxt,
         modeltxt
         capacitytxt,
         year_of_manufacturetxt,
         attachtxt,
         siteidtxt,
         locationtxt,
         smidtxt,
         periodic_maintenance_requiredtxt
        )
         VALUES(
         @assetcodetxt,
         @name_of_asset,
         @unit_no,
         @manufacturer,
         @make,
         @model,
         @capacity
         @year_of_manufacture,
         @attach,
         @siteid,
         @location,
         @smid,
         @perodic_maintenance_required
         )


text:
Q: Azure PostgreSql restores I have what seems to me at least an odd behavior when I'm dealing with a restored database from Azure Postgres.  The end result seems to be that both the original and the restored server are linked meaning any change against the restored server is also seen in the in the original server.
Here is the details of what I'm doing.  In the Azure Portal I'm going to my Azure Postgres server and clicking the restore button.  I'm picking a date from a few days ago and typing in a new server name.  After about 10 minutes the restore is completed and I connect Azure data studio to both the original server and the new restored server.  At this point I write the queries against each of these servers and they return the same results.
To be clear I can insert rows into the restored server and the inserted rows are available in the original server.  This is not the behavior that I expected, can somebody explain to me what is going and why this is the case and more importantly I can use this Restore.
What I am trying to do is restore the server, but then I only want to copy the data from 1 or 2 tables from the restored server onto the original server.

A: Paul. The behavior you are experiencing is the result of the restore operation by the PostgreSQL Azure Database service, as detailed here.

There are two types of restore available:

*

*Point-in-time restore is available with either backup redundancy option and creates a new server in the same region as your original server.

*Geo-restore is available only if you configured your server for geo-redundant storage and it allows you to restore your server to a different region.

The restore operation actually creates an entirely new instance of a PostgreSQL instance with your server configuration and a copy of your database at the point-in-time-selected.

A: The situation that you describe can happen if you connect to the restored server using the new hostname but the old username.
For instance, if the original server hostname is my-server and the restored server hostname is my-server-restored, make sure that when connecting to the new server you use new username admin@my-server-restored instead of the old username admin@my-server.


text:
Q: How to open .tar_1 file? I downloaded some firmware packages from Intel.
Two of them installed fine but this one is different and doesn't unpack fully.
It could be the wrong package that I downloaded but I'd like to know for it's own sake why it won't open and what is .tar_1?
(I'm on 16.04 LTS)

A: Try renaming the file extension to .tar (which is a common *nix archive format). You can also identify the format of the file using the console command "file":
file skldmcver126.tar_1

A: Interestingly, using a tar command in the terminal worked just fine.
tar -xvf myfile.tar_1

While using the archive manager produced an error.


text:
Q: External Java Authentication for IBM Cognos 8 Is it possible to right/configure a custom authentication java module, such that the authentication is done by java. If authentication is true then pass only loggedin user id to cognos and do business logic based on this like drop down or data population.
The password will not be accessible to cognos, only the user id.
The userid and password match is done by java application.
I have read this link http://www.ibm.com/developerworks/data/library/cognos/security/cognos8_platform/page517.html But i think cognos need the password also..


text:
Q: How to handle the new ConnectAsync API (C# Neo4jClient) I updated the Neo4JClient to the version 4.x which included refactoring from client.Connect(); to client.ConnectAsync(). The controller which connects to neo4j is getting instantiated when a request to the api is made, so there is not much time between connecting and using the connection. The async connecting so my guess runs me in the problem, that the client is not connected when I'm already making database requests. I tried to fix this with awaiting the ResultsAsync which didn't fix the problem. Currently there is no documentation existing since it's outdated. Here is my Code :
        // The client is getting injected from my server
        public MyService(GraphClient client)
        {
            this.client = client;
            this.client.ConnectAsync();
        }

        public async Task<bool> Login(string username, string password)
        {
            var query = client.Cypher
                .Match("(n)")
                .Where("n.username = '" + username + "' AND n.password = '" + password + "'")
                .Return(n => n.As<User>());

            var queryResult = await query.ResultsAsync;
            return queryResult.ToList().Count == 1;
        }

A: In your constructor, you would do:
var task = this.client.ConnectAsync();
task.Wait();

Or you can do:
this.client.ConnectAsync().Wait();

A couple of things extra, the GraphClient you are injecting should really be an IGraphClient - this will make it easier for you if you decide to change to a Bolt version later on.
The other, more important thing, is that the server injecting it, should have already done the ConnectAsync bit - you only want to call that once, and if it's injected into multiple classes, it'll be called more than once.


text:
Q: Add extra User Information with firebase I have integrated firebase auth with my android app. Lets say a user has a mail abc@abc.com. I want to add some extra information to the user like the name of the user, occupation and address. How can i connect the user auth table with my android app to do that?
Do i need to write any APIs for that?

A: You have to create another database table say "user". On successful signin, signup for first time you have to create a new row in user table.
public static void writeNewUser(DatabaseReference databaseReference, String userId, String name, String email, int accountType) {
    User user = new User(name, email, accountType);

    databaseReference.child("users").child(userId).setValue(user);
}

You may refer https://github.com/firebase/quickstart-android/tree/61f8eb53020e38b1fdc5aaeddac2379b25240f3b/database

A: First, create a users directory in db. Then, using user's unique id you get from authn process, store the user info under users/{userid}.
To achieve this, you need to get into the details of Firebase database. See here: https://firebase.google.com/docs/database/android/save-data

A: You do not need to write any custom code to do this. Firebase already has features you can use.
The first thing you'd need to do is ensure that users have access to only the data they store. To do this, go to Database/Rules and change your rules to this:
{
"rules": {
  "my_app_user": {
    "$uid": {
      ".write": "auth != null && auth.uid == $uid",
      ".read": "auth != null && auth.uid == $uid"
     }
   }
 }
}

Then, to save the new details in a Firebase database, do this:
        MyAppUser user = new MyAppUser();
        user.setAddressTwo("address_two");
        user.setPhoneOne("phone_one");
        ...

        mDatabaseReference.child("my_app_user").child(firebaseUser.getUid()).setValue(user).
                addOnCompleteListener(DetailsCaptureActivity.this,
                                   new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            ...

The name of the child my_app_user must match both in your code and the Firebase rules else it won't persist.
If everything goes as is supposed to, you should see the details in your database:


text:
Q: get request body in auth_request nginx I want to have a request body in auth_request to check something in there, but probably have some issues when i try to pass request body, as a subrequest, it can't get any information about the body of request
The api http://localhost:8091/api/authen/checkLoggedIn works alone very well and don't have any errors about request body, but when i use this api to do auth_request, it gets errors
when i get rid of @Nullable, even pass some infor like
{
"name" : "thisistest",
"gender" : "Male"
}
it can't get request body and throw exceptions
org.apache.catalina.connector.ClientAbortException: java.io.IOException: An existing connection was forcibly closed by the remote host
at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:310) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:273) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at org.apache.catalina.connector.CoyoteOutputStream.flush(CoyoteOutputStream.java:118) ~[tomcat-embed-core-9.0.65.jar:9.0.65]
at java.base/java.io.FilterOutputStream.flush(FilterOutputStream.java:153) ~[na:na]
at com.fasterxml.jackson.core.json.UTF8JsonGenerator.flush(UTF8JsonGenerator.java:1187) ~[jackson-core-2.13.4.jar:2.13.4]
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1009) ~[jackson-databind-2.13.4.jar:2.13.4]
this is my auth_request
    location = /auth {
    internal;
    proxy_method      POST;
    proxy_pass_request_body on;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
    proxy_pass http://localhost:8091/api/authen/checkLoggedIn;

    }

auth_request /auth;

@PostMapping("/checkLoggedIn")
public ResponseEntity checkLoggedIn(@Nullable @RequestBody Object object) {
// do something
return ResponseEntity.status(HttpStatus.OK).body("The request was successfully completed.");
}


text:
Q: Tika zip bomb exception We are using Tika 1.1 to extract content from an XLSM file. We have two instances of our server. On one of the servers the file content is getting extracted properly. But on another server I am getting zip bomb exception for the same file. We are using same tika standalone jar at both instances. But I am not able to identify the issue.
Not sure whether the SAX configuration is creating a problem at runtime (I am not well versed with SAX). How can I debug this issue?

Caused by: org.apache.tika.exception.TikaException: Zip bomb detected!
          at org.apache.tika.sax.SecureContentHandler.throwIfCauseOf(SecureContentHandler.java:192)
          at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:123)
          at org.apache.tika.Tika.parseToString(Tika.java:380)
          at com.ptc.search.solr.contentReader.contentExtraction.TikaExtractor.getContent(TikaExtractor.java:36)
          ... 45 more
  Caused by: org.apache.tika.sax.SecureContentHandler$SecureSAXException: Suspected zip bomb: 878 levels of XML element nesting
          at org.apache.tika.sax.SecureContentHandler.startElement(SecureContentHandler.java:234)
          at org.apache.tika.sax.ContentHandlerDecorator.startElement(ContentHandlerDecorator.java:126)
          at org.apache.tika.sax.ContentHandlerDecorator.startElement(ContentHandlerDecorator.java:126)
          at org.apache.tika.sax.ContentHandlerDecorator.startElement(ContentHandlerDecorator.java:126)
          at org.apache.tika.sax.ContentHandlerDecorator.startElement(ContentHandlerDecorator.java:126)
          at org.apache.tika.sax.SafeContentHandler.startElement(SafeContentHandler.java:264)
          at org.apache.tika.sax.XHTMLContentHandler.startElement(XHTMLContentHandler.java:244)
          at org.apache.tika.sax.XHTMLContentHandler.startElement(XHTMLContentHandler.java:274)
          at org.apache.tika.sax.XHTMLContentHandler.element(XHTMLContentHandler.java:313)
          at org.apache.tika.parser.microsoft.ooxml.XSSFExcelExtractorDecorator.extractHeaderFooter(XSSFExcelExtractorDecorator.java:145)
          at org.apache.tika.parser.microsoft.ooxml.XSSFExcelExtractorDecorator.buildXHTML(XSSFExcelExtractorDecorator.java:129)
          at org.apache.tika.parser.microsoft.ooxml.AbstractOOXMLExtractor.getXHTML(AbstractOOXMLExtractor.java:104)
          at org.apache.tika.parser.microsoft.ooxml.OOXMLExtractorFactory.parse(OOXMLExtractorFactory.java:110)
          at org.apache.tika.parser.microsoft.ooxml.OOXMLParser.parse(OOXMLParser.java:82)
          at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
          at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:242)
          at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:120)
          ... 47 more

A: After debugging the tika code I realized that I had set maxStringLength on WriteOutContentHandler and the code was throwing zip bomb error after the limit is reached. Correct error message might have helped sooner. Anyway, thanks all for the input. We will definitely plan to move to latest release.
Should we create a defect in Jira to throw proper error message?

A: I resolved this problem installing
emerge app-office/unoconv

and executing
$ unoconv -fpdf file.xlsm

It will create a .pdf file in the same directory of the file, then you can send it to Tika.
My server is Gentoo, then adapt to your dist.


text:
Q: Serilog structured data pretty print? Is there a way to make Serilog format structured data into a formatted output?
I've been using structured data structures in Serilog lately and even though there is an advantage of it being compact large data structures (5 properties or more) are hard to read in the console/file without formatting it later.
Hypothetically I'd only enable this on dev.
https://github.com/serilog/serilog/wiki/Structured-Data
From this:
{ "Fruit": ["Apple", "Pear", "Orange"] }

To this:
{
  "Fruit": [
    "Apple",
    "Pear",
    "Orange"
  ]
}

Edit:
Currently I'm using JsonConvert.SerializeObject({...}, Formatting.Indented) but I'd like to move away from this for reasons like proper coloring from the console package, faster serialization, deferred serialization etc.

A: I seem to recall that we had to do a custom formatter at work a few years ago to modify the default json output from serilog. I do not remember the exact problem we had.
You could take a look at, https://github.com/serilog/serilog/wiki/Formatting-Output, if you haven't already
I have started using https://getseq.net/ to look at the structured output during development, I would highly recommend it.


text:
Q: Writing parallel texts using \memorydump I Want to write two parallels texts. I can do it this way :
\begin{document}
  \begin{pairs}
    \begin{Leftside}
     \beginnumbering
     \pstart
      TEXT
     \pend
     \endnumbering
   \end{Leftside}
   \begin{Rightside}
     \beginnumbering
      \pstart
       TRANSLATION
      \pend
      \endnumbering
    \end{Rightside}
  \end{pairs}
\Columns
\end{document}

But it does not work when I write :
\begin{document}

    \begin{pairs}
        \begin{Leftside} \beginnumbering
         \pstart
          TEXT
         \pend
        \end{Leftside}

        \begin{Rightside} \beginnumbering
            \pstart
             TRANSLATION
             \pend
        \end{Rightside}
    \end{pairs}
   \Columns

    \begin{pairs}
        \begin{Leftside} \memorydump
            \pstart
             TEXT
            \pend
          \endnumbering \end{Leftside}
            \begin{Rightside} \memorydump
            \pstart
            \pend
           \endnumbering    \end{Rightside}
          \end{pairs}
          \Columns
\end{document}

I guess the problem must come from \memorydump, but I don't get why.

A: tl;dr
Dump \memorydump (which doesn't interact optimally with reledmac) and use \pausenumbering and \resumenumbering instead (see reledmacmanual §5.2.7 and my answer here).

Your use of \memorydump appears functionally equivalent to the very skimpy example in the "manual" part of the reledpar documentation (§7.2). In fact, the "official" example doesn't compile either. The bad form consists in removing an \endnumbering before closing Leftside which, however, is what the manual shows us to do. It also tells us to place a \memorydump first thing in the next Leftside environment.
What does \memorydump do? According to the "code" part of the documentation (§III, p. 37):

\memorydump is a shorthand for \pausenumbering\resumenumbering. This will clear the memorised stuff for the previous chunks while keeping the numbering going.

Basically, to call \memorydump is to call \endnumbering and \beginnumbering directly after one another. But then, no matter where you place \memorydump, you mess with the very delicate hierarchy and arrangement of environments that is needed to operate reledpar. No matter where you use it, it will break things.
It is hard to tell from the question what you are actually trying to achieve. (Please clarify the question, if you are still interested.)
Assuming your aim is to preserve continuous line numbering across a "break" – meaning that you break down long chunks of texts by ending the `Leftside and pages (etc.) environments and printing the \Pages every once in a while, allowing for more natural page breaks and text distribution – then the solution is the same as detailed in my other answer.
Just before the break, use \pausenumbering instead of \endnumbering and right after, use \resumenumbering instead of \beginnumbering (these are explained in the reledmacmanual §5.2.7).
\documentclass{article}
\usepackage[a6paper]{geometry}   % just for the screenshots
\usepackage{blindtext}
\usepackage[series={A},noend, noeledsec, noledgroup, nopenalties]{reledmac}
\usepackage{reledpar}

\begin{document}

\begin{pages}
\begin{Leftside}
%
\beginnumbering
\pstart
\blindtext
\pend
%
%\endnumbering     % endnumbering --> resets line counting
\pausenumbering    % pausenumbering --> continuous numbering
\end{Leftside}
%
\begin{Rightside}
\beginnumbering
%
\pstart
\blindtext
\blindtext
\pend
%
%\endnumbering     % endnumbering --> resets line counting
\pausenumbering    % pausenumbering --> continuous numbering
\end{Rightside}
\end{pages}
\Pages

\begin{pages}
\begin{Leftside}
%\beginnumbering     % beginnumbering --> restarts line numbering from 1 here
\resumenumbering     % resumenumbering --> continuous numbering
%
\pstart
\blindtext
\pend
%
\endnumbering
\end{Leftside}

\begin{Rightside}
%\beginnumbering     % beginnumbering --> restarts line numbering from 1 here
\resumenumbering     % resumenumbering --> continuous numbering
%
\pstart
\blindtext
\blindtext
\pend
%
\endnumbering
\end{Rightside}
\end{pages}
\Pages

\end{document}


text:
Q: Max depth of tree in a maze Suppose I have a N*N maze, for the worst case(I can use either Breath first search or Depth first search). What is the maximum depth of my search tree?
My understanding is it will be 2*(N-1) in this case.


text:
Q: How to use the object from a Linked List I am using a linked list for an assignment, and I am confused about something. We have to create another class for a phonebook, that takes in the name and number, and then store it in a linkedlist, and I got most of it figured out. Until I started to try and get the person object out of the linked list so I can run the methods I wrote for the my person object, like the getters and setters and such. But when I pull it back out of the linked list, it is just an object and not a person I put in, How do you get the object back out so that I can use it as the object I put in.
Thanks
Ok, sorry about adding it in the comments.
This is the test i have tried so far,
The person class has a print method, but I forgot about assigning the type with the
public static void main(String[] args) {
    LinkedList phonedir = new LinkedList();
    person one = new person("John", "Doe", "1234567890");
    phonedir.add(one);
    Object two = phonedir.get(0);
    two.print();
}

A: You should use LinkedList<person> so that the compiler knows that what you get out is a person.
public static void main(String[] args) {
    LinkedList<person> phonedir = new LinkedList<person>();
    person one = new person("John", "Doe", "1234567890");
    phonedir.add(one);
    person two = phonedir.get(0);
    two.print();
}

Also, it should be Person. Class names in Java should begin with capitals!

A: public class SaveRetrieveObjects {
    List<Item>  objs        = new LinkedList<Item>();
    File        fileName    = new File("objects.sav");

public SaveRetrieveObjects() {
    createItems();
    showItems();
    serializeObjs(objs, fileName);
    objs = deserializeObjs(objs, fileName);
    showItems();
    System.out.println("Vale!");
}

private void createItems() {
    Item oneObject = new Item();
    oneObject.setId("Citric-45");
    oneObject.setDesc("orange");
    oneObject.setCost(12345.67);
    oneObject.setQty(67);
    oneObject.setBool(true);
    oneObject.setColor(Color.orange);
    objs.add(oneObject);

    oneObject = new Item();
    oneObject.setId("Mobil-12");
    oneObject.setDesc("car");
    oneObject.setCost(67890.12);
    oneObject.setQty(2);
    oneObject.setBool(true);
    oneObject.setColor(new Color(1, 2, 3));
    objs.add(oneObject);
}

private void showItems() {
    Item itm;
    for (int j = 0; j < objs.size(); j++) {
        itm = objs.get(j);
        System.out.println("Item " + (j + 1) + " Contents:");
        System.out.print("\t" + itm.getId());
        System.out.print("\t" + itm.getDesc());
        System.out.print("\t" + itm.getCost());
        System.out.print("\t\t" + itm.getQty());
        System.out.println("\t" + itm.isBool());
        System.out.println("\t" + itm.getColor());
    }
     System.out.println("----------------------------------------------------");
}

private void serializeObjs(List<Item> objs, File file) {
    System.out.println("Serialization process started");
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    try {
        fos = new FileOutputStream(file);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(objs);
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            oos.close();
            fos.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    System.out.println("\nSerialization ended successfully");
    System.out.println("Checkout your specified output file");
    System.out.println("-----------------------------------");
}

@SuppressWarnings("unchecked")
private List<Item> deserializeObjs(List<Item> objs, File file) {
    objs.clear();
    System.out.println("Deserialization process started");
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    try {
        fis = new FileInputStream(file);
        ois = new ObjectInputStream(fis);
        objs.addAll((Collection<? extends Item>) ois.readObject());
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            ois.close();
            fis.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    System.out.println("Deserialization process ended");
    return objs;
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new SaveRetrieveObjects();
        }
    });
}
}

class Item implements Serializable {
private static final long   serialVersionUID    = 1L;

private String                      id;
private String                      desc;
private double                      cost;
private int                             qty;
private boolean                     bool;
private Color                           color;

public Item() {
    id = "";
    desc = "";
    cost = 0;
    qty = 0;
    bool = false;
    color = new Color(0, 0, 0);
}

public Item(String id, String desc, double cost, int qty, boolean bool, Color color) {
    this.id = id;
    this.desc = desc;
    this.cost = cost;
    this.qty = qty;
    this.bool = bool;
    this.color = color;
}

public String getId() {
    return id;
}

public void setId(String itemID) {
    this.id = itemID;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public double getCost() {
    return cost;
}

public void setCost(double cost) {
    this.cost = cost;
}

public int getQty() {
    return qty;
}

public void setQty(int quantity) {
    this.qty = quantity;
}

public boolean isBool() {
    return bool;
}

public void setBool(boolean bool) {
    this.bool = bool;
}

public Color getColor() {
    return color;
}

public void setColor(Color color) {
    this.color = color;
}
}

Here is a full example on "How to use Objects from a Linked List".
Use of Objects in a LinkedList or ArrayList:
 Steps:
 * -Create Class Item implements Serializable.
 * -Create the Item Objects.
 * -Add them to an ArrayList or LinkedList. These, ArrayList or LinkedList, do
 not need to be serializable! Only the Item class needs to implement
 serializable.
 * -Using streams write and retrieve the objects to and from file chosen.
 Hope this helps as has done for others. Vale!


text:
Q: Is there a lightweight multipart/form-data parser in C or C++? I'm looking at integrating multipart form-data parsing in a web server module so that I can relieve backend web applications (often written in dynamic languages) from parsing the multipart data themselves. The multipart grammar (RFC 2046) looks non-trivial and if I implement it by hand a lot of things can go wrong. Is there already a good, lightweight multipart/form-data parser written in C or C++? I'm looking for one with no external dependencies other than the C or C++ standard library. I don't need email attachment handling or buffered I/O classes or a portability runtime or whatever, just multipart/form-data parsing.
Things that I've considered:

*

*GMime - depends on glib, so no go.

*libapreq - too large, depends on APR, badly documented, no unit tests.

I've also looked at writing a parser with Ragel, but I can't figure out how to do it because the grammar is not static: the boundary can change arbitrarily.

A: Yes, there one. No secret it is my own. Feel free to use it. The link is: MPFDParser. It has no dependencies at all.

A: I know this question is a couple of years old now, but I needed the same and ended up using this:
https://github.com/iafonov/multipart-parser-c

A: mimetic claims to support it. I think GNU cgicc may also support it.

A: cgicc supports it... But is written quite badly and relays on entry buffer in memory.

A: this may not answer your question directly, but did you consider hiphop for php from facebook?
it converts your php code to c++ then compiles with g++.
might save you time in writing something on your own.