text:
Q: How to populate lists of objects with WTForms? Use case: using a form to enter grades for each course a student is enrolled in.
Model:
Using SQLAlchemy, I defined a Student object, a Course object, and a StudentCourse association object that stores each student's grade for each course.
class Student(Base):
    __tablename__ = 'students'
    id = Column(Integer, primary_key=True)
    name = Column(Text)
    courses = association_proxy('student_courses', 'grade',
        creator=lambda k, v: StudentCourse(course_title=k, grade=v))
    ...

class Course(Base):
    __tablename__ = 'courses'
    id = Column(Integer, primary_key=True)
    title = Column(Text, unique=True)
    ...

# Link students to courses and store grades
class StudentCourse(Base):
    __tablename__ = 'student_courses'
    student_id = Column(Integer, ForeignKey(Student.id), primary_key=True)
    course_id = Column(Integer, ForeignKey(Course.id), primary_key=True)
    grade = Column(Integer)
    student = relationship(Student,backref=backref(
            'student_courses',
            collection_class=attribute_mapped_collection('course_title'),
            cascade='all, delete-orphan'))
    course = relationship(Course)

    @property
    def course_title(self):
        if self.course is not None:
            return self.course.title
        else:
            return self._course_title
    ...

View:
I can query the StudentCourses model and construct a relevant form, but I can't figure out how to pass/retrieve the data from the query as an object.
def view(request):
    student = Student.from_request(request)
    student_courses = DBSession.query(StudentCourse).\
        filter(StudentCourse.student_id == student.id).\
        all()

    class GradesForm(Form):
        pass

    # Add form field for each course the student is enrolled in
    for c in student_courses:
        setattr(GradesForm,
                c.course_title,
                IntegerField()
                )

    form = GradesForm(request.POST, obj=student_courses) # this doesn't populate the form

    return {'form': form}

This produces a blank form, so I obviously can't populate the form with data directly from the Query object. But I've been unsuccessful populating the form with any kind of object, even when creating a form with a FormField type for each course:
class StudentCourseForm(Form):
    course_title = StringField()
    grade = IntegerField()

def view(request):
    ...
    class GradesForm(Form):
        pass

    # Add form field for each course
    for c in student_courses:
        setattr(GradesForm,
                c.course_title,
                FormField(StudentCourseForm)
                )

    form = GradesForm(request.POST, obj=student_courses)

    return {'form': form}

Using a query, if possible, would be the easiest. Per the SQLAlchemy docs, using the query() method on a session creates a Query object. When iterated like I did in my controller, this object is a list of StudentCourse objects.
[<app.models.StudentCourse object at 0x10875bd50>, <app.models.StudentCourse object at 0x10875bed0>]
...and my progress ends here. Any help appreciated!

A: The only way I've been able to populate these dynamically-created forms is by passing **kwargs, so I'll post this method as an answer until someone else can figure out an object-based solution.
To populate the form:
def view(request):
    ...
    data = {}
    for c in student_courses:
        data[c.course_title] = c.grade

    # Populate form
    form = GradesForm(request.POST, **data)
    ...

In this way, I can render a form in a template by iterating over the fields, and when submitted, I'll have a list of dicts which I can then validate and use to update my database records.
Form validation requires the same method:
def view(request):
    ...
    # Validate and persist form data
    if request.method == 'POST' and form.validate():
        for c in student_courses:
            student.courses[c.title] = form[c.title].data

This works, but it'd be great if I could use the WTForms populate_obj() method:
def view(request):
    ...
    if request.method == 'POST' and form.validate():
        form.populate_obj(student_courses)


text:
Q: How to Check dependency service is working or not, before consume the message in ActiveMQ
*

*In my application i generate the pdf and send email using
ActiveMQ.(i.e application never wait for pdf generation, it will put
the message into queue after that my consumer application get the
message from queue and create pdf then send it to customer).

*my application built on top of spring-framework

*i need to stamp the digital signature in my pdf, if the third party digital-signature server is down, i don't want my consumer to take
message for queue.

*if any possibility to add dependency in consumer before consume message

A: This scenario is a textbook use case for using consumer-side transactions with enterprise messaging. Use the SESSION_TRANSACTED or ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE mode in the session. This allows you to roll the message back to the broker in the event the downstream system is down. You can add delays or retries within your consumer program, and only acknowledge the message when you know its been sent to the other system.
ref: http://activemq.apache.org/how-do-transactions-work.html
Circuit break won't help you if your reliable() path is down as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mockito: set value to spy object but get null I have a test case where I want to see if a property is set correctly during the execution:
ContainerRequestContext requestContext = spy(ContainerRequestContext.class);
someMethodThatSetsTheSecurityContext(requestContext);

verify(requestContext).setSecurityContext(argument.capture());
assertEquals("myUserName", argument.getValue().getUserPrincipal().getName());
assertNotNull(requestContext.getSecurityContext());

Now if I run this, the verify() and assertEquals() methods return true, but for some reason the requestContext.getSecurityContext() is null.
I understand that for mocked object there is no real implementation behind, but I thought the spied object should work in this case.

A: Try to use Mockito.argThat instead and see if it changes it:
verify(requestContext).setSecurityContext(Mockito.argThat(x -> x.getValue().getUserPrincipal().getName().equals("myUserName")));


text:
Q: How to get latex in edge labels using dot2tex? The following example does not  work. The edge label doesn't show up properly.
DiGraph {
X [texlbl="$X$"]
Y [texlbl="$Y_s$"]
X -> YY [texlbl="$\int f(x) dx$"]
}

Looking for a way to get edge labels to work.

A: Ugh just saw this deep in the pdf after I posted:

If you use texlbl for edges, you have to provide a dummy label
  attribute. Otherwise Graphviz will not generate the necessary code for
  placing edge labels

So do this:
X -> YY [label="      ", texlbl="$asdf$"]


text:
Q: CakePHP Routing, reverse redirection Let's say i have a controller Articles and an action Search.
I have set the router configuration in routes.php like this:
Router::connect(
                 '/search/:search_term/*',
                 array('controller' => 'articles', 'action' => 'search')
);

This way i can see the article titles containing 'cakephp' in search results when i navigate to http://localhost/search/cakephp
But if i navigate to http://localhost/articles/search/cakephp i see the same results.
What i want is to be automatically redirected to
http://localhost/search/cakephp

when i navigate to
http://localhost/articles/search/cakephp

based on the configuration in routes.php.

A: you have to create .htaccess redirect for that you can't do it with routes:
RewriteRule ^articles/search/(.+)$ /search/$1 [L,NC]

OK I found something but not quite sure it will work:
Router::redirect(
    '/articles/search/*',
    '/search/',
    array('persist' => true)
);


text:
Q: A model's name contains 'cache' In my code, I have a model whose name contains the string 'cache'. For example:
class DataCache < ActiveRecord::Base

and the table name is data_caches. When I run:
"data_caches".classify.constantize.new

to initialize the model, I get an error like this:
NameError: uninitialized constant DataCach

Why doesn't this work? I expected "DataCache" but got "DataCach".

A: Take a look at the Inflections class in Rails. Add the following text to the config/initializers/inflections.rb class:
ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'cache', 'caches'
end

Now in the rails console try out the word:
>> "caches".singularize
=> "cache"
>> "cache".pluralize
=> "caches"

A: You should help rails understand how to convert singular to plural in this case. Try to update config/initializers/inflections.rb with this name. I think it should solve the problem.


text:
Q: How do you replace and save documents in MongoDB? I currently have a database that holds 5 entries per document in my mongoDB. Here is an example
I would like to update my documents in my database with more fields and information. Currently I am doing that with the code below.
    NFT.findOne({ "name": name }, (err, value) => {
        if (err) { console.error(err) }
        if (!value) {
            console.log('no value')
            let newNFT = new NFT({name, slug, symbol, description, verifiedStatus, bannerUrl, logoUrl, floorPrice, stats, social})
            newNFT.save()
        }
        else {
            let newNFT = new NFT({name, slug, symbol, description, verifiedStatus, bannerUrl, logoUrl, floorPrice, stats, social})
            NFT.replaceOne({"name": name}, newNFT, {returnDocument: "after"})
        }
    })

The reason for this question is, I have run console.log(NFT.find({"name": name}) and gotten an object back with all of the fields however, they don't seem to update in my database online. Because it pulls information from the web database, I know I'm connected, but they just aren't updating. What am I doing wrong here?

A: save() returns a Promise, you should await it.
Plus, try to change the code for updating your existing value:
NFT.findOne({ name }, async (err, value) => {
  if (err) {
    console.error(err);
  }
  if (!value) {
    // Create new NFT
    let newNFT = new NFT({
      name,
      slug,
      symbol,
      description,
      verifiedStatus,
      bannerUrl,
      logoUrl,
      floorPrice,
      stats,
      social,
    });
    await newNFT.save();
  } else {
    // Update existing NFT
    value.name = name
    value.slug = slug
    value.symbol = symbol
    value.description = description
    value.verifiedStatus = verifiedStatus
    value.bannerUrl = bannerUrl
    value.logoUrl = logoUrl
    value.floorPrice = floorPrice
    value.stats = stats
    value.social = social
    await value.save();
  }
});


text:
Q: How can I format a Google Protocol Buffers object in XML and parse from XML I'm going to pass GPB objects over the wire but in the local application I need to save them locally in XML (customer demands XML, no editing tool, don't ask me why) so the customer can edit the XML (which brings me to the other part of my question - parsing GPB from XML).
Is anyone aware of a framework which does this?
I need this code in C++ on Windows.

A: There is no C++ implementaion for this as far as I am aware.
You can port this code from Java http://code.google.com/p/protostuff/
if you want we can port it togeather I also need the same as you!
One of the problems is that pb are not self describing so you need to whole the schema outside  which is not ideal.
The documentaion on reflections which onbody uses inside of Google is a little confusing for me. http://code.google.com/apis/protocolbuffers/docs/reference/cpp/google.protobuf.message.html#Message.
Also see here Show all elements in a protocol buffer message


text:
Q: How reuse latex code for later expansion? I would like to make a command to help me writing lines like:
The \LaTeX~code is: \verb@e^{i\pi} - 1 = 0@, and the result is: $e^{i\pi} - 1 = 0$.

