text:
Q: Does pure MongoDB use schemas and models like Mongoose? I'm new on pure MongoDB and I've some questions about pure MongoDB.

1. Does pure MongoDB use schemas and models like Mongoose ODM?
If you have used Mongoose ODM, you know that Mongoose ODM uses schemas and models for defining fields with their properties. Like this;
/* Dependencies */
const mongoose = require('mongoose');

/* Define the user schema */
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  lastname: {
    type: String,
    required: true
  }
});

/* Define the model */
const User = mongoose.model('User', userSchema);

Do we need to define schemas and models with their fields?
2. Does pure MongoDB have any validators?
For example, If we have a field in schema; we can define some properties to fields like;
...
  name: {
    type: String,  // Type built-in validator
    required: true // Required built-in validator
  },
  points: {
    type: Number,  // Type built-in validator
    min: 0,        // Min (minimum) built-in validator
    max: 100       // Max (maximum) built-in validator
  },
  verified: {
    type: Boolean, // Type built-in validator
    validate: {    // Custom schema validator
      validator: function(v) {
        return this.points > 50;
      },
      message: 'You can not register!'
    }
  }
...

Does pure MongoDB support for any validators or we define them while CRUD operations like this;
function createUser(userData, db, callback) {
  if(userData.name && typeof(userData.name) == 'string' && userData.username && typeof(userData.lastname) == 'string') { // Validator for object
    const collection = db.collection('users');
    collection.insertOne({
      name: userData.name,
      lastname: userData.lastname
    }, function(err, result) {
      if(err) callback(err, null);
      console.log('One record writed!');
      callback(null, result);
    });
  } else {
    callback(new Error('You must enter name and lastname to register!', null));
  }
}

All my questions are about these. Thanks...

A:

*

*Does pure MongoDB use schemas and models like Mongoose ODM?

No, the MongoDB server (as at 4.0) does not have a concept of models or data relationships. Data is persisted in Documents which are stored on the server in a binary JSON-like serialization format called BSON.

*Does pure MongoDB have any validators?

The MongoDB server does support per-collection validation rules for inserting & updating documents. In MongoDB 3.6 validation rules are defined using JSON Schema; earlier versions used MongoDB query operators to express validation rules.
Mongoose vs MongoDB schema validation
Typically the goal is to validate data as early as possible in order to provide timely feedback to the end user and avoid unnecessary round trips and processing. For example, validation can happen in the frontend UI, in your application layer, and at the database layer. Frontend UI often has basic validation based on data types and field masks, while custom validation, relationships, and business logic is generally better suited to your application layer. Database validation is a final check to ensure only data fitting an expected (but flexible) schema is persisted.
Using a proposed standard like JSON Schema potentially allows validation rules to be shared by multiple layers of your stack. There are JSON Schema Implementations available for most popular programming languages and browsers. Note: MongoDB's implementation of JSON Schema has an Extension which is the inclusion of a bsonType keyword to allow use of all MongoDB BSON field types.
A current limitation of MongoDB's server-side JSON Schema validation is that it does not provide a detailed report of errors: documents either succeed or fail validation. You may want to watch/upvote SERVER-20547:  Expose the reason an operation fails document validation in the MongoDB Jira issue tracker. Depending on your validation rules and options, failure will either result in an error (the insert/update is rejected) or a warning (the insert/update succeeds but results in a log message). Several of the JSON Schema implementations for application code have more detailed validation reporting suitable for end users.

A: MongoDB supports schema validation.
As per MongoDB official documentation for Schema Vaidation.
MongoDB provides the capability to perform schema validation during updates and insertions.
You can specify the rules when creating a collection or add validation to existing documents as well with validator option.
Example from MongoDB documentation.
db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "gpa", "address.city", "address.street" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            gender: {
               bsonType: "string",
               description: "must be a string and is not required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               exclusiveMaximum: false,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               minimum: 0,
               description: "must be a double and is required"
            },
            "address.city" : {
               bsonType: "string",
               description: "must be a string and is required"
            },
            "address.street" : {
               bsonType: "string",
               description: "must be a string and is required"
            }
         }
      }
   }
})

A:
Does pure MongoDB support for any validators or we define them while
CRUD operations

As per MongoDB blog documentation here Traditionally, MongoDB developers have had to implement their own schema validation routines in their applications, but the arrival of JSON schema standards, the many JSON Schema validators and an excellent .NET validation library by NewtonSoft allowed this to be done in a standard way.
From Version 3.6, MongoDB supports this standard and provides a JSON Schema Validator from within the application that runs like a trigger to check any changes to the data via inserts or alterations.
A 'Validation Schema' had been introduced in 3.2, but 3.6 saw the introduction of the new standard way of doing this. Because it is an industry-standard, you can opt to validate your data from within MongoDB so that you can check data on entry or change, or you can export it as standard JSON, and validate it outside the database. Ideally, with bulk entry of data, you can validate it before import.
MongoDB is a document oriented database. which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.
For example
{
name : "sue",    <-----field:value
age  :  "26", <-----field:value
satatus: "A", <-----field:value
groups: ["news","sports"]  <-----field:value
}

As here The JSON document being validated or described we call the instance, and the document containing the description is called the schema.
The most basic schema is a blank JSON object, which constrains nothing, allows anything, and describes nothing:
{}

You can apply constraints on an instance by adding validation keywords to the schema. For example, the "type" keyword can be used to restrict an instance to an object, array, string, number, boolean, or null:
{ "type": "string" }

What JSON Schema checks for
The JSON Schema firstly determines how the data is stored. It is designed to check a JSON document, not a MongoDB collection, so we need to convert a 'collection' of documents into an array of documents.
However, if you provide a JSON Schema to a mongo collection, then it will work as if it is checking an array of objects, but you can configure the level of validation (validationLevel) and the action taken when an error is found (validationAction).
Out of the box, it will only check individual documents when they are altered or inserted.
The schema can do nothing if you want it to. The first thing it can check is the way that the data is structured within the document.
Normally, data is stored as arrays of objects, though tabular data can be stored as arrays of arrays.
It can then check on whether:

*

*The object has all the required properties

*Additional properties are allowed

*There is at least a minimum number of properties

*It is less than the maximum

You can define the data type of each property and how it should be validated to check for the range of values.
MongoDB schema validation in action
In order to check your validation, you need to take baby steps, and to do debugging in a high-quality JSON Schema Validator such as Newtonsoft's browser-based validator that highlights the broken line and even explains why it failed.

There are plenty of ways that one can validate a property value. One concept that quickly comes up is that of a subschema. This can be as little as a JSON Schema empty object '{}', but is normally a little more picky.


text:
Q: how is the output of the following program is "2"?? Kindly someone tell me how did it come as 2 I have tried to understand it. How does output come as "2"
def add_one(n):
    return n+1

def my_function(n):
    if n<5: return add_one(n)
    else: return add_one(n-5)

my_function(my_function(10))

A: First please use code tags. Second you just have to think.
10 is not smaller than 5 so it will become 6, because you subtract 5 and add 1.
6 is not smaller than 5 so it will become 2, because you subtract 5 and add 1.
You are calling the function twice, therefore the output is two.

A: you are running my_function(my_function(10))
first solve my_function(10),
 my_function(10) will be add_one(5) which is 6
now my_function(6) is evaluated which is add_one(1)
which is 2

A: 2 is the correct output.
The inner my_function(10) argument of the outer my_function() is evaluated first. Since n > 5, add_one(10-5) gives 6.
Then you have my_function(6).
 Still n > 5, add_one(6-5) gives 2.