I thought of using a newcommand as:
\newcommand{\eqn}[1]{The \LaTeX~code is: \verb@#1@, and the result is: $#1$.}

to use as:
\eqn{e^{i\pi} - 1 = 0}

which doesn't work.
Trying to pull out the verbatim out as:
\newcommand{\eqn1}[1]{The \LaTeX~code is: #1, and the result is: $#1$.}

to use as:
\eqn1{\verb@e^{i\pi} - 1 = 0@}

also doesn't work.
My question is, is there a way to achieve this in latex?
Thank you.
PS: unfortunately the thread bellow seems to indicate that it's not possible :(
Wrapping code (listings, verbatim, or other method) inside a newcommand

A: Absorb the argument verbatim and rescan it when you need the real output:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\eqn}{v}
 {
  The~\LaTeX{}~code~is:~\texttt{#1},~and~the~
  result~is:~\tl_rescan:nn { } { $#1$ }.
 }
\ExplSyntaxOff

\begin{document}

\eqn{e^{i\pi} - 1 = 0}

\end{document}

A: With inspiration from this answer by Ulrich Schwarz, we can solve this using \meaning:
\documentclass{article}

\makeatletter
\newcommand\meaningbody[1]{%
  {\ttfamily
    \expandafter\strip@prefix\meaning#1}%
}
\newcommand\eqn[1]{%
  {\def\@foo{$#1$}The \LaTeX~code is \meaningbody\@foo, and the result is: $#1$.}%
}
\makeatother

\begin{document}

\eqn{e^{i\pi} - 1 = 0}

\end{document}

The result is:

One potential problem is that the output from \meaning is not exactly the same as the input code. There is an extra space after \pi in this example.


text:
Q: Visual Studio Code Python Terminal more cleaner? When I run python code in VSC I get this nonsense that I dont need, Is there a way to remove it? The PS C:\Users.. thing

A: Have you tried adding python to system path?
Are you trying to run code like this?

python main.py

This link has the process for adding python to system variable.
https://datatofish.com/add-python-to-windows-path/

A: This information in the VS Code terminal is useful information. When we click the run button, it executes the run command in "Terminal", showing us the path of the python used and the path of the executed file, which avoids the confusion of multiple versions of python.
If you want to omit the displayed paths, you could click F5 to debug the file:
(Please use "console": "internalConsole", in launch.json.)

Or use the VS Code extension such as "Code Runner".


text:
Q: Laravel using where on eager loaded relationship Hi I have the following code to retrieve all posts along with their comments (1 to many relationship)
$posts = Post::with('comments')->get();

Now it works great but my problem is let say I want to do a search on the post title or comment content if given an optional parameter. Something like:
$posts = Post::with('comments');

if (Request::has('query')) {
    $posts = $posts->where('content', 'LIKE', '%' . Request::get('query'))->orwhere('title', 'LIKE', '%' . Request::get('query'));
}

$posts = $posts->get();

Now this doesn't work as 'content' column only exists on the comments table. Is there any way do use the where condition on the eager loaded comments relationship?

A: Use whereHas() when building your query, an example from the docs:
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

Docs link

A: Use orWhereHas() and orWhere():
$posts = Post::with('comments');

if (request()->has('query')) {
    $posts = $posts->orWhereHas('comments', function($q) {
        $q->where('content', 'like', '%'.request('query'));
    })->orWhere('title', 'like', '%'.request('query'));
}

$posts = $posts->get();

Test it. If you'll want to change behavior, you can use whereHas() and/or where() inside if() construction.

A: Use Constraining Eager Loads
if (request()->has('query')) {
    $posts = Post::where('title', 'LIKE', '%' . Request::get('query'))->with(['comments' => function ($query) {
        $query->orWhere('content', 'LIKE', '%' . Request::get('query'));
    }]);
} else {
    $posts = Post::with('comments');
}

$posts = $posts->get();

And i thought @Alexey Mezenin's answer was incorrect, the result would be all posts with comments.


text:
Q: Seg fault when accessing pointed to vector element by index -- what am doing wrong? I'm created a pointer to a vector and adding a member to it but I can't call that member by index without getting a seg fault. Why is that?
When I use the back() method I can access it fine.
Example using index:
#include <iostream>
#include <vector>

using namespace std;

int main() {
  vector<int> * a;
  a->push_back(2);
  cout<< (*a)[0] << endl;
}
// Segmentation fault (core dumped)

Example using back():
#include <iostream>
#include <vector>

using namespace std;

int main() {
  vector<int> * a;
  a->push_back(2);
  cout<< (*a).back() << endl;
}
// 2

Does this mean that the back of my vector is not at index = 0 ?

A: The example using back() is wrong. You should new a vector object before using it:
a = new vector<int>();

Yes, your code compiles. Different compilers have different initial values of a.  On my system, a is NULL, so it will throw out a "segfault" on a->push_back(2).
Try different compilers, the result will be different.
I am not sure what will happen if a has an uninitialized value, but it is dangerous.


text:
Q: Format inline output conditional on textual context Using a modification (adapted from Jason French's blog post here) to the default inline knitr hook, I am printing numeric output rounded to 3 decimal places. If the value is less than 0.001, it returns "< 0.001".
Here's an MWE showing the hook modification, and how I might use it in practice in R Markdown:
```{r setup, echo=FALSE}
library(knitr)
inline_hook <- function(x) {
  if (is.numeric(x)) {
    res <- ifelse(x == round(x),
      sprintf("%d", x),
      sprintf("%.3f", x)
    )
    res <- ifelse(x < 0.001, '< 0.001', res)
    paste(res, collapse = ", ")
  } else paste(as.character(x), collapse = ", ")
}

knit_hooks$set(inline = inline_hook)
```

```{r, echo=FALSE}
stat <- 1.2345
p <- 0.000001
```

Blah was significant (test statistic = `r stat`, p = `r p`)

The above renders as:
Blah was significant (test statistic = 1.234, p = < 0.001)

Note the p = < 0.001. Preferably, this would be p < 0.001. Is it possible to have knitr check whether an equals sign precedes the inline expression, and if it does, suppress it when appropriate?
In case it makes a difference, I'm actually knitting a Sweave document, not R Markdown.

A: Personally, I don't like the inline_hook used in the question / the linked blog. Automatically converting output like this seems risky to me. The current question is a case in point: Sometimes the conversion is harmful.
There is a trivial and a somewhat complex solution to the issue.
Trivial solution
The hook can be circumvented using asis_output:
`r asis_output(0.0001)`

outputs 1e-04, i.e. the hook doesn't apply. Otherwise the output was < 0.001.
Drawback: You either use the hook, but then you dont know whether you get [number] or < [number] as output (which is a problem when you want output like "p = [number]" / "p < [number]"). Or you use asis_output; then you know there will be no (in-)equality sign, but you cannot take advantage of the hook.
Advanced solution
The following function applies inline_hook but adds an additional = sign if the hook doesn't add <:
le <- function(x) {
  rel <- if (x >= 0.001) "=" else ""
  return(asis_output(paste(rel, inline_hook(x))))
}

This has the following advantages:

*

*The hook can be used.

*There always is an (in-) equality sign.

Note that le is not vectorized.
Examples:
```{r setup, echo=FALSE}
library(knitr)
inline_hook <- function(x) {
  if (is.numeric(x)) {
    res <- ifelse(x == round(x),
                  sprintf("%d", x),
                  sprintf("%.3f", x)
    )
    res <- ifelse(x < 0.001, '< 0.001', res)
    paste(res, collapse = ", ")
  } else paste(as.character(x), collapse = ", ")
}

knit_hooks$set(inline = inline_hook)

le <- function(x) {
  rel <- if (x >= 0.001) "=" else ""
  return(asis_output(paste(rel, inline_hook(x))))
}

```

* p `r le(0.01)` (value: 0.01)
* p `r le(0.001)` (value: 0.001)
* p `r le(0.0001)` (value: 0.0001)
* p `r le(0.00001)` (value: 0.00001)

Output:
p = 0.010 (value: 0.01)
p = 0.001 (value: 0.001)
p < 0.001 (value: 0.0001)
p < 0.001 (value: 0.00001)


text:
Q: Automatically create an Azure DevOps Organization with an ARM Template Since it is not possible to create an organization with the DevOps Rest API and the SDK for organizations is still in preview and not functional, we currently try to programmatically create an organization with an ARM template.
In the Azure Portal, it is possible to create a new organization with an ARM template like this:
{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/Microsoft.Resources.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "organizationName": {
      "type": "string",
      "defaultValue": ""
    },
    "organizationIdentifier": {
      "type": "string",
      "defaultValue": ""
    },
    "administrator": {
      "type": "string",
      "defaultValue": ""
    }
  },
  "resources": [
    {
      "name": "[parameters('organizationIdentifier')]",
      "type": "microsoft.visualstudio/account",
      "location": "West Europe",
      "description": "[parameters('organizationName')]",
      "apiVersion": "2014-02-26",
      "properties": {
        "operationType": "Create",
        "accountName": "[parameters('organizationIdentifier')]",
        "ownerUpn": "[parameters('administrator')]"
      }
    }
  ]
}

Unfortunately we couldn't find a solution to create this within a C# Azure Function programmatically, since the SDK would want a resource group, which doesn't make sense in this context. Is there a way to do this or is it simply not possible to create an organization automatically at this point?

A: Yes, as of now there is no ways to create an DevOps organization using REST API.
The way to create Azure DevOps Organization is Manual creation or using ARM Template.
Using ARM Template, you have to specify the Resource   name as a parameter. That is also we need to mention the Organization Name before deploying the ARM Template.
As of now the REST API is available for some of the services.
References
-Automating organization and project creation in Azure DevOps Blog gives the clear view


text:
Q: Is it possible to listen for the screen dimming or going black while not in my app? I'm writing a Kiosk app that, along with having some UI elements, also has a service that sits around in the background while the user explores other features on the device, and wish to re-launch the UI portion of the kiosk when the user has walked away. I figured that the most reliable way to do this is to listen for the screen to go dim and react to that event. However, I'm not seeing anything in the documentation about a system wide broadcast that I can listen to that the screen state has changed. Curious if I'm just overlooking it, or if it doesn't exist.

A: Take a look at this answer:
android.intent.action.SCREEN_OFF
FYI there is a full list of broadcast intents available in your sdk/platforms/android-xx/data/broadcast_actions.txt if you want to have a look. I found these two quickly, which led me to the answer I linked:
android.intent.action.SCREEN_OFF
android.intent.action.SCREEN_ON


text:
Q: get value from one column as variable for subtraction i have a data frame with XY's and distances.  what i am trying to do is store the distance as a variable and subtract it from the next distance if X or Y has a value greater than 0
here is a sample df
dist     x      y
  0    12.93   99.23
200     0        0
400     0        0
600     0        0
800     0        0
1000    12.46   99.14
1200     0        0
1400     0        0
1600     0        0
1800     0        0
2000    12.01   99.07

and this is new df
dist     x      y
  0    12.93   99.23
200     0        0
400     0        0
600     0        0
800     0        0
  0    12.46   99.14
 200     0        0
 400     0        0
 600     0        0
 800     0        0
2000    12.01   99.07

the last value doesn't matter, but technically, it would be 0.
the idea is that at every know XY, assign the distance as 0 and subtract that distance until the next known XY
in the above example, the distances are rounded numbers, but in reality, they could be like
132.05
19.999
1539.65

and so on

A: You can use groupby and apply, using a custom grouper calculated as follows:
grouper = (df['x'].ne(0) | df['y'].ne(0)).cumsum()
df['dist'].groupby(grouper).apply(lambda x: x - x.values[0])

0       0
1     200
2     400
3     600
4     800
5       0
6     200
7     400
8     600
9     800
10      0
Name: dist, dtype: int64

Where,
grouper

0     1
1     1
2     1
3     1
4     1
5     2
6     2
7     2
8     2
9     2
10    3
dtype: int64

The idea is to mark all rows that must be subtracted from the first non-zero value of that corresponding group.

A: With where + ffill
df['dist'] = df.dist - df.where(df.x.gt(0) | df.y.gt(0)).dist.ffill()

     dist      x      y
0     0.0  12.93  99.23
1   200.0   0.00   0.00
2   400.0   0.00   0.00
3   600.0   0.00   0.00
4   800.0   0.00   0.00
5     0.0  12.46  99.14
6   200.0   0.00   0.00
7   400.0   0.00   0.00
8   600.0   0.00   0.00
9   800.0   0.00   0.00
10    0.0  12.01  99.07

A: Check with transform
df.dist-=df.groupby(df.x.ne(0).cumsum())['dist'].transform('first')
df
Out[769]:
    dist      x      y
0      0  12.93  99.23
1    200   0.00   0.00
2    400   0.00   0.00
3    600   0.00   0.00
4    800   0.00   0.00
5      0  12.46  99.14
6    200   0.00   0.00
7    400   0.00   0.00
8    600   0.00   0.00
9    800   0.00   0.00
10     0  12.01  99.07


text:
Q: What will be the velocity of the truck after 50 minutes? This question came in the Rajshahi University admission exam 2019-20
Q) A truck of 5 metric ton filled with sand was moving with a velocity of $20ms^{-1}$. A hole was created in the truck through which $20kg$ sand falls down each minute. If momentum is conserved, then what will be the velocity of the truck after $50$ minutes?
(a) $20ms^{-1}$
(b) $25ms^{-1}$
(c) $25.5ms^{-1}$
(d) None
My attempt:
I think the answer will be (a). I am basing my answer on the conservation of linear momentum. The sand that was ejected still had the same velocity as the truck at the time of the ejection, so even as the sand is being ejected, the truck should still have the same velocity after 50 minutes.
I'll try to show this mathematically.
mass of sand ejected after 50 min, $m_1=20\times50=1000kg$
(mass of remaining sand + mass of truck)$=m_2=5000-1000=4000kg$
velocity of truck before ejection of any sand, $v=20ms^{-1}$
velocity of ejected sand, $v_1=20ms^{-1}$
velocity of truck after ejection of sand, $v_2=?$
According to the law of conservation of momentum,
$$v(m_1+m_2)=m_1v_1+m_2v_2$$
$$v_2=\frac{v(m_1+m_2)-m_1v_1}{m_2}$$
$$v_2=\frac{20(1000+4000)-1000\times 20}{4000}$$
$$v_2=20ms^{-1}\text{(Ans.)}$$
This is why I think that (a) is the answer.
A third party's claim:
A third-party question bank is of the opinion that (b) is the correct answer. The following is their attempt:
initial mass$=5000kg$
After 20 minutes $=(5000-20\times 50)kg=4000kg$
Since momentum is conserved, $5000\times 20=4000\times x \therefore x=25ms^{-1}$. So, (b) is the answer

Isn't the third party wrong?

A: Your assessment is correct - if the truck moves over a frictionless surface in vacuum:
The sand which falls through the hole does not transfer any momentum to the truck in doing so. Thus the momentum of each remaining part and cargo of the truck remains the same. Mind: this does mean that the total momentum of the truck with its remaining cargo drops as the dropping sand carries away its own momentum as it leaves the truck with the truck's speed and of course its own weight. What does not change here is the specific momentum, that is the momentum per unit mass.
The situation would be different, if someone threw the sand from the back of the truck with a certain velocity. In essence we then would have a rocket. but that's not answer (b) or (c) either and would need an assumption on the velocity used with which it is being thrown out.
Answer (d) would be correct for a real-life truck on a real surface with friction in air without any engine running: the drag of the air and the friction with the ground would dissipate any initial kinetic energy and it would come to a stop. With some guesses on the truck's cross-section and aerodynamic properties as well as the friction of the tires one could calculate the stopping time - but experience tells us that it definitely is less than 50 minutes.
As such: you can argue (a) or (d) - you just have to argue correctly. Or maybe the question or exam in general gives additional information which you did not quot here and allows to argue only (a) or (d). :)


text:
Q: Building a deep Nested array of objects in PHP using Recursion Basically, this is what I want to achieve
Jason
   ->Ronda
          ->Cat
               ->Abraham
               ->Jacob

  ->Joseph
          ->Brock
          ->Dustin

In JSON Format, this is what I would like to achieve
{
    id: 1,
    username: Jason,
    children: [
        {
            id:2,
            username:Ronda,
            children: [
                {
                    id:4,
                    name: Cat,
                    children:[
                        {
                            id:8,
                            username:Abraham,
                            children:[]
                        },
                        {
                            id:9,
                            username:Jacob,
                            children:[]
                        }
                    ]
                },
                {
                    id:5,
                    username:Connor,
                    children:[]
                }
            ]
        },
        {
            id:3,
            username:Joseph,
            children: [
                {
                    id:6,
                    username:Brock,
                    children: []
                },
                                {
                    id:7,
                    username:Dustin,
                    children: []
                },
            ]
        }
    ]
}

I have 2 tables in my database
Users
id username  parent
1  Jason      null
2  Ronda       1
3  Joseph      1
4  Cat         2
5  Connor      2
6  Brock       3
7  Dustin      3
8  Abraham     4
9  Jacob       4

UserLevels
id  upline downline level
1    1      2          1
2    1      3          1
3    1      4          2
4    1      5          2
5    1      6          2
6    1      7          2
7    1      8          3
8    1      9          3
9    2      4          1
10   2      5          1
11   2      8          2
12   2      9          2
13   3      6          1
14   3      7          1

Basically the user levels table is showing how deep or how each person is related to. For an example,Jacob is the great grandchild of Jason. Hence the userlevels id 8 represents their relationship. Jason is the upline which is user id 1, Jacob is the downline which is user id 9 , and it is 3 levels deep.
This is my code.
ListController.php (Controller)
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Collection;
use Inertia\Inertia;
use Carbon\Carbon;

use App\Models\User;
use App\Models\UserLevel;
use Auth;

class ListController extends Controller {
    protected function getDownline($upline) {
        return UserLevel::where([
            'upline' => $upline,
            'level' => 1
        ])->get();
    }

    protected function getUserName($id) {
        return User::findOrFail($id)->username;
    }

    //Recursion here
    public function getHierachyDataHelper($downline,$currentUserId) {
        $result = collect([
            'id' =>$currentUserId,
            'username' => $this->getUserName($currentUserId),
            'children' => collect()
        ]);
        foreach ($downline as $key => $child) {
            # code...
            $result['children']->push(collect([
                'id' =>$child['downline'],
                'username' => $this->getUserName($child['downline']),
                'children' => collect()
            ]));
            $children = $this->getDownline($child['downline']);
            if ($children->count() > 0 ) {
                # code...
                $this->getHierachyDataHelper($children , $child['downline']);
            }
        }
        return response()->json([
            'data' =>$result
        ]);

    }

    public function getHierachyData() {
        $currentUser = Auth::user();
        $downline = $this->getDownline($currentUser->id);
        return $this->getHierachyDataHelper($downline,$currentUser->id);
    }

}

UserLevel.php (model)
<?php

namespace App\Models;

use App\Models\User;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserLevel extends Model
{
    use HasFactory;
    protected $table = "user_levels";

    protected $fillable = [
        'upline',
        'downline',
        'level',
    ];

    public function uplineUser()
    {
        return $this->belongsTo(User::class, 'upline');
    }

    public function downlineUser()
    {
        return $this->belongsTo(User::class, 'downline');
    }
}

User.php(model)
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Appreciate any help given, Thank you very much :)


text:
Q: I have two emacs buffers in a frame: A.cc | B.cc I have two emacs buffers in a frame: A.cc | B.cc
So assume I have focus on B.cc. I want to fast copy B.cc to the left window by one stroke (like some hotkeys).
the final state is B.cc | B.cc. Currently, I can only use C-x b and type in a few chars of the buffer name. this is very slow.
NOTE: this should not be another opened replica buffer(e.g., B.cc[replicated], you know what i mean if you are a emacs user) but exact the same buffer, just show in two different windows

A: Select the other window:
(switch-to-buffer-other-window (current-buffer))

Do not select the other window:
(display-buffer (current-buffer) t)

Select the other window.:
(pop-to-buffer (current-buffer) 'other-window)

Here is an example of a global keyboard shortcut using the F5 key -- insert whatever function you want instead of ...:
(global-set-key [f5] (lambda ()
  (interactive)
    ... ))


text:
Q: Can Ordinal Regression be done on 2 likert scale variables I have 2 ordinal variables:

*

*Preferred Brand ranking 1 to 5 1 being Very Poor 5 being Very Good

*Preferred Country of Origin also ranking as above

Which test can I use to establish if the 2 variables are correlated? Is it possible for me to run Ordinal regression in SPSS?  If so which type of Ordinal regression?


text:
Q: Gradle cpp plugin doesn't link shared library I have a C++ library to listen to radio with RF24. I wrap this library using JNI with a Java class.
The issue that I have is that gradle don't link the shared library librf24.so into my library libtransmitter.so.
When I call ldd on libtransmitter.so I have :
linux-vdso.so.1 (0x7ee24000)
/usr/lib/arm-linux-gnueabihf/libarmmem.so (0x76ecc000)
libstdc++.so.6 => /usr/lib/arm-linux-gnueabihf/libstdc++.so.6 (0x76d73000)
libm.so.6 => /lib/arm-linux-gnueabihf/libm.so.6 (0x76cf4000)
libgcc_s.so.1 => /lib/arm-linux-gnueabihf/libgcc_s.so.1 (0x76cc7000)
libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0x76b88000)
/lib/ld-linux-armhf.so.3 (0x76ef5000)

librf24.so is not present
Here is my gradle configuration :
model {

    platforms {
        raspberry {
            architecture "arm"
            operatingSystem "linux"
        }
    }
    toolChains {
        raspToolChain(Gcc) {
            target("raspberry") {
              //  path 'C:\\SysGCC\\raspberry\\bin'
              //  cCompiler.executable 'arm-linux-gnueabihf-g++.exe'
              //  cppCompiler.executable 'arm-linux-gnueabihf-g++.exe'
              //  assembler.executable 'arm-linux-gnueabihf-g++.exe'
              //  linker.executable 'arm-linux-gnueabihf-g++.exe'
              //  staticLibArchiver.executable 'arm-linux-gnueabihf-ar.exe'
            }
        }
    }

    repositories {
        libs(PrebuiltLibraries) {
            jniLib {
                headers.srcDir projectDir.absolutePath + "\\jni\\include"
                headers.srcDir projectDir.absolutePath + "\\jni\\include\\linux"
            }
            rf24 {
                headers.srcDir projectDir.absolutePath + "\\rf24\\RF24"
                headers.srcDir projectDir.absolutePath + "\\rf24\\RF24\\utility"
                headers.srcDir projectDir.absolutePath + "\\rf24\\RF24\\utility\\RPi"
                binaries.withType(SharedLibraryBinary) {
                    sharedLibraryFile = file( projectDir.absolutePath + "\\rf24\\librf24.so")
                    sharedLibraryLinkFile = file( projectDir.absolutePath + "\\rf24\\librf24.so")
                }
            }
        }
    }

    components {
        transmitter(NativeLibrarySpec) {
            targetPlatform "raspberry"
            sources {
                cpp.lib library: 'jniLib', linkage: 'api'
                cpp.lib library: 'rf24', linkage: 'api'
            }
        }
    }

}

A: Use the following instead:
cpp.lib library: 'rf24', linkage: 'shared'

This induces a transitive dependency from libtransmission to librf24.
It is not enough to put the files side by side to be found, however. You should either set LD_LIBRARY_PATH at runtime or compile libtransmission with a relative RPATH .


text:
Q: restoring dropdown selected values in c# after refresh by retrieving values from database I have created a dropdownlist in my webpage which is outside the gridview and I have added automatic refresh. My problem is that I`m unable to retain the selected value in dropdownlist after the refresh. It goes to the default settings in the dropdown. Please help.

Thanks a lot for replying..
part of my code goes this way....
page_load(...)
{
 Refresh
 if(!IsPostBack)
 {
   //calling my function which includes databind..
    myfunction();
 }
}

i tried the same code as you people suggested but its not working..
even now after refresh, the default values appear in dropdownlist

A: Let me guess your Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
    DataBindGridView(); // loads the datasource of the grid and calls gridView1.DataBind();
    DataBindDropDown(); // loads the datasource of the dropdown and calls dropDown1.DataBind();
}

Do not reload all on every postback, just if !(IsPostBack):
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        DataBindGridView();
        DataBindDropDown();
    }
}