Remember add_one() function just adds 1 to the n parameter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validation form vb.net Stupid question!
I'm checking if the inputboxes are empty...but after the check, I want to navigate back to my form and give the user a second chance to change their input.
At this moment, the app will show a messagebox if it's empty, but he goes further in my code to the second check...is there a code where I can break the code an go back to the form?
My code:
    If naam = "" Then
        MessageBox.Show("Naam mag niet leeg zijn", "No entry",
        MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If

    prijsstr = TextBox2.Text
    If prijsstr = "" Then
        MsgBox("Prijs mag niet leeg zijn")
    ElseIf IsNumeric(prijsstr) = False Then
        MsgBox("Prijs moet numeriek zijn")
    Else
        prijs = Integer.Parse(prijsstr)
    End If

    If prijs < 0 Then
        MsgBox("Prijs mag niet onder 0 zijn")
    End If

A: Couldn't you just Return?
If naam = "" Then
    MessageBox.Show("Naam mag niet leeg zijn", "No entry",
    MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return
End If

prijsstr = TextBox2.Text
If prijsstr = "" Then
    MsgBox("Prijs mag niet leeg zijn")
    Return
ElseIf IsNumeric(prijsstr) = False Then
    MsgBox("Prijs moet numeriek zijn")
    Return
Else
    prijs = Integer.Parse(prijsstr)
End If

If prijs < 0 Then
    MsgBox("Prijs mag niet onder 0 zijn")
    Return
End If


text:
Q: Database Sync between two Local DBs using MS Sync Framework I am interested in knowing if there is any way to sync two local db database across different computers using Sync Framework? If not then what are alternatives?

A: Sync Framework should be able to sync LocalDb databases across networks. You use the same SqlSyncProvider for it.


text:
Q: Sqlite INSERT unix time Maybe someone can advise, how to correctly add code which returns epoch time. In MySQL I use following string, but this does not work with sqlite
 query = 'INSERT INTO '+ADS1115tableName+('(dateTime, usUnits, `interval`, ads_ch1, ads_ch2, ads_ch3, ads_ch4, pin1, pin2) VALUES(UNIX_TIMESTAMP(),  %i, %i, %.3f, %.3f, %.3f, %.3f, %.1f, %.1f)' %( units, gap, Voltage[0], Voltage[1], Voltage[2], Voltage[3], button1.value, button2.value ))

Where I can place strftime('%s', 'now') in my query?
Many Thanks
Andrej

A: *

*First, I would separate the query template from the code that populates query parameters.

*Then it would be easy to make the template "parametrized" as well and replace: UNIX_TIMESTAMP() with strftime('%s', 'now')
P.S. It's a best practice to use parametrized queries instead of direct interpolation of values such as here


text:
Q: How to form an array of nested arrays in my specific case? I have a specific usecase where I want to combine all objects from an array into one new array. So I have a form in my website where users while booking are adding participants. They can add as many participants as they want. I save them in database as JSON and now I want to form a array of all participants so that I can show them all in the table.
So I first fetch all transactions from a specific listing which I get as an Array of objects and then I loop through them all and only get the transaction.attributes.protectedData.questions which holds the participants of each transaction.
So my transactions object looks like:
[
   {
      "type":"transaction",
      "attributes":{
         "createdAt":"2021-06-24T08:50:26.911Z",
         "protectedData":{
            "questions":[
               [
                  {
                     "question":"name",
                     "answer":"Mario North"
                  },
                  {
                     "question":"email",
                     "answer":"mario@gmail.com"
                  }
               ]
            ],
            "ticketType":{
               "name":"Main entry",
               "quantity":1
            }
         }
      }
   },
   {
      "type":"transaction",
      "attributes":{
         "createdAt":"2021-06-24T08:48:57.646Z",
         "protectedData":{
            "questions":[
               [
                  {
                     "question":"name",
                     "answer":"John Adkins"
                  },
                  {
                     "question":"email",
                     "answer":"john@gmail.com"
                  }
               ],
               [
                  {
                     "question":"name",
                     "answer":"Thomas Smith"
                  },
                  {
                     "question":"email",
                     "answer":"thomas@gmail.com"
                  }
               ]
            ],
            "ticketType":{
               "name":"General entry",
               "quantity":2
            }
         }
      }
   }
]

So I need to loop through each transaction, then loop through questions and each new array in questions array is a new participant. In each participant I need to save the createdAt and ticketType values from transaction property.
So my final array/object needs to look like this:
[
   {
      "createdAt":"2021-06-24T08:50:26.911Z",
      "ticketType":"Main entry",
      "name":"Mario North",
      "email":"mario@gmail.com"
   },
   {
      "createdAt":"2021-06-24T08:48:57.646Z",
      "ticketType":"General entry",
      "name":"John Adkins",
      "email":"john@gmail.com"
   },
   {
      "createdAt":"2021-06-24T08:48:57.646Z",
      "ticketType":"General entry",
      "name":"Thomas Smith",
      "email":"thomas@gmail.com"
   }
]

So I can get the list of participants with createdAt and ticketType added to each of them. But I don't know how can I get my question/answer to appear as my wanted object I posted upper. This is what I have:
export const denormalisedParticipantList = transactions => {
  let participants = [];

  transactions.map(transaction => {
    const createdAt = transaction.attributes.createdAt;
    const questions = transaction.attributes.protectedData?.questions;
    const ticketType = transaction.attributes.protectedData?.ticketType?.name;

    return questions.map(q => {
      // Form new participant object
      const participant = {
        createdAt,
        ticketType,
        ...Object.fromEntries(q.map(({ question, answer }) => [question, answer])),
      };

      // Push new participant
      participants.push(participant);
    });
  });

  return participants;
};

I've been trying to figure it out since last night and I can't make it work. Can anyone please help me figure out how can I make a final array from my transactions object, I would be extremly thankful.

A: Destructuring can be a powerful way of keeping track of what you are accessing in a complex object. Here with flatMap() to return a single flattened array and Object.fromEntries() to map the questions array to individual objects.

const input = [{ "type": "transaction", "attributes": { "createdAt": "2021-06-24T08:50:26.911Z", "protectedData": { "questions": [[{ "question": "name", "answer": "Mario North" }, { "question": "email", "answer": "mario@gmail.com" }]], "ticketType": { "name": "Main entry", "quantity": 1 } } } }, { "type": "transaction", "attributes": { "createdAt": "2021-06-24T08:48:57.646Z", "protectedData": { "questions": [[{ "question": "name", "answer": "John Adkins" }, { "question": "email", "answer": "john@gmail.com" }], [{ "question": "name", "answer": "Thomas Smith" }, { "question": "email", "answer": "thomas@gmail.com" }]], "ticketType": { "name": "General entry", "quantity": 2 } } } }]

const result = input.flatMap((
  {
    attributes: {
      createdAt,
      protectedData: {
        questions,
        ticketType: { name: ticketType } }
    }
  }
) => (
  questions.map(p => ({
    createdAt,
    ticketType,
    ...Object.fromEntries(p.map(({ question, answer }) => [question, answer]))
  }))
));

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: var array = []
data.forEach((element) => {
var object = { created: null,ticketType: null,name: null,email: null }
object.created = element.attributes.createdAt;
object.ticketType = element.attributes.protectedData.ticketType.name;
var tmp_data = element.attributes.protectedData.questions;
tmp_data.forEach((tmp) => {
    tmp.forEach((item) => {
        if(item.question == "name"){
            object.name = item.answer;
        }else{
            object.email = item.answer;
        }
    })
    array.push(object);
})
})

try this :)

A: You can simply use reduce and map.

const data = [{ "type": "transaction", "attributes": { "createdAt": "2021-06-24T08:50:26.911Z", "protectedData": { "questions": [[{ "question": "name", "answer": "Mario North" }, { "question": "email", "answer": "mario@gmail.com" }]], "ticketType": { "name": "Main entry", "quantity": 1 } } } }, { "type": "transaction", "attributes": { "createdAt": "2021-06-24T08:48:57.646Z", "protectedData": { "questions": [[{ "question": "name", "answer": "John Adkins" }, { "question": "email", "answer": "john@gmail.com" }], [{ "question": "name", "answer": "Thomas Smith" }, { "question": "email", "answer": "thomas@gmail.com" },{ "question": "gender", "answer": "male" }]], "ticketType": { "name": "General entry", "quantity": 2 } } } }]

const output = data.reduce(
  (a, b) => [
    ...a,
    ...b.attributes.protectedData.questions.map(e => ({
      createdAt: b.attributes.createdAt,
      ticketType: b.attributes.protectedData.ticketType.name,
      ...e.reduce((acc, cur) => ({ ...acc, [cur.question]: cur.answer }), {}),
    })),
  ],
  []
);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Expand bounding boxes in edges of images to square I have a function designed to expand bounding boxes in images to squares.
def expand_bbox(bbox, img_shape):

    h, w = bbox[2] - bbox[0], bbox[3] - bbox[1]
    if h < w:
        d = w - h
        u = min(bbox[0], d // 2)
        v = d - u
        bbox[0] -= u
        bbox[2] += v
    else:
        d = h - w
        u = min(bbox[1], d // 2)
        v = d - u
        bbox[1] -= u
        bbox[3] += v

    bbox[0] = max(bbox[0], 0)
    bbox[1] = max(bbox[1], 0)
    bbox[2] = min(bbox[2], img_shape[0])
    bbox[3] = min(bbox[3], img_shape[1])
    h, w = bbox[2] - bbox[0], bbox[3] - bbox[1]
    assert h == w
    inc = h // 2
    inc = min(inc, bbox[0])
    inc = min(inc, bbox[1])
    inc = min(inc, img_shape[0] - bbox[2])
    inc = min(inc, img_shape[1] - bbox[3])
    bbox[0] -= inc
    bbox[1] -= inc
    bbox[2] += inc
    bbox[3] += inc
    h, w = bbox[2] - bbox[0], bbox[3] - bbox[1]
    assert h == w
    return bbox

It works fine for cases where the bounding box appears inside the image, but fails to expand boxes in the edges of images (i.e. when the bounding box is [979, 157, 1080, 261] and the image shape is (1080, 1920, 3))
What can I do make sure that the bounding box captures bounding boxes that appear along the edges of the images?

A: I am pretty sure all this code could be prettier, but if you search for a working code, I would go for adding some ifs:
# if increasing the upper edge position would go outside the img_shape, do not increase it, decrease bottom instead.
if bbox[2] + v > img_shape[0]:
    bbox[0] -= u + v
else:
    bbox[0] -= u
    bbox[2] += v

And the same for width.


text:
Q: Is it better to use ResultSet.getString() or ResultSet.getTimestamp() to get a timestamp? In retrieving a timestamp from Postgres or Oracle -- let's call it startDate -- is it better to use the resultSet.getString("startDate") call or resultSet.getTimestamp("startDate")?
Currently I'm using resultSet.getString("startDate") and it works fine, but it occurred to me it might be better practice to use getTimestamp().
Is there an established best practice? Could there be any unexpected consequences from using ResultSet.getString() on a timestamp?

A:
Is it better to use ResultSet.getString() or ResultSet.getTimestamp()
  to get a timestamp?

Neither.
It's better to get a date-time object than a string since this better represents what the thing is and means, and should lend itself better to further operations in the Java program.
At the same time it's far better to use the modern date-time classes from java.time than the old-fashioned Timestamp class. The latter has considerable design problems and has long been considered obsolete.
JDBC drivers are a little different, but see if you can get the correct time as either an Instant, an OffsetDateTime or if all else fails, then a LocalDateTime from your result set. In all cases use the two-argument getObject method. For example:
Instant instant = resultSet.getObject("startDate", Instant.class);

JDBC 4.2 specifies that java.time classes should be supported in this way. I believe all current SQL database engines have JDBC 4.2 compliant drivers out.
Only if you cannot use Java 8 or later, get a Timestamp as in your code. Next use the versions of the java.time classes from ThreeTen-Backport and use the DateTimeUtils class from ThreeTen-Backport for converting your Timestamp, best to en Instant, but if that happens to give you the wrong instant because of time zone trouble, then an LocalDateTime. Example:
Instant instant =
    DateTimeUtils.toInstant(
        resultSet.getTimestamp("startDate")
    )
;

A: I would use resultSet.getTimestamp(). Then your data type is mapped properly from the code to the database. You can convert that result into a String if you wish then. I don't think there is a time cost of calling resultSet.getString(), but generally it's more appropriate to retrieve the correct data type.


text:
Q: C# calling Delphi DLL (that loads additional dlls) FaultExecutionEngineError I have a C# Application (VS 2017 .Net 4.6.1) that passes a string to a Delphi DLL (Delphi 10.2) which processes the inputs and returns outputs.
I am receiving a FaultExecutionEngineError "Common sources of this bug include user marshaling errors for COM-interop or PInvoke".
I have a few questions:
If My Delphi DLL is compiled with IMAGE_FILE_LARGE_ADDRESS_AWARE will my c# App also need to be compiled with editbin /largeaddressaware?
Could my Delphi DLL Loading child DLLs be causing the FaultExecutionEngineError?  In my test I am not actually calling anything in the child DLLs except their initial startup.
Is there a tool to maybe debug these in Delphi?
Delphi:
procedure Go(Inputs : WideString; var Rates : WideString); stdcall;
begin
  Rates := Inputs + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
end;

c#
[DllImport("DelphiDLL.dll",
            CharSet = CharSet.Unicode,
            EntryPoint = "LoadLibraries")]
public static extern void _LoadLiabraries(
    out int res);

[DllImport("DelphiDLL.dll",
            CharSet = CharSet.Unicode,
            EntryPoint = "Go")]
public static extern void _Go(
    [MarshalAs(UnmanagedType.BStr)]
    string Inputs,
    [MarshalAs(UnmanagedType.BStr)]
    out string Outputs);

public static string CallGo(string Inputs) {
    string outputs;
    _Go(Risk, out outputs);
    return outputs;
}

If I run this code:
{
    string inputs = "Test Input";
    int i = 0;
    do {
      string output = CallGo(inputs);
      Console.WriteLine(String.Format("{0} {1} {2}", i, inputs, output)
    } while (i++ < 10000)
}

The I don't get the message but if I run this:
{
    int llres = 0;
    _LoadLibraries(llres);
    string inputs = "Test Input";
    int i = 0;
    do {
      string output = CallGo(inputs);
      Console.WriteLine(String.Format("{0} {1} {2}", i, inputs, output)
    } while (i++ < 10000);
}

I get the error after N tries.  The Number of tries has been consistent between tries.  If I change the code the Number of successful tries has changed.

A: I need to thank David for this.
I went looking into the _LoadLibraries code commenting out sections to see what I could post here.
In doing so I found the problem.  In my actual code _LoadLibraries passes a string (an ini file name) to the Delphi.DLL.  This string was not being passed correctly.  I didn't think to look at _loadLibraries because the error was thrown when calling the CallGo function.
So the answer is check every entry point to your DLL, the marshalling error may be caused by something you called earlier.


text:
Q: auto save excel workbook on every auto update change I have an excel workbook which pulls stock data from from another source (open, close, net position etc.)
The point is, I would like to save a CSV file with every data change, for example, I have entered a position with 100 stocks, the excel has updated the information accordingly and now I would like to save it into a separate excel sheet.
The code below works just fine when I enter the information manually, but when the data is pulled via RTD (auto update the cell) the code doesn't run
Private Sub Worksheet_Change(ByVal Target As Range)

    Application.DisplayAlerts = False

    If Not Intersect(Target, Me.Range("B33:D380")) Is Nothing Then
        ThisWorkbook.SaveCopyAs Filename:="F:\Google Drive\autosave.csv"
    End If
End Sub

A: Worksheet_Change() will not be triggered by a formula, like RTD, updating a cell.
For that you will need to create a Worksheet_Calculate() Sub to listen for the change.
The problem is that this worksheet function doesn't have a Range argument to test which cells are being edited...so for suggestions see this link.


text:
Q: не могу понять как работает команда continue в цикле while python. Заранее благодарю за поддержку добрые и умные люди) не могу понять как воспользоваться continue, что бы пропустить символ  в питоне. Стоит задача разбить строку на две части, да так чтобы вторая часть начиналась с символа 'e', но не включала его
numm = '123e-21'
res=''
res2=''
add = True
for i in numm:
  while add:

    if i!='e':
      res+=i
      break
    else:
      add= False
      break
  while not add:
    res2+=i
    break

print('Мантисса: ', res)
print('порядок этого числа: ', res2)

A: Для выполнения задачи достаточно воспользоваться методом split()
numm = '123e-21'
res, res2 = numm.split('e')
print('Мантисса: ', res)
print('порядок этого числа: ', res2)

По поводу continue в цикле while. Цель continue остановить выполнение текущей итерации в моменте появления continue и перейти к следующей итерации. Ниже решение этой задачи с циклом while и continue. Оно не оптимально. Чисто для учебных целей.
numm = '123e-21'
n = len(numm)
passed_e = False
res = ''
res2 = ''
i = 0
while i < n:
    v = numm[i]
    if v == 'e':
        passed_e = True
        i += 1
        continue
    if passed_e:
        res2 += v
        i += 1
        continue
    i += 1
    res += v
print('Мантисса: ', res)
print('порядок этого числа: ', res2)


text:
Q: Magento 2 PWA : Get the CMS block content I need to get the content of the cms block without rendering. I need some operation with that content(append some text in middle or at the end & replace some text). After I complete my operations, I render it. Is there any way, if so any once can help me?

A: First import and then add identifiers
import CmsBlockGroup from "@magento/venia-ui/lib/components/CmsBlock";
.
.
.
<CmsBlockGroup identifiers={'cms-block-name'}/>

I hope this will help every one.

A: I'm having the same problem, even passing the CMS id it doesn't render the content, it just displays the Pagebuilder html, that default structure of it.
But checking in Apollo, in the request the data comes correctly, it's just not mounted on the front-end.

Graphql request

A: add array []
<CmsBlockGroup identifiers={['cms-block-name']}/>


text:
Q: Linux: how to mark a file descriptor as not inheritable on fork? Is it possible to mark a specific file descriptor as not inheritable, or close it, in the child process when fork() is invoked?

A: No. All file descriptors are inherited in fork. You can set a fd to be closed on exec, however, by using fcntl(fd, F_SETFD, FD_CLOEXEC).

A: No its not possible. By default child processes with inherit file table from parent process.

A: If you really want close-on-fork, something like this could work:
static void fd_to_close;
static void closer()
{
    close(fd_to_close);
}

pthread_atfork(0, 0, closer);

Normally close-on-exec is the desired behavior anyway, though.


text:
Q: Does dynamic binding rules over the exception mechanism in C++? I have a class A that is derived from std::exception and have another class B derived from A. I already overrode the what() function for both classes A and B. I know that if I have catch block like this
catch(A& ob){
  std::cout << ob.what();
}

this will catch objects of type A and of type B which is derived from
A. But for B objects it also calls the what() function that is specific
to A. Why is this happening?

A: The only way this can happen is if B::what() does not override the function in the base class, which will happen if it's signature doesn't match the function in the base class.
Make sure you didn't forget to make it const in B, to match const char* what() const in the base class.


text:
Q: Getting all posts matching custom post type, taxonomy and category I currently have the following set up:

*

*Custom post type called "workshops"

*Within the workshop post type I have a taxonomy called "workshop-status"

*Workshop status subsequently has categories for example "past-event"

I have been using the code below to fetch posts within a particular post type:
<?php $loop = new WP_Query( array( 'post_type' => 'workshops', 'posts_per_page' => -1 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

    content here...

<?php endwhile; wp_reset_query(); ?>

My question is: how can I change this to fetch a post from the past-event category within my custom post type, and custom taxonomy?
My aim is to have multiple page templates and target each category individually.
I have tried changing the arrange to target the category alone, but this did not work. I cannot find an online resource on how to target all aspects.

A: You simply need to add the category attribute like so:
$query = new WP_Query( array( 'category_name' => 'past-event' ) );

So in your example case, this would become:
$loop = new WP_Query( array( 'post_type' => 'workshops', 'posts_per_page' => -1, 'category_name' => 'past-event' ) );

You can do a whole load of stuff as detailed in the code

A: If I understand you correctly, you're looking for something like this:
$args = array(
    'post_type' => 'workshops',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'workshop-status',
            'field' => 'slug',
            'terms' => array( 'past-event'),
            'operator' => 'IN'
        ),
    )

);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) :
    while ( $loop->have_posts() ) : $loop->the_post();

        //do your stuff

    endwhile;
endif;
wp_reset_postdata();


text:
Q: How to print 'x' if the input int is b/w the desired numbers in python? So, I started making a program and now I require it to print anything I like if the number is between 1-100, How to I make the program realize that it needs to print it if the number's between 90 and 100?
#This is a sample code
F2 = int(input())
if F2 == range(90 , 100):
    print("A")
else:
    print("BRUH")

I'm really new to this, I'll be very thankful if someone could help me

A: You're checking if f2 is equal to range(90,100), correct form is if it's IN the range(90,100).
if F2 in range(90,101): #last number is not included in range(101 won't be included)
    print('A')

also, if you try
f2 = range(90,100)
print(f2)

you'll understand what f2 == range(90,100) means.
if you use in, code will check if f2 in [90,91,92...100] , if f2 will be equal any of them, then returns True.

A: Simply do an if else check and if it falls under the range of 90 to 100 then it will print.
#This is a sample code
F2 = int(input())
if F2 >=90 and F2 <=100:
    print("A")
else:
    print("BRUH")

A: Use in operator for membership test. == is comparison operator for equality.
print("A" if (F2 := int(input())) in range(90,101) else "BRUH")


text:
Q: Integration by parts proof $1 = 0$ Let's integrate $\int\frac{f^\prime(x)}{f(x)} dx$ by parts
$$
\\ \mbox{ Let } dv= f^\prime(x)dx,u=\frac{1}{f(x)} \\
\mbox{ Then }v=f(x), du=-\frac{f^\prime(x)}{[f(x)]^2}dx \\
\mbox{ This implies }\int\frac{f^\prime(x)}{f(x)}dx = f(x) \frac{1}{f(x)} - \int -f(x)\frac{f^\prime(x)}{[f(x)]^2}dx \\
\mbox{ after simplifying } \int\frac{f^\prime(x)}{f(x)}dx = 1 + \int \frac{f^\prime(x)}{f(x)}dx \\
\mbox{ subtracting the integral from both sides } \\0 = 1$$
How do we teach integration by parts properly so that this isn't what students think is correct?

A: You are solving for a $\textit{class}$ of functions when you compute an indefinite integral. Meaning when you compute an indefinite integral as follows, where $F'=f$ and $G'=g$
$$f=g\Rightarrow \int f=\int g +c \\\Rightarrow F=G+c$$
The function $F$ is the same as the function $G$ $\textit{up to a constant}$

A: $0=1$ is correct, modulo constants.
The problem here is not integration by parts — the problem is properly doing algebra with things that are only defined up to a (local) constant. "Remember the $+C$" sort of helps with that (although it's not terribly rigorous), but only if they actually remember the $+C$; in this example, the usual cue of computing the antiderivative has been eliminated, making it easy to forget.


text:
Q: Java Smooth 2D Rectangle collision? Hey guys i'm making a maze game and I'm trying to figure out how to make a 2D collision smooth. Currently I have some really bad collision code that I thought up since I haven't done this part yet and it is glitchy and sometimes goes inside the wall then you can't get out.
My code:
    public void checkCollision() {
    Rectangle player_rectangle = new Rectangle(player.getX(),player.getY(),32,32);

    for(Wall wall : walls) {

        Rectangle wall_rectangle = new Rectangle(wall.getX(), wall.getY(), 32,32);

        if(player_rectangle.intersects(wall_rectangle)) {
            if(player.xspeed == 1) {
                player.xspeed = 0;
                player.x -= 1.2;
            } else {

                if(player.xspeed == -1) {
                    player.xspeed = 0;
                    player.x += 1.2;
                }
                else
                    if(player.yspeed == 1) {
                        player.yspeed = 0;
                        player.y -= 1;
                    } else {
                        if(player.yspeed == -1) {
                            player.yspeed = 0;
                            player.y += 1;
                        }
                    }

            }
        }

    }

}

What is a better way to do the collision? here is a picture of the types of maps I will have:

EDIT:
New Collision code:
            if (player_rectangle.intersects(wall_rectangle)) {
            Rectangle intersection = (Rectangle) player_rectangle.createIntersection(wall_rectangle);

            if (player.xspeed > 0) {
                player.x -= intersection.getWidth();
            }

            if (player.yspeed > 0) {
                player.y -= intersection.getHeight();
            }

            if (player.xspeed < 0) {
                player.x += intersection.getWidth();
            }

            if (player.yspeed < 0) {
                player.y += intersection.getHeight();
            }

            Print(Integer.toString(intersection.width) + ", " + Integer.toString(intersection.height));

        }

Movement Code:
    public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_LEFT) {

        xspeed = -1;

    } else {
        if(key == KeyEvent.VK_RIGHT) {

                xspeed = 1;

        } else {
            if(key == KeyEvent.VK_UP) {
                yspeed = -1;
            } else {
                if(key == KeyEvent.VK_DOWN) {
                    yspeed = 1;
                }
            }
        }
    }
}

Thanks for any help you can give me.

A: You can use Rectangle.createIntersection(Rectangle).
If the player moves to a positive direction, just subtract the width and height of the resulting Rectangle from his position, if he moves to a negative, add them.
Don't set the speed to zero, this could cause the player to hang.
EDIT
if (playerRectangle.intersects(wallRectangle) {
    Rectangle intersection = (Rectangle) playerRectangle.createIntersection(wallRectangle);

    if (player.xspeed > 0) {
        player.x -= intersection.getWidth();
    }

    if (player.yspeed > 0) {
        player.y -= intersection.getHeight();
    }

    if (player.xspeed < 0) {
        player.x += intersection.getWidth();
    }

    if (player.yspeed < 0) {
        player.y += intersection.getHeight();
    }
}

EDIT2
As far as I know, keyPressed is only triggered when you press a key, and not when you release it. Try it like this:
private boolean up, down, left, right;

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KEyEvent.VK_UP) {
        up = true;
    }

    ...
}

public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KEyEvent.VK_UP) {
        up = false;
    }

    ...
}