If you need to refresh your GridView don't use Page_Load but the appropriate event handler. If you use an ASP.NET Timer to reload your page periodically to refresh the grid, use it's Tick event.
protected void GridRefreshTimer_Tick(object sender, EventArgs e)
{
    DataBindGridView();
}

A: You probably need to implement something like this in your page_load handler:
if (IsPostback) return;
//here populate the dropdown


text:
Q: Where do I put Laravel 4 helper functions that can display flash messages? I've written a simple display_messages() function that will search Session::get('errors') for flash data and echo it to the screen.
Where do I put this function? In Codeigniter, you had a helpers folder where you could stick all your little global helper methods.

A: For loading Classes:
Create app/libraries/class/Message.php, and add class in file
class Message {
    public static function display() {

    }
}

Add "app/libraries/class" to composer.json
"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php",
        "app/libraries/class"
    ]
},

Finally run composer dump-autoload in command line.
You can access that by Message::display()
For loading plain non-object php Functions:
Create app/libraries/function/display_messages.php, and add function in file
function display_messages() {

}

add one line in start/global.php
require app_path().'/libraries/function/display_messages.php';

You can access that just by display_messages()

A: As Usman suggested,

*

*create a file /application/libraries/demo.php

*define a class Demo() { inside it

*call the function like so: {{ Demo::display() }}
Works because libraries and models are autoloaded in start.php line 76.  I believe that filenames must match Classnames (note capital).
<?php

class Demo {

    public static function display() {

        if( !$message = Session::get('errors'))
            $message = 'No Errors';

        echo "
print_r($message)
";

    }

}

Can't quite figure out why I had a problem using the classname Common, there may be a conflict (you could define a namespace if this were important)...

A: Create a folder helpers within your app folder and create a file application_helper.php. With such code:
// app/helpers/application_helper.php

function display_messages()
{
  exit('Yes');
}

Then open your composer.json file in root. autoload app/helpers/application_helper.php with composer files.
"autoload": {
....

    "files": [
        "app/helpers/application_helper.php"
    ]

Done, you can now call display_messages().
Some autoloaders may require you to run composer dump command for the first time.

A: Thank you memeLab provided a very useful answer which helped me a lot. I just wanted to expand on his answer as the "libraries" folder was not an auto load directory, at least not in the release/current version of L4 I am using. Also the start.php seems to have been expanded to be  the start folder with global.php, local.php, and artisan.php.
So to use your own classes for separate libraries or helpers with the L4 lazy auto loader you just have to include whichever folder you want to store these in to the global.php. For example I added a libraries folder to the directory list.
ClassLoader::addDirectories(array(

    app_path().'/commands',
    app_path().'/controllers',
    app_path().'/models',
    app_path().'/database/seeds',
    // this a custom path
    app_path().'/libraries',

));

Then whatever class you define in that folder as classname.php can be called via CLASSNAME::methodName($someVar); in your controllers.
class CLASSNAME {

    public static function methodName($someVar=NULL) {

        // whatever you want to do...

        return $message;
    }

}

So in this fashion you can create a helper class and define different methods to use throughout your controllers. Also be careful defining regular functions outside of your Class in this manner will cause you grief because they will not work (because the class is not always loaded). (for example someFunctionName($someVar); instead of CLASSNAME::methodName($someVar);) If you want to create functions in this manner you would need to make sure the is loaded, however I will not elaborate on this because it is better practice to use the lazy loader classes for such things so you only load the classes you really need.
Thanks again to memeLab and Usman, I would not have gotten as far without their answers. :)

A: Add this in app/start/global.php
require app_path().'/config/autoload.php';
require app_path().'/start/loader.php';
App::instance('loader',new loader($autoload));

create a new file loader.php in app/start and add:
class loader{
private $helpers = array();
public $autoload = array(
    'helpers' => array()
);
function __construct($autoload  = array()) {
    if (!empty($autoload))
        $this->autoload = $autoload;
    foreach ($this->autoload as $key => $value)
    {
        $function = strtolower($key);
        $this->$function($value);
    }
}
function helpers($helpers=array())
{
    if (!is_array($helpers))
        $helpers = explode(",",$helpers);
    foreach ($helpers as $key => $value) {
        $this->helper($value);
    }

}
function helper($helper = '',$path = '/')
{
    $folder = app_path().'/helpers'.$path;
    if (file_exists($folder.$helper.'.php') && !in_array($helper, $this->helpers)){
        $this->helpers[] = $helper;
        require $folder.$helper.'.php';
    }
    else{
        $segments = explode('/',$helper);
        if (is_dir($folder.$segments[0])){
            array_shift($segments);
            $this->helper($segments,$path.$segments[0].'/');
        }
    }
}

}
create a new file autoload.php in app/config and add:
$autoload['helpers'] = array('functions'); // my autoload helpers!

create a new folder helpers in app/ , add your helper files. ( es. myhelper.php )
function myhelper()
{
echo 'helper';
}

in your controller add:
App::make('loader')->helper('myhelper');
    myhelper();

A: In L3, I would normally create a application/libraries/helpers.php file, and require_once() it in my application/start.php.  Similar to how L3 has a laravel/helpers.php file.
I'm assuming there is something similar you can do in L4.
EDIT:  Just looking at the source, app/start/local.php seems like it might be the place.

A: I used this tutorial and i think is the easiest method: http://laravel-recipes.com/recipes/50/creating-a-helpers-file

*

*First create the file app/helpers.php

*Then either load it at the bottom of app\start\global.php as follows.
// at the bottom of the file
 require app_path().'/helpers.php';
Or change your composer.json file and dump the autoloader.
 {
        "autoload": {
            "files": [
                "app/helpers.php"
            ]
        }
    }

$ composer dump-auto

*then you can write your functions in helpers.php and call them from anywhere
function myfunction($result){
     return $result;
    }

A: open root_folder/vendor/laravel/framework/src/Illuminate/Support/helpers.php
and you can add your function
if ( ! function_exists('display_messages'))
{
    function display_messages()
    {
        return ...
    }
}


text:
Q: Excel M query: Permission issue I am trying to access investing.com from excel 2016 using power query, I am getting a permission issue, is there a way to bypass it? It worked till yesterday, but now I am still getting this error even though I passed the cookie and header information in the URL. Below are the error and code
Error: [Permission Error] The credentials provided for the web source are invalid. Please update the credentials through a refresh or in the Data Source settings dialog to continue. Any guidance is much appreciated.
let
Source = ()=> Web.Contents("https://tvc6.investing.com/de339cb1628af015d591805dfffe9b13/1663439222/1/1/8/quotes?symbols=NSE%20%3ANSEI",[Headers=[#"accept-encoding"="gzip, deflate",#"cookie"="jLeqXJArEhTZVUQpwiP1gSPVlhn19b3fsB7uRcSUbyg-1666154846-0-AR2gelOI/3ZaH0SKRFuxhsgOGr/SOXpnbQ7e90mYM2iDmpTf8XcvvIB/FvGtgkB50nccnbWB1rFawcO37vJpSBU=",#"accept-language"="en-US,en;q=0.9",#"user-agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36 Edg/106.0.1370.47"]])
in
    Source


text:
Q: PHP/Array : Can't get array value from multi-dimensional This is OOP file uploader from https://github.com/CreativeDream/php-uploader. I have an array output like this,
Array
(
    [files] => Array
        (
            [0] => news/idENPYygDf.png
        )

    [metas] => Array
        (
            [0] => Array
                (
                    [date] => Tue, 21 Feb 2017 03:55:27 +0100
                    [extension] => png
                    [file] => news/idENPYygDf.png
                    [name] => idENPYygDf.png // Can't get this Name
                    [old_name] => lobat.png
                    [replaced] =>
                    [size] => 313342
                    [size2] => 306.00 KB
                    [type] => Array
                        (
                            [0] => image
                            [1] => png
                        )

                )

        )

)

I'm trying to get the name but seems not working is this correct? I got an error says Notice: Undefined index: name
if($data['isComplete']){
     $files = $data['data']['metas']['name'];
     echo'<pre>';
     print_r($files);
     echo'</pre>';

}

A: The tag 'name' is inside a position in the 'metas' array, so I'd try with
$data['data']['metas'][0]['name'];

or with
$data['metas'][0]['name'];

Hope it helps!


text:
Q: Splice function php I can't understand how the splice function is working.
If I have these two arrays, I want to replace the array after an offset
Let's say I want to replace after the '2'
$t=array(1,2,3,4,5,6);
$t2=array(0,0);
What should I do to get [1,2,0,0]
I tried this, but obviously not working array_splice($t,2,0,$t2)
Thanks.

A: If we check the PHP documentation, We can see that your offset is wrong.
Right now, your third parameter is 0, meaning that amount of items we need to replace is 0.
This will do the trick:
array_splice($t, 2, count($t), $t2);

You can try it out here where it gives the following result:

array(4) {   [0]=>   int(1)   1=>   int(2)   2=>   int(0)   [3]=>
  int(0) }

Bare in mind that when executing array_splice, two different results are available.

*

*The return value of array_splice, which returns an array consisting of the extracted elements. (In this case, it would return 3, 4, 5, 6 because those are the elements that were removed)

*Since we pass the array by reference, the array itself will contain the result you are looking for.


text:
Q: What's the best way to create a generic serializer which is able to serialize all the subclasses of the base model in Django Rest Framework? I'm currently working on a notification system which is going to deliver many different types of notifications through an API.
I have a base notification class called BaseNotification. Here is the code:
class BaseNotification(models.Model):
    message = models.CharField(max_length=500)
    seen = models.BooleanField(default=True)

    class Meta:
        abstract = True

And I want to subclass this model to create different variations of notifications:
class InvitationNotification(BaseNotification):
    invited_user = models.ForeignKey(User, on_delete=models.CASCADE)
    campagin = models.ForeignKey(Campagin, on_delete=models.CASCADE)
    # ... the rest of specific fields

class ChatMessageNotification(BaseNotification):
    contact = models.ForeignKey(User, on_delete=models.CASCADE)
    chat_room = models.ForeignKey(SomeSortOfChatRoomWhichIsNotImplementedYet, on_delete=models.CASCADE)
    # ... the rest of specific fields

As you can see, each of those variations, has some meta-data associated with it. The front-end developer would be able to create user interactions using these meta data (for example, in the case of a chat message, the front-end developer would redirect the user to the chat room)
I want to list all of these notifications through one unified API. For that, I need a serializer to serialize the objects as json but I don't want to have a sperate serializer for each. Ideally I want to have a generalized serializer which is capable of serializing all kinds of notifications and generates different json output depending on the type of the notification object passed in. (It might use other serializers under the hood).
Maybe I'm on the wrong track but the end goal is to deliver notifications and all their meta-data through one unified API.
I really need your suggestions and help. Thank you all in advance.

A: I finally figured it out by myself. My end goal was to provide some metadata for the front-end developer so that he can implement user interactions based on the type of the notification.
I simply solved the problem with a JSONField. That works just fine and that was the only thing I needed.
models.py
class Notification(models.Model):
    NEW_MEMBER_JOINED = 'NEW_MEMBER_JOINED'
    INVITATION = 'INVITATION'
    TEXT = 'TEXT'
    NEW_POST_CREATED = 'NEW_POST_CREATED'
    NEW_MESSAGE = 'NEW_MESSAGE'
    NEW_CAMPAIGN_CONTENT = 'NEW_CAMPAIGN_CONTENT'
    NEW_COMMENT = 'NEW_COMMENT'

    target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='notifications')
    text = models.CharField(max_length=300)
    type = models.CharField(max_length=255)
    date_created = models.DateTimeField(auto_now_add=True)
    seen = models.BooleanField(default=False)
    metadata = models.JSONField(null=True, blank=True)

    def __str__(self) -> str:
        return f"[{self.type}] {self.text}"

serializers.py
class NotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notification
        fields = '__all__'
        read_only_fields = [
            'text', 'type', 'metadata', 'date_created', 'seen'
        ]

In my case, this solution works the best.


text:
Q: Working with OpenLDAP 2.4 LDIF config backend In OpenLDAP 2.4, the configuration has been moved into an LDIF backend called cn=config. The OpenLDAP documentation says "you should never edit any of the LDIF files directly. Configuration changes should be performed via LDAP operations..." but does not give details any further details.
There's lots of conflicting information and to make matters worse, distros, such as Redhat Linux and Ubuntu, have specific configuration.

A: There are two ways to edit the cn=config date: directly and indirectly. Indirect uses normal ldap tools, such as ldapmodify and ldapsearch, which provides the simplest and most logical approach. HOWEVER, many distros use SASL to restrict access to just the root user on the local box. Assuming, you have a preconfigured instance, you can easily change this:
Enabling external access to cn=config

*

*sudo -i / su -

*Create a new password:
slappasswd

*Copy result, including "{SSHA}"

*Prepare auth.ldif. Replace olcRootPW with your password hash from last command
dn: olcDatabase={0}config,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=admin,cn=config
-
replace: olcRootPW
olcRootPW: {SSHA}jCMTRlz/iT4cw3CZno5z2PtCkJQbKrqK

*Import LDIF:
ldapmodify -Y EXTERNAL -H ldapi:/// -f auth.ldif

*You may now connect externally (assuming you have network access), using any LDAP client. E.g.
ldapsearch -b cn=config -D cn=admin,cn=config -H ldap://myldapserver -W

*Configure SSL ASAP!

Direct Mode
In direct mode, you can edit the cn=config database (and any other database), even if slapd is down. This is through the use of slapadd and slapcat tools. You must pass the database suffix. For example:
slapcat -b cn=config

IMHO, direct mode is best used when you know the exact LDIF you need to apply. I rarely do, so I tend to use normal LDAP tools to add, replace, and delete configuration on the fly.


text:
Q: Get selected value from drop down which is populated from a database I want to get the selected SystemID from my drop down menu which is populated by a database. I have named the drop down"data3"
Drop down from database is all working, it is displaying all the SystemIDs from my table.
Code below:
<select id ="data3" style="position:relative; top:-70px; left: 3.6%;"
name="data3" class="btn btn-light btn-sm dropdown-toggle">
    <option value="SystemID">SystemID</option>
    <?php
        $sql = "SELECT DISTINCT SystemID FROM MyTable ORDER BY
        SystemID";
    $result = sqlsrv_query($conn, $sql);
    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
        echo "<option value=\"\">" . $row['SystemID'] . "</option>";
        }
    ?>
  </select>

How do I get the selected value from that drop down? I have tried doing
var data3=$("#data3").val();

But this returns nothing

A: Use the ternary operator to check if the value coming from the database match the one from the select and mark it as selected. Please note that you must have a list of all the values of the select/option statement to be able to compare.
$row['SystemID'] == $value?'selected':''
echo "<option value='".$row['SystemID'] ."' ". ($row['SystemID'] == $value?'selected':'') ."  >" .
        $row['SystemID'] .
     "</option>";


text:
Q: Powershell Python What happens when you type python in windows powershell? It shows me the python version but what can you do inside it since you can't really use it to display code you've written on an editor, right?

A: It starts the Python REPL (Read-Eval-Print-Loop) or Python in interactive Mode.


text:
Q: Special signs such as æøå always stands with lowercase even though forced by strtoupper I am collecting the following names from the database and using strtoupper to make them upper case:
ADFæRD

FORRETNINGSFORSTåELSE

INTERNT

KOMMUNIKATION

KOMPETENCEMåLING

KULTUR

LEDELSE

MOTIVATION

PRODUKTER

PSYKOLOGI

SALG & PERFORMANCE

SERVICE

SYSTEMER

As you can see every character works however the special characters like ÆØÅ is always lowercase.
Is there a way i can fix this?

A: Use mb_strtoupper, example :
$s='adfærd';
echo mb_strtoupper($s, 'UTF-8');

outputs

ADFÆRD

A: You are probably looking for mb_strtoupper

Returns str with all alphabetic characters converted to uppercase.
[...]
By contrast to strtoupper(), 'alphabetic' is determined by the Unicode
character properties. Thus the behaviour of this function is not
affected by locale settings and it can convert any characters that
have 'alphabetic' property, such as a-umlaut (ä).

Example:
$str ='adfærd';
echo mb_strtoupper($str , 'UTF-8');


text:
Q: SSD Boot disk error This is more just a general question about troubleshooting, as I think I know the answer already, but the behavior is a little odd so here goes...
I have two 60gb SSDs striped together (for more space, as its the system drive).  On bootup, I've been getting an error on one of the drives for months from the Intel Rapid Storage driver, but it always booted.  Recently, I moved the computer and while I am still getting the error, I now get a blue screen on startup.
What is curious to me is that Intel Rapid Storage driver loads up and sees the drives as striped, giving me an error on the one drive, but then it finds windows and attempts to start up.
I used a live CD to run Gparted and it sees both of the drives.  One drive is gets an "invalid argument during seek for read on /dev/sda" on Gparted startup, followed by the backup GPT table is corrupt but the primary appears OK so that will be used.  Once GParted has started up, that drive is unallocated, while dev/sdb's filesystem is "unknown", with 1mb unallocated.
But since I also have a Microsoft keyboard that had been doing some weird stuff, like just stopping working, I thought I should post just in case that might actually be the problem.  These are my first two SSDs so I am not quite sure how it looks when they fail.  It just seems weird that Windows would attempt to start up, as it seems like the boot instructions would be spread across the two drives.
Thanks in advance!

A: So, just in case anyone comes across this looking for help-
In the end, I used the Intel RSTe dialog at bootup to delete my raid, and then re-striped the SSDs.  I ended up with 5gb less of space, so I am going to assume that the one drive with the error has some bad blocks and the RAID driver just ignored them.  Once I re-striped them, I get no errors and was able to re-install my OS.  Luckily they are SSDs so the install was quick, and gave me an opportunity to move around my user profile and default install directories in Windows.


text:
Q: 16.04 docker-engine install fails $ apt-get install docker-engine
Depends: llibvdevmapper1.02.1 (>=2:1.02.97) but 2:1.02.90-2.2+deb8ul is to be installed
Depends: libltdl7 (>=2.4.6) but 2.4.2-1.11_b1 is to be installed
E:Unable to correct problems, you have held broken packages.

This is a new install, how do I fix this?

A: Manually reinstall or update the dependencies.
To update or install:
apt-get install llibvdevmapper1.02.1
apt-get install libltdl7

To remove then reinstall:
apt-get remove llibvdevmapper1.02.1
apt-get remove libltdl7

apt-get install llibvdevmapper1.02.1
apt-get install libltdl7


text:
Q: Trying to merge 2 files but ignore new lines I'm trying to merge 2 lists together: Only copy over common differences, but ignore new lines. Might be easier to explain by this:
a.txt                 b.txt
abc                   123
def                   abc.^$234,~12
ghi                   abcdd
jkl                   asdf
mnn                   ghi.^$321,~11
opq                   jkl
                      mnn^$qws
                      zxy

Becomes:
output.txt:
abc.^$234,~12
def
ghi.^$321,~11
jkl
mnn^$qws
opq

Trying to combine to lists, copy common lines while dropping new lines.

A: This might work for you (GNU sed):
sed -nE '1{x;s/.*/cat file2/e;x};G;s/^([^\n]+)(\n.*)*\n(\1\>[^\n]*).*/\3/;P' file1

Slurp file2 into the hold space and then append it to each line in file1.
If the word in file1 matches a word in file2, print the contents of that line in file2. Otherwise, print the current line in file1.

A: you could try the diff and patch commands, they might help you.
diff -u old_file new_file > change.diff
patch new_file < change.diff

A: Using awk:
$ awk '
NR==FNR {
    a[$0]
    next
}
{
    for(i in a)
        if(index(i,$0)) {
            print i
            next
        }
    print
}' b a

Output:
abc.^$234,~12
def
ghi.^$321,~11
jkl
mnn^$qws
opq

A: You're requirements aren't at all clear but this will produce the expected output you posted given the sample input you posted so it may be what you're looking for:
$ awk -F'[^[:alnum:]]' 'NR==FNR{a[$1]=$0; next} {print ($1 in a ? a[$1] : $1)}' b.txt a.txt
abc.^$234,~12
def
ghi.^$321,~11
jkl
mnn^$qws
opq


text:
Q: 2 div inline but with centered h1, like if second div wasn't there i have a complex issue. I hope u understand my problem.
There is the fiddle: http://jsfiddle.net/User1010/ZNGsh/110/

    TITLE

       Line 1

    Line 2

What i actually want is the H1 - Title to be centered like in the nav div.
But the second div (header-e2) needs to be floating next to the first div(header-e1) and move down if the width get's too low.
Is this even possible?

A: You can do that with flexbox
As your question is  quite unclear about:

But the second div (header-e2) needs to be floating next to the first
  div(header-e1) and move down if the width get's too low.-

I'll give you a few examples

*

*H2 floating next to H1 but close to the side of the page not to H1

body {
  margin: 0
}

#header {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  width:100%;
  background: lightblue
}

#header-e1 {
  margin: auto
}