// Call this in the mainthread
public void updateMovement() {
    if (up) {
        player.xspeed = 1;
    }

    ...
}

So in every frame, you update the movement, move the player and then check the collision.


text:
Q: Print echo and return value in bash function I want print echo in function and return value. It's not working:
function fun1() {
    echo "Start function"
    return "2"
}

echo $(( $(fun1) + 3 ))

I can only print echo:
function fun1() {
    echo "Start function"
}

fun1

Or I can only return value:
function fun1() {
    echo "2" # returning value by echo
}

echo $(( $(fun1) + 3 ))

But I can't do both.

A: Well, depending on what you wish, there are several solutions:

*

*Print the message to stderr and the value you wish to take in stdout.
function fun1() {
    # Print the message to stderr.
    echo "Start function" >&2

    # Print the "return value" to stdout.
    echo "2"
}

# fun1 will print the message to stderr but $(fun1) will evaluate to 2.
echo $(( $(fun1) + 3 ))

*Print the message normally to stdout and use the actual return value with $?.
Note that the return value will always be a value from 0-255 (Thanks Gordon Davisson).
function fun1() {
    # Print the message to stdout.
    echo "Start function"

    # Return the value normally.
    return "2"
}

# fun1 will print the message and set the variable ? to 2.
fun1

# Use the return value of the last executed command/function with "$?"
echo $(( $? + 3 ))

*Simply use the global variable.
# Global return value for function fun1.
FUN1_RETURN_VALUE=0

function fun1() {
    # Print the message to stdout.
    echo "Start function"

    # Return the value normally.
    FUN1_RETURN_VALUE=2
}

# fun1 will print the message to stdout and set the value of FUN1RETURN_VALUE to 2.
fun1

# ${FUN1_RETURN_VALUE} will be replaced by 2.
echo $(( ${FUN1_RETURN_VALUE} + 3 ))

A: With additional variable (by "reference"):
function fun1() {
    echo "Start function"
    local return=$1
    eval $return="2"
}

fun1 result
echo $(( result + 3 ))

A: A funny resolution could be tailing the last line of fun1() as a returned value:
function fun1() {
    echo "Start function"
    echo "return:"
    echo "2"
}

# Create a temporary file
output=$(mktemp)
# Run and redirect the output to console and to file simultaneously
fun1 |& tee $output
# Get the last line of the file into returnValue
returnValue=$(tail -1 $output)

echo $(( $returnValue + 3 ))


text:
Q: MySQL select most recent entry for each unique value in another column I have a table with columns document_key (varchar(100)), last_modified (datetime), modified_by (varchar(100)), product_key (char(36)), service_type (char(20)).
How can I extract the most recent entry (last_modified) for each document_key, with a request that is compatible with MySQL 5.6 AND above ?
************************************************************************************************
* id   * document_key     * last_modified          * modified_by  * product_key * service_type *
************************************************************************************************
* 000a * aaa-aaa-aaa-aaa  * 2020-01-23 08:00:00    * Admin        * 123-456     * service      *
************************************************************************************************
* 000b * aaa-aaa-aaa-aaa  * 2020-01-20 23:00:00    * Admin        * 123-456     * service      *
************************************************************************************************
* 000c * bbb-bbb-bbb-bbb  * 2020-01-23 12:00:00    * Admin        * 123-456     * service      *
************************************************************************************************
* 000d * bbb-bbb-bbb-bbb  * 2020-01-18 04:00:00    * Admin        * 123-456     * service      *
************************************************************************************************