#header div {
  border: red solid
}

      TITLE

      Line 1

 Line 2

*H2 floating next to H1 and next to H1

body {
  margin: 0
}

#header {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width:100%;
  background: lightblue
}

#header div {
  border: red solid
}

      TITLE

      Line 1

 Line 2


text:
Q: How to bound a campus map in Google Maps? I'm new in this programming language so I kinda copy and paste the codes found in the net and then I've found and tried using these codes in bounding a certain area and it works:
private GoogleMap mMap;
// Create a LatLngBounds that includes the city of Adelaide in Australia.
private LatLngBounds ADELAIDE = new LatLngBounds(
new LatLng(-35.0, 138.58), new LatLng(-34.9, 138.61));
// Constrain the camera target to the Adelaide bounds.
mMap.setLatLngBoundsForCameraTarget(ADELAIDE);

But when I changed it using my campus coordinates into like this:
private LatLngBounds CPUBounds = new LatLngBounds(
new LatLng(10.732581, 122.548413), new LatLng(10.730052, 122.549958));

My app suddenly stop working. What should I do?

A: Try to paste the Logcat to review the Error
From If you want to show the specific position try the following code
To Move Camera Position Over a Specific Region Use this ,
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,
                           zoomWidth,
                           zoomHeight,
                           zoomPadding));

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(10.732581, 122.548413),
                           zoomHeight));

If u want to add a marker Over region use
mMap.addMarker(new MarkerOptions()
                       .position(new LatLng(10.732581, 122.548413))
                       .title("campus name"));

To Disable the Dragging Use
mMap.getUiSettings().setScrollGesturesEnabled(false);
but it doesn't disable map zoom by touch on map. for that use Following Code
googleMap.getUiSettings().setZoomGesturesEnabled(false);


text:
Q: How to extract the value of each first item in Pug array I'm trying to get the first item in this array using Pug.
- val newx = {'O1_Carmine':'#E54A34', 'O2_Lipstick':'#D04735'}

each val,index in newx
    .span2(style={ background: val, color: 'black', height: '3em'} class='pad1')
        p index[0]

This renders

index[0]

index[0]

but I'm trying to get;

O1_Carmine

O2_Lipstick

Any tips?

A: Try this
each val,index in newx
    .span2(style={ background: val, color: 'black', height: '3em'} class='pad1')
        p= index

Note the = after the p, and no need for [0] (and that first line should read - var, not - val)


text:
Q: How to stop the days in appending after I select the month To make the issue short. I have 3 dropdowns for picking a date. The date picker display the range of the days within the month if it's only 29 or 31 days. It's working fine now except that when I changed in different month the value in my days is repeating.
For example I choose February. The days that is display is 28 days.
     Then I changed to March. The days displays as 31 days. The problem is they are only combining so the value in my day dropdown become many. How can I fixed this, any help?