I want to get the lines with id = 000a and 000c.
I had this request with MySQL 5.6 and it worked. However MySQL 8 does not return the most recent entry.
SELECT document_key, last_modified, modified_by
FROM (SELECT document_key, last_modified, modified_by FROM document_modification_traces WHERE product_key = '123-456'
    AND service_type = 'service' ORDER BY last_modified DESC) sub_table
GROUP BY document_key;

A: You can use  correlated subquery -
SELECT document_key, last_modified, modified_by
FROM tablename a
where  last_modified = (SELECT max(last_modified) from tablename b where a.document_key=b.document_key) and product_key = '123-456'
    AND service_type = 'service'

A: One canonical way of doing this, which would work on all versions of MySQL, uses a join:
SELECT d1.*
FROM document_modification_traces d1
INNER JOIN
(
    SELECT document_key, MAX(last_modified) AS max_last_modified
    FROM document_modification_traces
    GROUP BY document_key
) d2
    ON d1.document_key = d2.document_key AND
       d1.last_modified = d2.max_last_modified;

To make the above query run even faster, consider adding the following index:
CREATE INDEX idx ON document_modification_traces (document_key, last_modified);

This might dramatically speed up the inner join.


text:
Q: Adding Audio Controls in iOS App using Swift in Xcode I have added background music to my app using the following code:-
Now I am trying to add audio controls to my app using the following methods, but after I click on another view controller and come back to the main view controller the play button is not working. Any help will be highly appreciated Thanks!
var toggleState = 1
var music: AVAudioPlayer!

override func viewDidLoad() {
    super.viewDidLoad()

    playMusic()

}

func playMusic() {
    if let musicURL = Bundle.main.url(forResource: "Adding", withExtension: "mp3") {
        if let audioPlayer = try? AVAudioPlayer(contentsOf: musicURL) {
            music = audioPlayer
            music.numberOfLoops = -1
            music.play()
        }
    }
}
@IBAction func playButtonPressed(_ sender: Any) {

    if (toggleState == 1) {

        music.pause()

        toggleState = 2

    }
    else {

        music.play()

        toggleState = 1

    }

}


text:
Q: Ratio of triangular numbers Which natural numbers can be written as the ratio of two triangular numbers?
That is, which natural numbers can be written as
$$\frac{n(n+1)}{m(m+1)}$$ for natural numbers $m,n$.

A: A small complement to the nice answers so far: there are infinitely many squares that are not the ratio of two triangular numbers.
Indeed, with Gjergji Zaini's notation, let $k=p+1$, where $p\equiv 3\pmod{4}$ is a prime. Then the equation
$$k^2-1=(ky-x)(ky+x)$$
becomes
$$p(p+2)=((p+1)y-x)((p+1)y+x).$$
The first factor on the right is at most $p$, hence if $p$ divides this factor, then the factors on the right are $p$ and $p+2$, so that $y=1$, which corresponds to $n=0$. If $p$ divides the second factor on the right, then the factors on the right are $q$ and $pr$ such that $qr=p+2$. Now
$$q-r\equiv q+pr=2(p+1)y\equiv 0\pmod{p+1},$$
hence $|q-r|\geq p+1$, which forces $q=1$ and $r=p+2$ (since $1\leq q\leq p$). In other words, the factors on the right are $1$ and $p(p+2)$, so that $y=(p+1)/2$. The last expression is even, hence it does not correspond to any $n$.

A: Any non-square $d$ can be written in this way. We need to solve $n(n+1)=dm(m+1)$, and multiplying by 4 and setting $a=2n+1$, $b=2m+1$ we get
$$a^2-db^2=1-d$$
and we need to solve this in odd integers $a$ and $b$ other than $a,b=\pm1$ (which give division by zero when we sub back). But we can do this -- $a=1$ and $b=1$ is one solution, and if we choose a unit $u>1$ in $R=\mathbf{Z}[\sqrt{d}]$ congruent to 1 mod $2R$ (such a thing exists by general theory) then $(1+\sqrt{d})u=a+b\sqrt{d}$ gives a solution congruent to 1 mod $2R$ and hence $a$ and $b$ are odd giving us a solution to the original question.
Here's an example: set $d=97$. Then $u=62809633+6377352\sqrt{97}$ is a unit
congruent to 1 mod 2, and $(1+\sqrt{97})(62809633+6377352\sqrt{97})=681412777+69186985\sqrt{97}$ giving $n=340706388$ and $m=34593492$. This probably isn't the smallest solution but on the other hand it was easy to generate because pari can compute units in real quadratic fields super-quickly.
For $d$ a square it seems a bit more delicate. Say $d=r^2$. If $r=2$ mod 4 then $n=(r^2-4)/4$ and $m=(r-2)/4$ works so this gives a solution for $d=6^2,10^2,14^2\ldots$. But in the remaining cases there might not be a simple criterion -- the question seems to involve (amongst other things) factorizing $r^2-1$ into two factors other than $r+1\times r-1$ but whose sum is $2r$ mod $4r$, and this is perhaps the sort of thing that can be done sometimes but can't be done sometimes. For example $35^2-1=6\times 204$ and (omitting the details, which are not hard) this yields $n=49$ and $m=1$. A computer search for such factors shows that $d^2$ can be written as a ratio of triangular numbers for $d=35,99,195,204,323,483,675,899,980,1155,\ldots$ and the $2$ mod $4$ cases.

A: Kevin already finished the non-square part. Suppose $$\frac{m(m+1)}{n(n+1)}=k^2$$ then denoting $x=2m+1,y=2n+1$, we get the form $$k^2-1=(ky-x)(ky+x).$$
So there is an integer $a$ so that $ky-x=a, ky+x=\frac{k^2-1}{a}$, in particular $$2y=\frac{k^2+a^2-1}{ka}\in \{6,10,14,\dots\}=S$$ because $y$ is odd and $>1$. It is easy to show that this happens if only if $(a,k)$ are consecutive terms in the sequence
$$a_0=1,a_1=2y,a_{n+1}=2ya_n-a_{n-1}.$$ So $k^2$ is the ratio of two triangular numbers iff
$$k\in \bigcup_{m\in S}\{1,m,m^2-1,m^3-2m,\dots\}$$ where $S$ consists of all numbers $2\pmod{4}$ that are greater than $2$.


text:
Q: android.database.sqlite.SQLiteException: table orderTime has no column named product_price I have gone trough all the posts related to this problem on stack overflow but not able to get any solution that worked out. I am using sqlite datebase in android to store data but each time I tried it throws an error that table do not have such column.
// code for database class
public class demo extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "orderTimeManager";

    // Contacts table name
    private static final String TABLE_ORDER = "orderTime";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String PRODUCT_ID = "product_id";
    private static final String PRODUCT_NAME = "product_name";
    private static final String PRODUCT_DETAIL = "product_detail";
    private static final String PRODUCT_TYPE = "product_type";
    private static final String PRODUCT_PRICE = "product_price";

    public demo(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_ORDER_TABLE = "CREATE TABLE " + TABLE_ORDER + "("
                + KEY_ID + " INTEGER PRIMARY KEY,"
                + PRODUCT_NAME + " TEXT," + PRODUCT_DETAIL + " TEXT,"
                + PRODUCT_TYPE + " TEXT,"
                + PRODUCT_PRICE + " TEXT" + ")";
        db.execSQL(CREATE_ORDER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ORDER);

        // Create tables again
        onCreate(db);
    }

    // Adding new order
    public void addOrder(ProductModel object) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        // Contact Name
        values.put(PRODUCT_NAME, object.getProductName()); // Contact Phone Number
        values.put(PRODUCT_DETAIL, object.getProductDetail());
        values.put(PRODUCT_TYPE, object.getProductType());
        values.put(PRODUCT_PRICE, object.getProductType());

        // Inserting Row
        db.insert(TABLE_ORDER, null, values);
        db.close(); // Closing database connection
    }

     // Getting All order

       public List<ProductModel> getAllOrders() {
        List<ProductModel> orderList = new ArrayList<ProductModel>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_ORDER;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ProductModel object = new ProductModel();
                object.setProductId(cursor.getString(0));

                object.setProductName((cursor.getString(1)));
                object.setProductDetail(cursor.getString(2));
                object.setProductType(cursor.getString(3));
                object.setProductPrice(Integer.parseInt(cursor.getString(4)));
                // Adding contact to list
                orderList.add(object);
            } while (cursor.moveToNext());
        }

        // return contact list
        return orderList;
    }