function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}
function onMonthChange(){
    var year = document.getElementById("yeardialog").value;
    var month = document.getElementById("monthdialog").value;

    var endOfTheMonth = daysInMonth(month, year);
    console.log(endOfTheMonth);

    var select = document.getElementById('datedialog');
    for (var i = 0; i < endOfTheMonth; i++) {
        select.options[select.options.length] = new Option(i + 1, i);
    }
}
<select id="yeardialog" name="yeardialog">
    <option value="">--</option>
    <option value="1990">1990</option>
    <option value="1991">1991</option>
    <option value="1992">1992</option>
</select>

<select id="monthdialog" onchange="onMonthChange()">
    <option value="">--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select id="datedialog">
    <option></option>
</select>

A: var select = document.getElementById('datedialog');
select.innerHTML = ""; // clear the select.
for (var i = 0; i < endOfTheMonth; i++) {
    select.options[select.options.length] = new Option(i + 1, i);
}

The solution is plain and simple. Delete the contents of the select before populating them.
Solution inside the snippet:

function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}
function onMonthChange(){
    var year = document.getElementById("yeardialog").value;
    var month = document.getElementById("monthdialog").value;

    var endOfTheMonth = daysInMonth(month, year);
    console.log(endOfTheMonth);

    var select = document.getElementById('datedialog');
    var selectedvalue = select.querySelector('option:checked');
    if (selectedvalue)
    {
      var store = selectedvalue.getAttribute("value");
    }
    select.innerHTML = "";
    for (var i = 0; i < endOfTheMonth; i++) {
        select.options[select.options.length] = new Option(i + 1, i);
    }
    var retrieved = select.querySelector("option[value='"+store+"']");
    if (retrieved)
    {
      retrieved.setAttribute("selected", "true");
    }
}
<select id="yeardialog" name="yeardialog">
    <option value="">--</option>
    <option value="1990">1990</option>
    <option value="1991">1991</option>
    <option value="1992">1992</option>
</select>

<select id="monthdialog" onchange="onMonthChange()">
    <option value="">--</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select id="datedialog">
    <option></option>
</select>

Updated question. Store the original value before deleting:
We look for the selected value using:
select.querySelector('option:checked');
Then we look if the value can be found in the new list. If so select the value. If not revert to 1. This happens when you select 31 and the month loaded only has 30 days.

A: I wouldn't modify the innerHTML, I prefer removing the nodes
var select = document.getElementById('datedialog');

while(select.hasChildNodes())select.removeChild(select.firstChild);// clear the select.
for (var i = 0; i < endOfTheMonth; i++) {
    select.options.add(new Option(i + 1, i));
}

A: Try this:

function onMonthChange(){
 var year = document.getElementById("yeardialog").value;
 var month = document.getElementById("monthdialog").value;

 var endOfTheMonth = daysInMonth(month, year);
 console.log(endOfTheMonth);

 var select = document.getElementById('datedialog');
 select.innerHTML = '';
 select.options[0] = new Option("Pick a date", 0);
 for (var i = 1; i < endOfTheMonth; i++) {
  select.options[select.options.length] = new Option(i + 1, i);
 }
}


text:
Q: Unexpected result for string comparison I cannot understand the following behavior:
WITH tests(min, val, max) AS (
    SELECT 'a', 'x', 'z' UNION ALL
    SELECT '',  'x', 'z' UNION ALL
    SELECT 'a', 'x', '~'
)
SELECT min, val, max, CASE WHEN val BETWEEN min AND max THEN 'PASS' ELSE 'FAIL' END AS result
FROM tests

Result:
| min | val | max | result |
|-----|-----|-----|--------|
| a   | x   | z   | PASS   |
|     | x   | z   | PASS   |
| a   | x   | ~   | FAIL   |

The character codes for x and ~ are 120 and 126 respectively. In every programming language I know 'x' < '~' is true. So what is with SQL?
I get same result on different RDBMS. On SQL Server the following collation is used:

Latin1-General, case-insensitive, accent-sensitive,
  kanatype-insensitive, width-insensitive

A: In my comment beneath your question I asked you what collation you were using.  You said "assume default", but there is no "default".  The "default" depends on how your database and server are setup.  I ran your experiment on my SQL Server and happened to get the same results you did, but that was merely a coincidence.
The SQL Server and database I ran the experiment on is using the SQL_Latin1_General_CP1_CI_AS collation.  Based on this fact, here is the ordering of characters:
http://collation-charts.org/mssql/mssql.0409.1252.Latin1_General_CI_AS.html
Notice that Tilde ~ comes before alphabetical characters which obviously includes x.

A: You need to apply a BINARY collation, or else SQL Server will use a (probably non-binary) order depending on the collation that is in use for your table or database.
Here is an example that works. Which exact binary collation you need, that is up to you to determine.
WITH tests(min, val, max) AS (
    SELECT 'a', 'x', 'z' UNION ALL
    SELECT '',  'x', 'z' UNION ALL
    SELECT 'a', 'x', '~'
)
SELECT
    min, val, max,
    CASE WHEN val COLLATE SQL_Latin1_General_CP437_BIN BETWEEN min AND max THEN 'PASS' ELSE 'FAIL' END AS result
FROM tests

Output:
min val max result
--- --- --- ------
 a   x   z  PASS
     x   z  PASS
 a   x   ~  PASS

A: Your behavior depends from the collation you use.
I've tried this:
select
case
    when 'x' < '~' then 'ok'
    else 'ko'
end

and Sql Server returns ko (with my default collation Latin1_General_CI_AS)
If I wirte as follow:
select
case
    when 'x' < '~' collate Latin1_General_BIN  then 'ok'
    else 'ko'
end

it works in according with ASC code


text:
Q: Как сделать аналогичный XMLHttpRequest fetch запрос? Подскажите в чём разница, половину вечера сижу смотрю...
На сервере (фреймворк Yii2) есть такой код.
 public function actionCreateImages()
    {

        \Yii::$app->response->format = Response::FORMAT_JSON;

        $images = new Images();
        $images->scenario = Images::SCENARIO_CREATE;
        $images->attributes = \Yii::$app->request->post();

        if($images->validate()){
            $images->save();
            return array('status'=>true, 'data'=>'images created successfully');
        } else {
            return array('status'=>false, 'data'=>$images->getErrors());
        }
    }

В PostMan запрос правильно обрабатывается

Код запроса из Postman
var data = new FormData();
data.append("name", "test");
data.append("file", "test");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://advanced/admin/api/images/create-images");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("Postman-Token", "9cf730e3-d78b-41a0-8c76-a0075fd5e714");

xhr.send(data);

Я использую на ноде fetch запрос следующего вида.
async function post (obj) {
  var data = new FormData()
  data.append('name', 'test')
  data.append('file', 'test')
  fetch(`http://advanced/admin/api/images/create-images`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'cache-control': 'no-cache'
    },
    body: data
  }).then(function (response) {
    return response.json()
  }).then(function (json) {
    console.log('################### response ###################')
    if (json.status === 404) {
      console.log('~~~~~~~~~~ 404 ~~~~~~~~~~', json)
      return json
    } else {
      console.log('~~~~~~~~~~ object ~~~~~~~~~~', json)
      return json
    }
  }).catch(function (error) {
    console.assert(false, '~~~~~~~~~~ error ~~~~~~~~~~', error)
  })
}

У меня в response выдаёт status false

В чём отличие от POST запроса из PostMan ?
Почему у меня не получается передать данные ?


text:
Q: How to pass my User object data to ASPX page? I'm just trying to do something really simple here in ASP.net (ASPX), and it doesn't seem to be working.
I have the following class/Model, View and Controller:
Users.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ASPWebsite.Models
{
    public class Users
    {
        private string firstName;
        private string lastName;

        public Users(string firstName, string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public string GetFirstName()
        {
            return this.firstName;
        }

        public string GetLastName()
        {
            return this.lastName;
        }
    }
}

Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ASPWebsite.Models.Users>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Index

<%Model.GetFirstName();%>

</asp:Content>

HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ASPWebsite.Models;

namespace ASPWebsite.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            var user = new Users("foo", "bar");

            return View(user);
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

As you can see, I have created a User with the name foo bar and passed it to the view, but when I run it, it doesn't display the name. What is wrong with it??

A: Try
<%: Model.GetFirstName() %>


text:
Q: Conflict Error when obtaining attributes in FIWARE Orion Context Broker I cannot get any entity attribute when I have context provider registered. I constantly get the same 409 conflict error. How can I  prevent having two objects with the same id and merge them into one?

SETUP
I have whole Orion Context Broker all setup and running after following this commands:
docker pull mongo:3.6
docker pull fiware/orion:2.0.0
docker network create fiware_default

docker run -d --name=mongo-db --network=fiware_default \
  --expose=27017 mongo:3.6 --bind_ip_all --smallfiles
docker run -d --name fiware-orion -h orion --network=fiware_default \
  -p 1026:1026  fiware/orion:2.0.0 -dbhost mongo-db

ENTITIES
I have one Car entity added with curl:
 curl -iX POST \
  'http://localhost:1026/v2/entities' \
  -H 'Content-Type: application/json' \
  -d '
{
    "id": "urn:ngsi-ld:Car:001",
    "type": "Car",
    "brandName": {
        "type": "Property",
        "value": "Mercedes"
    },
    "location": {
        "type": "geo:json",
        "value": {
             "type": "Point",
             "coordinates": [0.00, 0.00]
        }
    },
    "name": {
        "type": "Text",
        "value": "MyCar"
    }
}'

Moreover, I also registered my Context Provider:
 curl -iX POST \
  'http://localhost:1026/v2/registrations' \
  -H 'Content-Type: application/json' \
  -d '
{
  "description": "Temperature",
  "dataProvided": {
    "entities": [
      {
        "id": "urn:ngsi-ld:Car:001",
        "type": "Car"
      }
    ],
    "attrs": [
      "temperature"
    ]
  },
  "provider": {
    "http": {
      "url": "http://192.168.xxx.xxx:8080/api/cars/temperature/1"
    },
     "legacyForwarding": true
  }
}'

CONTEXT PROVIDER
I exposed locally my Context Provider (exposed by my SpringBoot application written in Java 10) at http://192.168.xxx.xxx:8080/api/cars/temperature/1/queryContext. The JSON data (returned in html body) is in NSGI v1 format and looks like that:
   {
  "contextResponses": [
    {
      "contextElement": {
        "attributes": [
          {
            "name": "temperature",
            "type": "float",
            "value": "-10"
          }
        ],
        "id": "urn:nsgi-ld:Car:001",
        "isPattern": "false",
        "type": "Car"
      },
      "statusCode": {
        "code": "200",
        "reasonPhrase": "OK"
      }
    }
  ]
}

PROBLEM
When I make this query:
curl GET 'http://localhost:1026/v2/entities?type=Car&options=keyValues'

I receive list of objects with the same ids:
[{"id":"urn:ngsi-ld:Car:001","type":"Car","brandName":"Mercedes","location":,"name":"MyCar"},{"id":"urn:nsgi-ld:Car:001","type":"Car","temperature":"-10"}]

1) When I try to get location attribute:
curl -iX GET 'http://localhost:1026/v2/entities/urn:ngsi-ld:Car:001/attrs/location/value'

I get response:
HTTP/1.1 409 Conflict
Connection: Keep-Alive
Content-Length: 98
Content-Type: application/json
Fiware-Correlator: 509119fa-fd27-11e8-922c-0242ac130003
Date: Tue, 11 Dec 2018 09:29:53 GMT

 {
        "error": "TooManyResults",
        "description": "More than one matching entity. Please refine your query"
    }

2) I noticed that I can remove an entity by id:
curl -iX DELETE 'http://localhost:1026/v2/entities/urn:ngsi-ld:Car:001'

3) And then, I can get temperature for not existing object:
curl -iX GET 'http://localhost:1026/v2/entities/urn:ngsi-ld:Car:001/attrs/temperature/value'

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 5
Content-Type: text/plain
Fiware-Correlator: 0de19b36-fd2a-11e8-8abe-0242ac130003
Date: Tue, 11 Dec 2018 09:49:29 GMT

"-10"

I would like to be able to get an attribute (the location) and the attribute from the context provider (temperature) for the entity (urn:ngsi-ld:Car:001), but it looks like this entity has been somehow splitted into two entities with the same id (and the same type).
What should I do to prevent this id conflict? How to prevent having two objects with the same id when registering context provider?


text:
Q: Syntax error, malformed JSON SLIMCD When request for Transaction using Slimcd. I have issue "Syntax error, malformed JSON ". I have searched through google nothing found useful.
// Create a ProcessTransaction Request class
$request = new Transact_ProcessTransactionRequest() ;
$request->username = '1032';
$request->password = '289075';
$request->clientid = '1032';
$request->siteid = 228226448 ;
$request->priceid = 74 ;
$request->transtype = 'LOAD';
$request->amount = '0.00';
$request->cardnumber = '4111111111111111';
$request->expmonth = '12';
$request->expyear = '49';
$request->product = 'MyPHP';
$request->ver = '1.0';
$request->key = 'SVD-072-5QQ6-5K58';
$reply = $SlimCD->Transact_ProcessTransaction($request);
print_r(json_encode($reply)) ;

Response:
{"response":"Error","responsecode":"2","description":" - Syntax error, malformed JSON","responseurl":"https:\/\/trans.slimcd.com\/soft\/json\/jsonpayment.asp","datablock":""}


text:
Q: Writing datas to memobox from .txt file using Lazarus freepascal? I've got a project at schools which requires to write datas from a .txt file to a "memobox" in Lazarus freepascal.
There are datas in order like this.
Budapest tomato 23
Dublin tv 45
Rosslare projector 43
etc.
I have to read these datas from a .txt file and then write them into a memobox in Lazarus freepascal.
If I am not mistaken I have already copyed the datas from the .txt file but I have no idea how to write them.
I've already written this code:
type
cityname:integer;
product:string;
quantity:integer;
var
Form1: TForm1;
ceg:array[1..5] of rektip;
db:integer;

implementation
procedure TForm1.Button1Click(Sender: TObject);
var f:textfile; i:integer; a:char;
begin
assignfile(f,'termek.txt');
reset(f);
readln(f,db);
While not eof(f) do
begin
  readln(f,ceg[i].varosnev,a,ceg[i].termek,a,ceg[i].darabszam);
end;
db:=1;
closefile(f);
end;

procedure TForm1.Button2Click(Sender: TObject);
var i:integer;
begin
For i:=1 to db do
Memo1.lines.add(ceg[i].varosnev,ceg[i].termek,IntToStr(ceg[i].darabszam));
end;
end;

I would like to know how to fix it.

A: The code you posted is incomplete, so I assume:
type
  rektip = record
    varosnev: string;
    termek: string;
    darabszam: Integer;
  end;

There is a lot wrong with your approach:
readln(f,db);
While not eof(f) do
begin
  readln(f,ceg[i].varosnev,a,ceg[i].termek,a,ceg[i].darabszam);
end;
db:=1;
closefile(f);
end;

You are not initializing nor updating i, so you are reading all data into the same record, and you don't even know which one (i could be 100 and you'd be writing the data to somewhere unknown -- there is no ceg[100]). That results in undefined behaviour (and that can be a crash too).
Do something like:
var
  ceg: array of rektip;

...

begin
  AssignFile(f, 'termek.txt');
  Reset(f);
  Readln(f, db);
  if db = 0 then
    Exit;
  SetLength(ceg, db);
  i := 0;
  while not eof(f) do
  begin
    Readln(f, ceg[i].varosnev, ceg[i].termek, ceg[i].darabszam);
    Inc(i);
    if i > High(ceg) then
      Break;
  end;
  SetLength(ceg, i); // remove any empty slots.
  CloseFile(f);
end;

Now you can put them into the TMemo:
for i := Low(ceg) to High(ceg) do
begin
  Memo1.Lines.Add(Format('%s %s %d', [ceg[i].varosnev, ceg[i].termek, ceg[i].darabszam]));
end;

Note that the code above, reading from the file, assumes the file looks like:
3
Budapest tomato 23
Dublin tv 45
Rosslare projector 43

i.e. each "record" is on a line of its own and the first line contains the number of records.


text:
Q: How can I change the localSID for a SAMBA Server? I am trying to change the localSID for a SAMBA server, however I am unable to. I have tried the command "net setlocalsid" to no avail. To troubleshoot I have also stopped the smbd and nmbd services, but this did not help. Any help would be great!
root@TheWiggle:~# net getlocalsid
SID for domain THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000

root@TheWiggle:~# net getdomainsid
SID for local machine THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000
SID for domain THISDOMAIN is: S-1-5-21-748580849-194208185-3916830000

root@TheWiggle:~# net setlocalsid S-1-5-21-33300351-1172445578-3061011111

root@TheWiggle:~# net getlocalsid
SID for domain THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000