// call database in another class to add data
    JSONObject ob1 = jsonArray.getJSONObject(i);
                    {
                        String productId = ob1.getString("pkproductId");
                        String productName = ob1.getString("name");
                        String productType = ob1.getString("productType");
                        String productPrice = ob1.getString("price");
                        String productDetails = ob1.getString("details");

                        Log.d(TAG, "Inserting");
                        db.addOrder(new ProductModel(productName,productDetails,productType,Integer.parseInt(productPrice)));
 }

  // Product Model

      public ProductModel( String productName, String productDetail, String productType, int productPrice) {
    this.productId = productId;
    this.productName = productName;
    this.productDetail = productDetail;
    this.productPrice = productPrice;
    this.productType = productType;
}

A: try step by step
1) try to change the DATABASE_VERSION = 1; to 2: and then install it again
2) use String productPrice in ProductModel and remove Integer.parseInt( from db.addOrder. because your database having TEXT datatype
3) change this line
values.put(PRODUCT_TYPE, object.getProductType());
values.put(PRODUCT_PRICE, object.getProductPrice());

hope it helps you. if this doesn't help feel free to ask the problem


text:
Q: Node.js hosting providers that dont throw timeout error I uploaded my app to Heroku.
Because it takes a lot of time in one function, the response is not sent for some number of minutes.
Meanwhile, Heroku throws a timeout error (H12 error) after 30 seconds of not sending a response.
I try to solve this problem but it keeps getting increasingly complex, with socket.io and whatnot.
Are there providers that wont throw this error and will let the client wait indefinitely?


text:
Q: Transform an object of objects to an array (special example) I am trying to transform an object of objects into an array of objects.  Basically I want to transform this:
    sales_over_time_week: {
          "1": {
            "orders": 96,
            "total": 270240
          },
          "2": {
            "orders": 31,
            "total": 74121
          }
        }

into this:
[
    {name: 1, orders:96, total:270240},
    {name:2, orders:31, total: 74121}
]

To just transform it normally I would do this
     var myData = Object.keys(items).map(key => {
        return items[key];
      });

and it would give me
[
    {1: {orders: 31, total: 74121}},
    {2: {orders: 52, total: 180284}}
]

but my example is a bit special

A: You can use Object.entries with .map()

let data = {
      "1": {
        "orders": 96,
        "total": 270240
      },
      "2": {
        "orders": 31,
        "total": 74121
      }
    };

 let result = Object.entries(data).map(([key, value]) => ({name: key, ...value}));
 console.log(result);

A: Try
Object.keys(data).map(k=> ({name:+k, ...data[k]}));

data = {
      "1": {
        "orders": 96,
        "total": 270240
      },
      "2": {
        "orders": 31,
        "total": 74121
      }
    }

let r = Object.keys(data).map(k=> ({name:+k, ...data[k]}));

console.log(r);


text:
Q: Can we calculate Spring bean initialization time I would like to develop a spring AOP feature where we can put a point cut/within during the spring bean initialization so as to calculate some statistics as required for business.
I would like to know if its possible using spring AOP module?

A: You can measure initialization time using this component:
@Component
public class MyBeanPostProcessor implements BeanPostProcessor, Ordered {

    private Map<String, Long> start;

    private Map<String, Long> end;

    public MyBeanPostProcessor() {
        start = new HashMap<>();
        end = new HashMap<>();
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        start.put(beanName, System.currentTimeMillis());
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        end.put(beanName, System.currentTimeMillis());
        return bean;
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }

    //this method returns initialization time of the bean.
    public long initializationTime(String beanName) {
       return end.get(beanName) - start.get(beanName);
    }
}

But this time doesn't include time of running constructor.
But you can chronicle a moment after reading bean definition before all bean constructors are run. Use BeanFactoryPostProccessor for it:
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private long launchTime;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        launchTime = System.currentTimeMillis();
    }

    public long getLaunchTime() {
        return launchTime;
    }
}

The lauchTime is a moment when the spring just finished reading the configuration (for example, xml file) and ready to create beans.
So, the full initialization time can be calculated use this two components like: max(end) - launchTime. (The difference between the time last bean was initialized and bean configuration was read)


text:
Q: Alter Column Size in Large SQL Server database causes issues I have a table with more than 600 million records and a NVARCHAR(MAX) column.
I need to change the column size to fixed size but I usually have two options with this large DB:

*

*Change it using the designer in SSMS and this takes a very long time and perhaps never finishes

*Change it using Alter Column, but then the database doesn't work after that, perhaps because we have several indexes

My questions would be: what are possible solutions to achieve the desired results without errors?
Note: I use SQL Server on Azure and this database is in production
Thank you
Clarification: I actually have all the current data within the range of the new length that I want to put

A: Never did this on Azure, but did it with hundred million rows on SQL Server.
I'll add a new column of the desired size allowing null values of course and creating the desired index(es).
After that, I'll update in chunks this new column trimming / converting old column values to new one. After all, remove indexes on the old column and removing it.

A:
Change it using the designer in SSMS and this takes a very long time
  and perhaps never finishes

What SSMS will do behind the scenes is

*

*create a new table with the new data type for your column

*copy all the data from original table to newe table

*rename new table with the old name

*drop old table

*recreate all the indexes on new table

Of course it will take time to copy all of your "more than 600 million records".
Besides, the whole table will locked for the duration of data loading with (holdlock, tablockx)

Change it using Alter Column, but then the database doesn't work after
  that, perhaps because we have several indexes

That is not true.
If there is any index involved, and it can be only indexes that have that field ad included column beacuse of its datatype nvarchar(max), server will give you an error and will do nothing until you drop that index. And in case there is no index affected it just cannot "doesn't work after that, perhaps because we have several indexes".
Please think one more time what you want to achieve changing the type of that column. If you think you'll gain some space doing so it's wrong.
After passing from nvarchar(max) to nchar(max) (from variable length type to fixed length type) your data will occupy more space than now because you are going to store fixed number of bytes even if the column has null or 1-2-3 characters.
And if you just want to change max to smth else, for example 8000, you gain nothing because this is not the real data size but only the maximum size the data can have. And if your strings size is small enough, your nvarchar(max) is already stored as in-row data, not as LOB data as it was with ntext


text:
Q: Is there a graph-drawing tool that will allow me to constrain x, and automatically lay out y? I am looking for a tool similar to graphviz that can render graphs, but that will allow me to constrain just the x coordinate of each node. Then, the tool will automatically choose y coordinates to make the graph look neat.
Basically, I want to make a timeline.
Language / platform / rendering medium are not very important.

A: If you want a neat-looking graph a force-directed algorithm is going to be your best bet. One of the best ones is SFDP (developed by AT&T, included in graphviz) though I can't seem to find pseudocode or an easy implementation. I don't think there are any algorithms this specialized. Thankfully, it's easy to code your own. I'll present some pseudocode mostly lifted form Wikipedia, but with suitably one-dimensional modifications. I'll assume you have n vertices and the vector of x-positions is x, subscripted by x.i.
set all vertex velocities to (0,0)
set all vertex positions to (x.i, random)
while (KE > epsilon)
    KE = 0
    for each vertex v
        force = (0,0)
        for each vertex u != v
            force = force + (0, coulomb(u, v).y)
            if u is incident to v
                force = force + (0, hooke(u, v).y)
        v.velocity = (v.velocity + timestep * force) * damping
        v.position = v.position + timestep * v.velocity
        KE = KE + |v.velocity| ^ 2

here the .y denotes getting the y-component of the force. This ensures that the x-components of the positions of the vertices never change from what you set them to be. The epsilon parameter is to be set by you, and should be something small compared to what you expect  KE (the kinetic energy) to be. Also, |v| denotes the magnitude of the vector v (all computations are of 2-vectors in the above, except the KE). Note I set the mass of all the nodes to be 1, but you can change that if you want.
The Hooke and Coulomb functions calculate the respective forces between nodes; the first is linear in distance between vertices, the second is quadratic, so there is a guaranteed equilibrium. These functions look something like
def hooke(u, v)
    return -k * |u.position - v.position|

def coulomb(u, v)
    return C * |u.position - v.position|

where again most computations are in vector form. C and k have real values but experiment to get the graph you want. This isn't usually necessary because the scaling factors will, in two dimensions, pretty much expand or contract the whole graph, but here the x-distances are set so to get a good-looking graph you will have to change the values a bit.