root@TheWiggle:~# net getdomainsid
SID for local machine THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000
SID for domain THISDOMAIN is: S-1-5-21-748580849-194208185-3916830000

root@TheWiggle:~# net setdomainsid S-1-5-21-33300351-1172445578-3061011111

root@TheWiggle:~# net getdomainsid
SID for local machine THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000
SID for domain THISDOMAIN is: S-1-5-21-33300351-1172445578-3061011111

root@TheWiggle:~# net setlocalsid S-1-5-21-33300351-1172445578-3061011111

root@TheWiggle:~# net getlocalsid
SID for domain THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000

root@TheWiggle:~# service smbd stop && service nmbd stop
smbd stop/waiting
nmbd stop/waiting

root@TheWiggle:~# net setlocalsid S-1-5-21-33300351-1172445578-3061011111

root@TheWiggle:~# net getlocalsid
SID for domain THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000

root@TheWiggle:~# net setdomainsid S-1-5-21-33300351-1172445578-3061011111

root@TheWiggle:~# net getdomainsid
SID for local machine THEWIGGLE is: S-1-5-21-748580849-194208185-3916830000
SID for domain THISDOMAIN is: S-1-5-21-33300351-1172445578-3061011111

A: I was able to change the sid once I put the server in a backup domain controller mode. Since this server does not need to be an actual domain controller this mode was fine.
server role = classic backup domain controller

Hopefully this helps anyone with this issue!!!

A: I had the same issue and before changing the netlocalsid of the HOST, I had to change the sambaSID of the sambaDomainName=HOST in the LDAP.
After you changed the sambaSID with the value you want to change, the command # net setlocalsid
works well.


text:
Q: Determining where in x-z plane, $f(z,t,x)$ is negative for all values of $0I want to mark regions in $z - x$ plane in which, a know function,$f(x,z,t)$, is negative for all values of $0<t<\pi$.
How can I do that? I don't want to plot $f$ in $3D$. Could anyone help me?
The function f(t,x,z) is as below:
    f[x_ , z_ , t_ ] :=Re[0.125 (-21.2 +
 Re[2 z Cos[2 t] -
   2 z Cos[2 t]^2 + (2. E^(-I t) (E^(2 I t) (-8. - 3. x) z +
        E^(12 I t) (-8. - 3. x) z + x z + E^(14 I t) x z +
        E^(6 I t) (105.6 + 79.2 x - 8. z - 1. x z) +
        E^(8 I t) (105.6 + 79.2 x - 8. z - 1. x z) +
        E^(4 I t) (-79.2 x + 16. z + 3. x z) +
        E^(10 I t) (-79.2 x + 16. z + 3. x z)) ((28.4 - 5. x +
           0.25 x^2 + (-24.4 + 8. x - 0.125 x^2) Cos[
             2 t] + (-3. - 0.25 x) x Cos[4 t] +
           0.125 x^2 Cos[6 t])^2)^(1/4))/(E^(2 I t) (-24. -
         2. x) x + E^(10 I t) (-24. - 2. x) x + x^2 +
      E^(12 I t) x^2 + E^(4 I t) (-195.2 + 64. x - 1. x^2) +
      E^(8 I t) (-195.2 + 64. x - 1. x^2) +
      E^(6 I t) (454.4 - 80. x + 4. x^2))])]

By the use of solution, I want to do the same thing when there are two functions which should be negative for all values of t:
g[x_ , z_ , t_ ] :=Re[0.125 (-21.2 +
     Re[2 z Cos[2 t] -
       2 z Cos[2 t]^2 + 2. E^(-I t) (E^(2 I t) (-8. - 3. x) z +
            E^(12 I t) (-8. - 3. x) z + x z + E^(14 I t) x z +
            E^(6 I t) (105.6 + 79.2 x - 8. z - 1. x z))]

max[x_?NumericQ, z_?NumericQ] :=NMaximize[{f[x, z, t], 0 <= t <= Pi}, t,Reals, AccuracyGoal -> 5,PrecisionGoal -> 5][[1]]

max[x_?NumericQ, z_?NumericQ] :=NMaximize[{g[x, z, t], 0 <= t <= Pi}, t,Reals, AccuracyGoal -> 5,PrecisionGoal -> 5][[1]]

RegionPlot[ max[x, z] <= 0 , {x, -10, 10 }, {z, -10, 10},"NumericalFunction"-> False ]

A: With
f[x_ , z_ , t_ ] :=Re[0.125 (-21.2 +
 Re[2 z Cos[2 t] -
   2 z Cos[2 t]^2 + (2. E^(-I t) (E^(2 I t) (-8. - 3. x) z +
        E^(12 I t) (-8. - 3. x) z + x z + E^(14 I t) x z +
        E^(6 I t) (105.6 + 79.2 x - 8. z - 1. x z) +
        E^(8 I t) (105.6 + 79.2 x - 8. z - 1. x z) +
        E^(4 I t) (-79.2 x + 16. z + 3. x z) +
        E^(10 I t) (-79.2 x + 16. z + 3. x z)) ((28.4 - 5. x +
           0.25 x^2 + (-24.4 + 8. x - 0.125 x^2) Cos[
             2 t] + (-3. - 0.25 x) x Cos[4 t] +
           0.125 x^2 Cos[6 t])^2)^(1/4))/(E^(2 I t) (-24. -
         2. x) x + E^(10 I t) (-24. - 2. x) x + x^2 +
      E^(12 I t) x^2 + E^(4 I t) (-195.2 + 64. x - 1. x^2) +
      E^(8 I t) (-195.2 + 64. x - 1. x^2) +
      E^(6 I t) (454.4 - 80. x + 4. x^2))])]

it is possible to define the function
max[x_?NumericQ, z_?NumericQ] :=NMaximize[{f[x, z, t], 0 <= t <= Pi}, t,Reals, AccuracyGoal -> 5,PrecisionGoal -> 5][[1]]

which gives the maximum of f for given x,z.
Using RegionPlot the region f<0 can be calculated:
RegionPlot[ max[x, z] <= 0 , {x, -10, 10 }, {z, -10, 10},"NumericalFunction"-> False ]


text:
Q: How to get value of a Volley XML response? I write a Volley StringRequest and get a XML response. How to get the value of "CurrentVersion" for example ?
My XML response as below :
<string xmlns="http://tempuri.org/">
    <?xml version="1.0"?> <Result xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <IsSuccessed>true</IsSuccessed> 1 <Message>{ "CurrentVersion": "108.12.16.1", "ForceUpdate": false, "EnableO365": true, "Description": "" }</Message> </Result>
    </string>

My Volley StringRequest as below :
String HttpUrl ="https://m.fbl.com.tw:1114/Fubon/pss/FubonWebservice.asmx/GetActiveAppVersionEx?appCode=fubonmapp2&platformName=AndroidPad";
            RequestQueue mQueue = Volley.newRequestQueue(MainActivity.this);

           StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {

    Log.i("TAG", response.toString())

                        }

                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                    Log.i("TAG", error.toString());

                }
            });

            mQueue.add(stringRequest);

        }

A: You can use StringRequest to get your response and parse it in public void onResponse(String response).

A: Create StringRequest having response type String. Once you will get callback in public void onResponse(String response) method, you can parse sting XML data using XML parser library and you XML convert into Model class.


text:
Q: SwiftUI: Is there any solution to clear value in DatePicker? I am finding a solution to clear value of a DatePicker in SwiftUI. I tried and it's not success. Please check:
struct EditProfileView: View {

    @State var birthDate = Date()

    var body: some View {
        Form {
            Section (header: Text("Birth day")) {
                DatePicker(selection: $birthDate, in: ...Date(), displayedComponents: .date) {
                    Text("Select a date")
                }
                HStack {
                    Text("You were born in \(birthDate, formatter: dateFormatter)")
                    .font(.subheadline)
                    .foregroundColor(Color.gray)
                    Spacer()
                    Button(action: {
                        self.clearDate()
                    }) {
                        Text("Clear")
                    }
                }
            }
        }
    }

    func clearDate () {
        self.$birthDate = nil
    }

}

This line of code is not work:
self.$birthDate = nil
I think because of Date type cant not leave nil but I cant find a solution to handle with it

A: Set the birthDate (not $birthDate) to the following, which will default back to the current date:
self.birthDate = Date()

A: You can create a Binding from Date?
  struct EditProfileView: View {

            @State var birthDate : Date?

            var dateFormatter: DateFormatter {
                           let formatter = DateFormatter()
                           formatter.dateStyle = .short
                           return formatter
                         }

            var body: some View {
                Form {
                    Section (header: Text("Birth day")) {
                        DatePicker(selection: Binding<Date>(get: { () -> Date in
                            self.birthDate ?? Date()
                        }, set: { (Date) in
                            self.birthDate = Date
                        }), in: ...Date(), displayedComponents: .date) {
                            Text("Select a date")
                        }
                        HStack {
                            Text( "You were born in :") + (birthDate == nil ? Text("") :  Text("\(birthDate!, formatter: dateFormatter)"))
                            .font(.subheadline)
                            .foregroundColor(Color.gray)
                            Spacer()
                            Button(action: {
                                self.clearDate()
                            }) {
                                Text("Clear")
                            }
                        }
                    }
                }
            }

            func clearDate () {
                self.birthDate = nil
            }

          }


text:
Q: Setting up a UITableViewCell subclass in code I am reading the apple docs on setting up custom subclasses of UITableViewCell - Docs
In this example I need to setup a custom cell which does not have a NIB/storyboard file. The apple docs provide an example of using a predefined style and configuring that but not creating a completely custom layout.

*

*How should the cell be called in.. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath ?

I am looking to have a completely custom layout so is this correct? As the cell is being called initWithStyle...?
MESLeftMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if(cell == nil)  {
    cell = [[MESLeftMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}

*

*In the custom cell subclass how/where should I implement the setup of the views within the contentView?
Which method is called for the init, would it be initWithStyle as above? If so, can I simply create the cell outlets in there once only?

Then in the cellForRowAtIndexPath can I access the outlets as i.e. cell.MainLabel.text ... ?

A: This is how I have been shown to set up my Collection View Cells in their custom class. I know you are using a tableview but this is threw me for a while so decided to add here. Hopefully it helps you.
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    [self commonInit];
}
return self;
}

- (id)initWithCoder:(NSCoder *)encoder
{
    self = [super initWithCoder:encoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    // set up your instance
}

To access the outlets of that cell I just add outlets to the header file of the custom class  and you can easily access them.

A: As of iOS 6, you no longer need to check whether the dequeued cell is nil.
What you would do is as follows:
In the viewDidLoad method of the view controller containing the table view you could say
[self.tableView registerClass:[MyCellClass class] forCellReuseIdentifier:MyCellIdentifier];

This results in your dequeueReusablecellWithIdentifier call to never return nil. In essence, in the background, initWithStyle is called. So you would set your stuff up when overriding that function.