text:
Q: Not getting dummy json response as Expected but Error As per the following code I must get a dummy json response, but instead it is showing me an error. Why?

<html>
<head></head>
<body>
<script>
var root = 'https://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});
</script>
</body>
</html>

Reference:
https://jsonplaceholder.typicode.com/
Thanks in advance.

A: The error is:

{   "message": "Uncaught ReferenceError: $ is not defined",
  "filename": "https://stacksnippets.net/js",   "lineno": 17,   "colno":
  1 }

So you need to add jquery as script like this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

You can also take a look at jquery page


text:
Q: Angular-UI-Router with Html5Mode refresh page issue I have an app that uses angular-ui-router with html5mode(true). Everything seems to work fine when running and routing to other states.
My default state is app/calendar which is set during module.run()
But when i refresh the page while i'm currently in other routes(lets say app/profile) it takes me back to app/calendar.
Debugging i noticed that the $state.current is always empty after i refresh the page
Object {name: "", url: "^", views: null, abstract: true}

if only the $state.current has value i can just transistion to the current state.
Is there anything that i am missing?
Hopefully someone can help.
My server routing looks like
app.get('/:var(/|app/calendar|app/customers|app/profile|app/settings)?', function(req, res) {
    res.sendFile('/app/main/main.html',{ root: '../Appt/public' });
});

i'm always serving the same file.
and my front-end state configuration
(
    function()
    {
        angular.module('Appt.Main').config(['$stateProvider','$locationProvider',function($stateProvider,$locationProvider)
        {
            $locationProvider.html5Mode(true);

            var calendar = {
                    name: 'calendar',
                    url: 'app/calendar',
                    controller: 'Appt.Main.CalendarController',
                    controllerAs: 'calendar',
                    templateUrl: '/app/main/calendar/calendar.html'
                },
                customers = {
                    name: 'customers',
                    url: 'app/customers',
                    controller : 'Appt.Main.CustomersController',
                    controllerAs : 'customers',
                    templateUrl : '/app/main/customers/customers.html'
                },
                profile = {
                    name: 'profile',
                    url: 'app/profile',
                    controller : 'Appt.Main.ProfileController',
                    controllerAs : 'profile',
                    templateUrl : '/app/main/profile/profile.html'
                },
                settings = {
                    name: 'settings',
                    url: 'app/settings',
                    controller : 'Appt.Main.SettingsController',
                    controllerAs : 'settings',
                    templateUrl : '/app/main/settings/settings.html'
                };

            $stateProvider.state(calendar);
            $stateProvider.state(customers);
            $stateProvider.state(profile);
            $stateProvider.state(settings);

        }]);

    }
)();

My module.run
(
    function()
    {
        'use strict';

        angular.module('Appt.Main',['ngRoute','ui.router','Appt.Directives'])
            .run(['$state','$stateParams', function ($state,$stateParams) {
                console.log('Appt.Main is now running')

                console.log($state.current);
                console.log($stateParams);

                $state.transitionTo('calendar');

            }])
    }
)();

A: I'm not sure if this is going to solve your problem, but I had a very similar problem. First thing I had to do to use html5mode was to use a rewrite property so the app would reload from the index file when i refresh the page, no matter what $state I'm. This is the code I´m using, but it may be different, depending on the serverside you are using.
<IfModule mod_rewrite.c>
    RewriteEngine On
    #RewriteBase /relative/web/path/

    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^(.+) - [PT,L]

    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^(.*) index.html

    RewriteCond %{HTTP:Authorization}  !^$
    RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
</IfModule>

You can read more here, in the docs from ui-router
Also, you'd better set a base or not use a base for your app.
You either insert <base href="/" >inside your head tag (or other base folder, depending on your structure).
Or you can use:
$locationProvider.html5Mode({
    enabled: true,
    requireBase: false
});

So you don't have to use a base.
Also, you don't need a .run to define a default state, ui-router can do it with $urlRouterProvider.when or $urlRouterProvider.otherwise
You can read more in the docs
Since I'm new user to Angular, this is just what i did to solve my problem, which was very similar to yours. Hope it can help you.

A: I had the same issue, and I fixed it by adding this:
app.config(..., $urlMatcherFactoryProvider) {
    $urlMatcherFactoryProvider.strictMode(false);
});

This is because my route was adding a trailing slash / at the end of the paths and $stateProvider was not recognizing the URL, thus taking me back to the home state.


text:
Q: Mutex in Obj-c / Cocoa I'm pretty new to multithreaded programming & cocoa.
I'm going to need a lock to access/modify a NSMutableArray iVar. What's the simpliest way to do it ?
And while I'm here, do you guys have some reading about multithreaded programming with Obj-c/Cocoa ?
Thx.

A: Using the @synchronized block:
@synchronized(MyArray)
{
    // thread safe code
}

This block is not recognized by Xcode at times, but trust me, it works!
For more information, you can read this article.

A: An alternative method is to use GCD and serial queues.
For your NSArray property, write accessors that use a private serial queue. to set, and fetch the values from the backing store. Since serial queues Are FIFO, and will run the blocks sequentially this provides thread safe access to the property.


text:
Q: Never ending query in SQL Server 2012 SQL Server 2012, Amazon RDS
This is my simple query
update [dbo].[DeliveryPlan]
set [Amount] = dp.Amount +
                  case when @useAmountColumn = 1 and dbo.ConvertToInt(bs.Amount) > 0
                         then dbo.ConvertToInt(bs.Amount)
                         else @amount
                  end
from
    BaseSpecification bs
join
    BaseSpecificationStatusType t on (StatusTypeID = t.StatusTypeID)
join
    [DeliveryPlan] dp on (dp.BaseSpecificationID = bs.BaseSpecificationID and dp.ItemID = @itemID)
where
     bs.BaseID = 130 and t.IsActive = 1

It can't be finished. If where condition bs.BaseID=130 (update 7000 rows) change for bs.BaseID=3 (update 1000000 rows) it lasts 13 sec.
Statistics are actual, I think
In performance monitor I see 5% processor usage
When I use sp to watch active connections and for this query
tempdb_allocations is 32, tembdb_current - 32, reads - 32 000 000, cpu - 860 000 (query lasts 20 minutes)
What is the problem?
UPDATE: I added non-clustered index for [DeliveryPlan] - by BaseSpecificationID + ItemID and problem is gone. Unfortunately I see this problem every day with different queries. And problem disappears unpredicatedly.

A: You may suffer from a locking condition for your base tables.
Optimize your query to update dp directly to avoid update all rows of DeliveryPlan
update dp set [Amount] = dp.Amount +
    case
        when @useAmountColumn=1 and dbo.ConvertToInt(bs.Amount)>0 then
            dbo.ConvertToInt(bs.Amount)
        else @amount
    end
from
    BaseSpecification bs
    join BaseSpecificationStatusType t on (bs.StatusTypeID = t.StatusTypeID)
    join [DeliveryPlan] dp on (dp.BaseSpecificationID = bs.BaseSpecificationID)
where
    bs.BaseID = 130
    and t.IsActive = 1
    and dp.ItemID = @itemID

A: This will perform better and in a different way as the join conditions will narrow down the number of rows in the first go itself, rather than waiting for the where clause to execute. The execution plan will be different for both (with where/ without where).
UPDATE dp
  SET Amount = dp.Amount + CASE
                       WHEN @useAmountColumn = 1
                        AND dbo.ConvertToInt( bs.Amount ) > 0 THEN dbo.ConvertToInt( bs.Amount )
                           ELSE @amount
                       END
  FROM BaseSpecification bs
   JOIN BaseSpecificationStatusType t ON
                                        ( bs.StatusTypeID = t.StatusTypeID
                                      AND bs.BaseID = 130
                                      AND t.IsActive = 1
                                        )
   JOIN DeliveryPlan dp ON
                          ( dp.BaseSpecificationID = bs.BaseSpecificationID
                        AND dp.ItemID = @itemID
                          );

A: If the problem mentioned in the update part is that it comes and goes randomly, it sounds like bad parameter sniffing. When the problem happens you could look into plan cache to check if the query plan looks ok and in case it doesn't, what are the values the plan was created with (you can find them in the leftmost object in the plan) and for example use sp_recompile and see what kind of plan you'll get the next time.


text:
Q: Real Analysis: ε-δ definition to prove that f is a continuous function. Let $f:R\backslash \{1 \} \to R$ be defined by $f(x)= \frac{1}{(1-x)}$. Use the $\epsilon$-$\delta$ definition to prove that $f$ is a continuous function.
My attempt is
let $c \in R \backslash \{1\}$. $$|f(x) - f(c)| = \Big|\frac{1}{1-x} - \frac{1}{1-c}\Big| = \Big|\frac{1}{1-x}\Big| \cdot \Big|\frac{1}{1-c}\Big| \cdot |x-c|$$ (this is the part I do not know how to simplify.)
Given $\epsilon > 0$, we choose $\delta =$ something I do not know. Then | something I do not know | $< \delta$ implies that $|f(x) - f(c)|$ something in the middle that I do not know $= \epsilon$.
Could someone please check my direction for the proof? If it is right, could you help me with the parts that I said I do not know?

A: Let $c \neq 1$, and choose $\epsilon>0$.
Choose $\delta = \min(\frac{1}{2}|1-c|, \frac{1}{2}|1-c|^2 \epsilon) $.
Then if $|x-c|< \delta$, we have $|x-1| \ge |1-c|-|x-c| \ge \frac{1}{2} |1-c|$.
We also have $|f(x)-f(c)| = \frac{|x-c|}{|x-1||1-c|} \le \frac{2|x-c|}{|c-1|^2} < \epsilon$.


text:
Q: SQL query in php with input from html dropdown Ok so what I'm trying to do is make a query evaluation tool for a project. I get the user input as a php variable and use it in my query, so it's like the user is submitting the query. I am using mysqli
I'm currently doing this with my my query
$sql = "SELECT * FROM `idk` where  `alias` = '".$s."'";

I get the values from the form below
$s = $_GET['val'];

<select name="selector" id = "selector">
        <option value="">Select a criteria:</option>
        <option value="0">id</option>
        <option value="1">name</option>
        <option value="2">email</option>
        <option value="3">alias</option>
        <option value="4">position</option>

I'm wondering if I can add user input for the where clause condition(=,!=) and get it like i get the value for the column instead of hard coding it.
Keep in mind that this is for a uni project and no one is going to use it or delete my database, but any security suggestions would be appreciated.

A: The shortest possible answer: yes. You can control everything. All you need to achieve this is add another choice element into your form that will let the user control the way values are compared. I'll use a simplified example.
If you have an input for the user's value:
<input type="number" name="age" value="" />

add a choice field before it:
<select name="age_comparison">
    <option value="equal">equal to</option>
    <option value="not_equal">not equal to</option>
    <option value="less_than">less than</option>
    <option value="greater_than">greater than</option>
</select>
<input type="number" name="age" value="" />

Note: the position isn't relevant for handling - at all. I just think it's a better user experience if users read your page just like they would a piece of text in real life. Meaning that when input comes later it will read as "age greater than X", which reads better than "age X, greater than", if you put the input first.
For the same reason (better user experience), I tend to label the options with something that reads more like a human, hence "equal to" instead of just "equal". But I omitted it from the option values since it doesn't add any valuable information to the code ("equal" tells the whole story as a parameter value).

Then, after your form is submitted, you can detect your user's choice and build the query string accordingly:
if (isset($_GET['age'])) {
    $age = $_GET['age'];
}
if (isset($_GET['age_comparison'])) {
    switch ($_GET['age_comparison']) {
        case 'equal':
            $ageComparison = '=';
            break;
        case 'not_equal':
            $ageComparison = '!=';
            break;
        case 'less_than':
            $ageComparison = '<';
            break;
        case 'greater_than':
            $ageComparison = '>';
            break;
    }
}
// if we have all the parameters, we can query the database
if (isset($age) && isset($ageComparison)) {
    // the following line is very unsafe - we'll be on that in a minute
    $queryString = 'SELECT * FROM students WHERE age '.$ageComparison.$age;
    ...

Note: I used $_GET because you used it in your question. If you're going to have multiple parameters in your form, I suggest you rather use the post method and avoid having a whole bunch of parameters added to the url of your page. Your form values will be under the same keys, only in the $_POST variable. Plus, when you use post, it's enough to detect if the name of the submit is set - if it is, the rest of the inputs from the same form is guaranteed to be present as well. With get you have to check every parameter individually.

So there you have it. A query with variable comparison operators.
BUT
We're not done yet. There are some bad practices to shed away and some good practices to pick up on the way.
First and foremost, never build queries by directly inserting parameters:
$sql = "SELECT * FROM `idk` where  `alias` = '".$s."'";

That makes you wide open to SQL injection. You should use prepared statements instead. Prepared statements have built-in protection mechanisms and also take care of all your quoting needs (meaning you don't have to manually put uote marks around parameters that are strings). So you do it like this:
// the question mark means we'll be adding a parameter in that position
$queryString = 'SELECT * FROM students WHERE age '.$ageComparison.' ?';
// here I assume you have mysqli statement ready
// you can see an example about creating one in the link about prepared statements
$statement->prepare($queryString);
$statement->bindParam('i', $age);

You might say "But wait a minute! You just added the comparison operator directly! Isn't that dangerous?" - no, because it didn't come directly from the user. We decided its value in the switch statement, meaning we took user's input (which might be compromised) and turned it into a value that we control. The user can't decide what comes out of the switch statement, we can. Hence, it's safe to directly concatenate it into the query string because we know we've defined some safe values.
Speaking of the switch statement, there's an improvement to be made there, too. What if we add another option in the select, but we forget to add it in the switch statement? Or a malicious user compromises the value of the option being sent? We will end up with an error, since then no cases in the switch will be matched (a case for a value outside of the 4 we put there is not defined) and thus the variable $ageComparison will never be created and we'll never execute the query, because our if condition will fail. So how do we fix it? We add a default case (default executes when none of the cases are matched):
// remainder of statement cut for length
    ...
    case 'greater_than':
        $queryComparison = '>';
        break;
    default:
        throw new Exception('Unsupported value for age comparison: '.$ageComparison);
}

Exceptions halt execution when not handled (the proper term is caught), but I'll leave it to you if you wish to explore that topic on your own (seems a bit much for a beginner, plus there's quite a bit of text here already).


text:
Q: How to get values to dense table with columns of categories using PostgreSQL (crosstab)? I have this toy example which gives me sparse table of values separated in their different categories. I would want to have dense matrix, where all columns are individually ordered.
drop table if exists temp_table;
create temp table temp_table(
    rowid int
    , category text
    , score int
    );
insert into temp_table values (0, 'cat1', 10);
insert into temp_table values (1, 'cat2', 21);
insert into temp_table values (2, 'cat3', 32);
insert into temp_table values (3, 'cat2', 23);
insert into temp_table values (4, 'cat2', 24);
insert into temp_table values (5, 'cat3', 35);
insert into temp_table values (6, 'cat1', 16);
insert into temp_table values (7, 'cat1', 17);
insert into temp_table values (8, 'cat2', 28);
insert into temp_table values (9, 'cat2', 29);

Which gives this temporary table:

rowid
category
score

0
cat1
10

1
cat2
21

2
cat3
32

3
cat2
23

4
cat2
24

5
cat3
35

6
cat1
16

7
cat1
17

8
cat2
28

9
cat2
29

Then ordering score values to different columns based on their category:
select "cat1", "cat2", "cat3"
from crosstab(
    $$ select rowid, category, score from temp_table $$ -- as source_sql
    , $$ select distinct category from temp_table order by category $$ -- as category_sql
 ) as (rowid int, "cat1" int, "cat2" int, "cat3" int)

That outputs:

cat1
cat2
cat3

10

21

32

23

24

35

16

17

28

29

But I would want the result of the query to be dense, like:

cat1
cat2
cat3

10
21
32

16
23
35

17
24

28

29

Maybe PostgreSQL's crosstab is not even right tool to do this, but that comes to my mind first as it produces that sparse table close to the result I would need.

A: This should work for the exact given example data and expected output.
select max(cat1), max(cat2), max(cat3)
from crosstab(
$$ select rank() over(partition by category order by rowid) as ranking,
  rowid,
  category,
  score
from temp_table
order by rowid, category asc$$ -- as source_sql
, $$ select distinct category
from temp_table
order by category $$ -- as category_sql
  ) as (ranking int, rowid int, "cat1" int, "cat2" int, "cat3" int)
group by ranking
order by ranking asc

You can test the solution here - https://dbfiddle.uk/?rdbms=postgres_14&fiddle=f198e40a18a282cc0d65fa6ecdf797cb
Edit:
Improvements made to your query to arrive at the solution:

*

*In the source SQL query, I have ranked the category values based on the rowid order, which helps "determining" the order of the expected values, as per your requirement.

select rank() over(partition by category order by rowid) as ranking, rowid, category, score from temp_table order by rowid, category asc

*In the external query, I am effectively picking the max() values of each category, for each of the rankings as obtained in the source SQL query.

A: with cte as (
  select category, score, row_number() over (
    partition by category order by score
  ) as r
  from temp_table
)
  select
    sum(score) filter (where category = 'cat1') as cat1,
    sum(score) filter (where category = 'cat2') as cat2,
    sum(score) filter (where category = 'cat3') as cat3
  from cte
  group by r
  order by r
;

If the number of columns is known and it is reasonably small, FILTER might be a better option than CROSSTAB, which requires an extension.


text:
Q: How to write file path into json file in java I have a text which contains file path location. When I am trying to write this text path into a other json file using JSON object put method , I am getting \\ while my original text path contains \.
How can I avoid \\?
Please assist me on this.

A: Don't remove the slashes, because that's how the JSON standard is defined for when you show the entire object as a string. If you extract the string from the JSONObject then the slashes are removed.
Edit: to find out the rules for how JSON changes string to it's own notation for "internal" use, see http://json.org/ for the string type.
Still if you want to remove slash use string.replace from java or any other libraries or simply escape the character