text:
Q: php file_get_contents / header server difference I am accessing spreadsheets which are not located inside in the web directory and serving them to the browser. I am using the following code to do this:
$filePath = WEBSITE_ROOT_PATH.'/../where_the_spreadsheets_are/file_name.xls';

if(file_exists($filePath)){
    $contents = file_get_contents($filePath);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment;filename=file_name.xls");
    header("Content-Transfer-Encoding: binary");
    echo $contents;
}

This code works correctly on 20+ separate servers, but not on one. On the one that fails Excel says that the spreadsheet is corrupt.
The server that fails has a mirror server, so the same file path and file name exists, and on this server the spreadsheet is ok.
It's a Win server 2007 running WAMP. All the rest are also Win Servers running WAMP.
Does anyone know the reason for this?


text:
Q: wordpress custom fields multiple data i need help with wordpress custom fields currently i store date in one custom field called audio using the "," and "$" example:
name, link $ name, link $ etc
i have managed to use the data and split the data using php in my theme i.e the playlist.
i just need help in creating a custom metabox with 2 text fields that can be duplicated by clicking on adding more and two more fields would show. i only want to use only one custom field to store the data.
thanks

A: You can store an array in a custom field; WordPress serializes it for you on save and unserializes it on get.
Name your fields with a pseudo array syntax:
<input name="mycustomfield[audio]">
<input name="mycustomfield[date]">

You'll get a $_POST array:
mycustomfield = array ( 'audio' => 'somevalue', 'date' => 'somedate' )

Now you can do whatever you want with it.
Drawback: Meta queries against serialized arrays are hard. Multiple post meta field are much easier to handle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why am I getting "java.lang.NoClassDefFoundError: kong/unirest/Unirest"? I'm creating a Java application that does a POST action. I need to do a HttpRequestWithBody to send a JSONObject. I'm using Unirest to accomplish this task. While debugging the program stops at the line that creates the request and asigns the URL.
Here is the code:
HttpRequestWithBody response = Unirest.post("{{URL}}"); // This line has the problem
try {
    *** adds headers and body ***
} catch (Exception ex) {
    System.out.println(ex.getMessage());
}

And this is the POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>{{groupId}}</groupId>
<artifactId>program</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>Program</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>10</source>
                <target>10</target>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-java</artifactId>
        <version>3.1.00</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.10</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpasyncclient</artifactId>
        <version>4.1.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.10</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20190722</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
</dependencies>

The error thrown is the following:
Exception in thread "main" java.lang.NoClassDefFoundError: kong/unirest/Unirest
at Program.main(Program.java:139)
Caused by: java.lang.ClassNotFoundException: kong.unirest.Unirest
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 1 more

Process finished with exit code 1

I tried adding other apache.httpcomponents such as Core and Core NIO, none of this helped.
Any help appreciated thanks.

A: This line in exception's stack trace means that you don't have that class Unirest in your class path Exception in thread "main" java.lang.NoClassDefFoundError: kong/unirest/Unirest
However it seems, you added it's lib in dependencies section to be resolved by maven, but it's in "provided scope", and that means you're expecting something else to provide it to you like application server for instance, but i think it's not your environment.
So could you remove that line provided for this dependency
<dependency>
        <groupId>com.konghq</groupId>
        <artifactId>unirest-java</artifactId>
        <version>3.1.00</version>
        <scope>provided</scope>
</dependency>

Then give it another try.

A: removing the <scope> solved it for me.


text:
Q: QuantLib-python pricing barrier option using Heston model I have recently started exploring the QuantLib option pricing libraries for python and have come across an error that I don't seem to understand. Basically, I am trying to price an Up&Out Barrier option using the Heston model. The code that I have written has been taken from examples found online and adapted to my specific case. Essentially, the problem is that when I run the code below I get an error that I believe is triggered at the last line of the code, i.e. the european_option.NPV() function
*** RuntimeError: wrong argument type
Can someone please explain me what I am doing wrong?
# option inputs
maturity_date = ql.Date(30, 6, 2020)
spot_price = 969.74
strike_price = 1000
volatility = 0.20
dividend_rate = 0.0
option_type = ql.Option.Call
risk_free_rate = 0.0016
day_count = ql.Actual365Fixed()
calculation_date = ql.Date(26, 6, 2020)
ql.Settings.instance().evaluationDate = calculation_date

# construct the option payoff
european_option = ql.BarrierOption(ql.Barrier.UpOut, Barrier, Rebate,
                      ql.PlainVanillaPayoff(option_type, strike_price),
                      ql.EuropeanExercise(maturity_date))

# set the Heston parameters
v0 = volatility*volatility # spot variance
kappa = 0.1
theta = v0
hsigma = 0.1
rho = -0.75
spot_handle = ql.QuoteHandle(ql.SimpleQuote(spot_price))

# construct the Heston process
flat_ts = ql.YieldTermStructureHandle(ql.FlatForward(calculation_date,
                                                     risk_free_rate, day_count))

dividend_yield = ql.YieldTermStructureHandle(ql.FlatForward(calculation_date,
                                                            dividend_rate, day_count))
heston_process = ql.HestonProcess(flat_ts, dividend_yield,
                                  spot_handle, v0, kappa,
                                  theta, hsigma, rho)

# run the pricing engine
engine = ql.AnalyticHestonEngine(ql.HestonModel(heston_process),0.01, 1000)
european_option.setPricingEngine(engine)

h_price = european_option.NPV()

A: The problem is that the AnalyticHestonEngine is not able to price Barrier options.
Check here https://www.quantlib.org/reference/group__barrierengines.html for a list of Barrier Option pricing engines.


text:
Q: Django @login_required causing issue when submitting forms I am passing a some information to view function by submitting a form and view requires has  @login_required decorator. Here is the template where i'm passing email ID using a from
<form action="{% url 'become_booster' %}"  method="post">
    {% csrf_token %}
    <input type="hidden" name="email" value="{{ profile_user.email }}" />

            <input type="submit" class="btn btn-success btn-sm" value="Become a Booster">

</form>

Here is the view function
@login_required
def become_booster(request):
    if request.method == "POST":
        email = request.POST.get('email')
        user = CustomUser.objects.filter(email= email)[0]
        tiers = Tiers.objects.filter(user=user)
        form = SubscriptionForm
        return render(request,'select_tier.html',{'tiers':tiers,'form':form})

This is working fine when the user logedin already. When user didn't login, @login_required sends them to login and when it comes back request.method is no longer POST. It no longer has that email info. Can someone help me with this. Thanks!

A: @login_required decorator is used to available that function to registered user who are actually logged in or send to login page or registration page. if you remove @login_required from your view function it will be available for unregistered and all type of users.

A: Try this,
from django.shortcuts import *
@login_required(login_url='become_booster')
def become_booster(request):
    if request.method == "POST":
        email = request.POST.get('email')
        user = get_object_or_404(CustomUser, email=email)
        tiers = get_list_or_404(Tiers, user=user)
        form = SubscriptionForm
        return render(request,'select_tier.html',{'tiers':tiers,'form':form})
    elif request.method == 'GET':
        # Something like this
        # return render(request, 'your_template.html', {'profile_user': user_object_which_contains_email})


text:
Q: Where are the Login and Register pages in an AspNet Core scaffolded app? In VS 2017, I created a new ASP.NET Core Web Application.  On the second page of the wizard, I chose Web Application, and for Authentication, I chose "Individual User Accounts".
Now, I'm trying to find the Pages associated with /Account/Register and /Account/Login.
_Layout.cshtml brings in _LoginPartial.cshtml, much as it did in classic MVC:

Home

About

Contact

    <partial name="_LoginPartial" />

If the user is not signed in then _LoginPartial includes  tags that point to the login and register pages:

Register

Login

That all seems to make sense. But I would have expected the Areas folder structure to include the Register and Login folders.  It does not. The only thing I find there is _ViewStart.cshtml

I know that the scaffolded code works. When I run the project, the Register link points to "/Identity/Account/Register", and the Login link points to "/Identity/Account/Login".  Clicking on the Register link gets me a registration page that includes the text "Create a new account".
But I can't find the text "Create a new account" anywhere in the project.
Can someone tell me what I'm missing?

A: 'If you want all the identity code to be in your application so that you can change it however you want, you can use the new identity scaffolder to add the identity code to your application. All the scaffolded identity code is generated in an identity specific area folder so that it remains nicely separated from your application code.'
https://blogs.msdn.microsoft.com/webdev/2018/02/02/asp-net-core-2-1-roadmap/#identity
It works pretty nice and easy for me.

A: Right-click on the project, select Add -> New Scaffold Item, on the dialog select Identity in the left pane.

You can also generate these pages using this command:
dotnet aspnet-codegenerator identity -dc WebApplication1.Data.ApplicationDbContext

Make sure you replace with your own namespace + DbContext name. The pages are generated here:

If you see this problem:

Feature 'default literal' is not available in C# 7.0. Please use
  language version 7.1 or greater.

You may be able to fix it by adding this to you .csproj and rebuilding it:
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="3.2.0-beta3-final" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.2.0-beta3-final" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.2.0-beta3-final" />

A: It was announced during the preview of asp.net core 2.1 that the Identity UI would be moved to a new Razor Class Library.
https://blogs.msdn.microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identity-ui/
It is still possible to scaffold the Identity Views into your own project if you prefer local views:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.1&tabs=visual-studio

A: Little late to the party but after frustrations with the  Identity UI I gave up on it. Create your projects without it.  My advice is (when using 2.1 or 2.2) create your own account/manage controllers and mvc pages. Some startup.cs debugging will be necessary. Also disable the publish view (i.e. views.dll) compilation option. Maybe I don't have an option set but the compiler completely ignores any changes in page level script blocks.

A: You can do this from within Visual Studio,
Right click on your Project and select Add->New Scaffolded Item

Then select Identity and click on Add

Now select the pages you want to override. Drop down Data Context Class: and your Namespace and Context should be pre-filled in for you.

Finally click on Add. If you have already existing override files there (i.e. from the template) this will warn about overwriting them.

A: Once I found this answer my next question was where is the controller code for identity views? And I found is all csharp codes are attached with these .cshtml files now. I added picture for better understanding.

A: Just wanted to add. If you are looking for the underlying classes for these pages, just open up the related page folder.  Example, for the Register class, open up the Register.cshmtl to find the underlying Register.cshmtl.cs file.  Please see below:


text:
Q: RTL orienting TOC and typesetting Estern Arabic Numberals in Arabxetex I am using arabxetex package and need my TOC oriented from right-to-left as well as to have page numbers be in Eastern Arabic Numberals i.e (٠ ١ ٢ ٣ ٤ ٥ ٦ ٧ ٨ ٩)?
Table of Contents should look like this:   (صصض....... ٣)
Here is a minimal example:
    \documentclass[a4paper]{article}
\usepackage{hyperref}
\usepackage{multicol}
\usepackage{fancyhdr}
\makeatletter
\makeatother
\usepackage{hyperref}
\hypersetup{
    colorlinks,
    citecolor=black,
    filecolor=black,
    linkcolor=black,
    urlcolor=black
}
\usepackage[margin=0.08in, paperwidth=3.56in, paperheight=5.95in]{geometry}
\usepackage{arabxetex}
\usepackage{setspace}
    \renewcommand*\contentsname{}

\begin{document}
\tableofcontents
\newpage

\phantomsection
\addcontentsline{toc}{section}{AAA} % Instead of AAA, I need Arabic text ننن
\begin{arab}[utf]
نتنتنهه
\end{arab}

\newpage
\phantomsection
\addcontentsline{toc}{section}{\textarab[utf]{ يسيس}} % Instead of BBB, I need Arabic text ههه
\begin{arab}[utf]
منسة
\end{arab}

\end{document}

A: If you want to type Arabic natively, then use xelatex and polyglossia, not arabxetex:
\documentclass[a4paper]{article}
\usepackage{polyglossia}
\setmainlanguage{arabic}
\setotherlanguage{english}
\setmainfont{Times New Roman}
\begin{document}
\tableofcontents
\section{انا عجم لا عرب}
الخلیج الفارسیه

\end{document}


text:
Q: drf-spectacular extend_schema_serializer can't do empty value example I'm using the extend_schema_serializer decorator to document examples of json data that can be sent in a POST request. The problem is, one of the variations/examples requires no data, but the generated swagger doc insists on showing what looks like an auto-generated default with all possible params. This isn't ideal when I'm trying to demonstrate the most simple examples.
I have this for the serializer.
@extend_schema_serializer(
    examples=[
        OpenApiExample(
            'Simple example',
            value={},
            request_only=True,
            response_only=False,
        ),
        OpenApiExample(
            'Single param example',
            value={
                'mult': 3,
            },
            request_only=True,
            response_only=False,
        ),
    ],
)
class RollChartSerializer(serializers.Serializer):
    mult = serializers.IntegerField(required=False, write_only=True)
    input_vars = serializers.DictField(required=False, write_only=True)
    foo_name = serializers.CharField(source="foo", allow_null=True, read_only=True)
    foo_url = ChartAbsoluteUrlField(source="foo.id", allow_null=True, read_only=True)
    results = serializers.StringRelatedField(many=True, read_only=True)
...

Where I have value={}, I've also tried value=None and have tried removing it altogether. In all cases, the 'example value' in swagger showing.
{
  "mult": 0,
  "input_vars": {
    "additionalProp1": "string",
    "additionalProp2": "string",
    "additionalProp3": "string"
  }
}

Is there something I'm missing?
I did notice that the generated redoc docs show null.
For the second example, swagger correctly shows
{
    "mult": 3
}

A: I'm not quite sure if they are related, but I had a similar output when I was using the @extend_schema_serializer with a nested serializer like this:
@extend_schema_serializer(
examples=[
    OpenApiExample(
        'Simple example',
        value=some data,
        request_only=True,
        response_only=False,
    ),
    OpenApiExample(
        'Single param example',
        value={another data,},
        request_only=True,
        response_only=False,
        ),
    ],
)
class UserSerializer(serializers.Serializer):
    email = serializers.EmailField()
    username = serializers.CharField(max_length=100)

class CommentSerializer(serializers.Serializer):
    user = UserSerializer()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

The correct way is like this:
class UserSerializer(serializers.Serializer):
    email = serializers.EmailField()
    username = serializers.CharField(max_length=100)

@extend_schema_serializer(
examples=[
    OpenApiExample(
        'Simple example',
        value=some data,
        request_only=True,
        response_only=False,
    ),
    OpenApiExample(
        'Single param example',
        value={another data,},
        request_only=True,
        response_only=False,
        ),
    ],
)
class CommentSerializer(serializers.Serializer):
    user = UserSerializer()
    content = serializers.CharField(max_length=200)
    created = serializers.DateTimeField()

I'm not sure if this will help, but you can include "required=False" in all your "RollChartSerializer" fields. Also, include a summary after the example names.


text:
Q: Create new "execute" function/program in Windows (instead of command prompt) I am using a small program called Youtube-DL to download videos but everytime I have to open the command prompt, get to the right folder and then execute, say, youtube-dl https://www.youtube.com/watch?v=uFk0mgljtns.
What do I need to set up so that I can do the same thing directly from the "execute" tool (the one you access with the shortcut Windows+R)? Ideally all I would need to do would be Windows+R, type yt-dl https://www.youtube.com/watch?v=uFk0mgljtns.

A: Add the youtube-dl executable to your %path%: Use setx /M PATH "%PATH%;C:\folder_with_youtubedl" with an admin cmd.


text:
Q: Appending Result from fetchall() multiple execution to a single DF and converting to a CSV, but in CSV unable to split the list into multiple columns query = pd.read_csv('input_query.csv')
query_list = query['DB_QUERY'].tolist()
length = len(query_list)
result_df = pd.DataFrame()
for i in range(length):
    sql1 = query_list(i)
    cusror1 = conn.cursor()
    cursor1.execute(sql1)
    result = cursor.fetchall()
    result_d = pd.DataFrame(result)
    result_f = result_f.append(result_d)
 result_f.to_csv('output_result.csv',index =False,header=1)

Output is in the format (https://i.stack.imgur.com/hHqHr.png)
0,1,2,3,4
booking,complete,Booking_Daily.snapshot,2021-07-31,2
booking,valid,Booking_Daily.snapshot,2021-07-31,97
Required Format(https://i.stack.imgur.com/vMlD0.png) -
Values splitted in multiple columns instead of single column with column header.

A: Try this:
for i in range(length):
    sql1 = query_list(i)
    cusror1 = conn.cursor()
    cursor1.execute(sql1)
    result = cursor.fetchall()
    result_d = pd.DataFrame(result)
    result_d.to_csv('output_result.csv',index =False,header=1, mode='a')

A small explanation:
result_d is a data frame now so you can append it to a csv on every loop.
Alternatively:
You can append all fetch all results to a list by doing all_results += result[0] as fetchall returns a tuple of lists...
At the end of the loop you can convert all_results to a data frame and proceed to export as csv


text: Q: New tab for the /review : Self-Answer From what I have seen so far self-answer are often thank you message or question asked toward an answer (should be a comment). I think it would be nice to have an other tab in the /review section to have Self-Answer listed there so that we can review them.


text:
Q: Putting of default SMS notification What I am trying to do is developing an SMS notification system for our own application, whenever the sms is received from a specified number the application gets invoked but the problem is that whenever the sms arrives from any other number then also the application gets invoked and that is undesirable. I would be grateful to hear from u all .

A: Read this question and answers: how to stop the application from opening in android
Basically you need to extract the number from the message and if it is a number you are interested in, then you start your application, otherwise not.


text:
Q: pgfplots ticks are not applied I am trying to create a 3D plot with custom z-ticks. However I can not create them with starting negative number. It works however as expected when the ticks start at 0.
My code is this one
\begin{tikzpicture}
\begin{axis}[view={30}{30},grid=major,
   /pgfplots/xtick={0,60,...,300},
   /pgfplots/ytick={0,60,...,300},
   /pgfplots/ztick={-1.0,0.2,...,1.0},
]
\addplot3[surf,domain=0:360,samples=40,
  colormap/jet,colorbar]
  {sin(x)*sin(y)};
\end{axis}
\end{tikzpicture}

with these results (the second with ztick={0,0.2,...,1.0}):

How do I get correct z-ticks from -1 to 1 with steps 0.2?

A: The second number does not give the step size, but the next step. So try {-1.0,-0.8,...,1.0}, or, better, {-1.0,-0.8,...,-0.2,0.0,0.2,...,1.0} as in:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[view={30}{30},grid=major,
   /pgfplots/xtick={0,60,...,300},
   /pgfplots/ytick={0,60,...,300},
   /pgfplots/ztick={-1.0,-0.8,...,-0.2,0.0,0.2,...,1.0},
]
\addplot3[surf,domain=0:360,samples=40,
  colormap/jet,colorbar]
  {sin(x)*sin(y)};
\end{axis}
\end{tikzpicture}
\end{document}

I explicitly specified ...,-0.2,0.0,0.2,... because otherwise, you might get a tick of 10^{-5} instead of 0.


text:
Q: Angular 6 - Change class with onmouseover on a div with ngFor I've this component with html:

        {{option | uppercase}}

Here options is an array ['x', 'y', 'z'] defined in the typescript of the same component.
The problem is, on hover, the class (or clazz) changes for all the three divs that get generated from *ngFor. I expect the class to change only for the hovered div.
Can you please help me understand how to use (mouseover) with *ngFor, and change the class like this? Am I doing something wrong here?
Thanks!

A: You can prepare an array, if you plan to add the class to only one div, something like below:-

    {{option | uppercase}}

As a side note, you may also build a directive which could perform your desired functionality.


text:
Q: avoid line numbering in a algorithm when closing tcolorbox and adjustbox when closing the tcolorbox and adjustbox inside an algorithm, the lines of codes corresponding to their commands are displayed numbered. How can I prevent the 1 beside the caption (see the below figure) from being displayed in the following code?
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[linesnumbered]{algorithm2e}
\usepackage{ float, tcolorbox, adjustbox}
\begin{document}

\begin{algorithm}[htp!]
\begin{adjustbox}{width=0.9\textwidth} \begin{tcolorbox}[left=20pt]
\setcounter{AlgoLine}{0}
\KwData{X: some description o fthe data}
\KwData{Y: other data to describe}
\vspace*{5pt}
\hrule
\vspace*{5pt}
here is the first lone of the code \;
\For{ condition }{
    wow for loop!! \;
    \For {condition}{
        \While{condition}{
        that's intriguing;
        \While{indx in indxs or empty}{indx  $\leftarrow$ rblabla\;}}
    blabla\;
    \For{condition}{
      blabla\;
      blabla\;}}}
      %here I should put something to stop the numbering
      \end{tcolorbox}  \end{adjustbox}
\caption{my caption}\label{alg:this}
\end{algorithm}
\end{document}

A: The following might be sufficient to remove the orphaned line numbering:

\documentclass{article}

\usepackage[linesnumbered]{algorithm2e}
\usepackage{tcolorbox, adjustbox}

\begin{document}

\begin{algorithm}
  \SetNlSty{@gobble}{}{}% Remove line numbering
  \begin{adjustbox}{width=0.9\textwidth}
    \SetNlSty{textbf}{}{}% Default line numbering style
    \setcounter{AlgoLine}{0}% Restore default line numbering start
    \begin{tcolorbox}[left=20pt]
      \KwData{X: some description o fthe data}
      \KwData{Y: other data to describe}
      \vspace*{5pt}
      \hrule
      \vspace*{5pt}
      here is the first lone of the code \;
      \For{ condition }{
        wow for loop!! \;
        \For {condition}{
            \While{condition}{
            that's intriguing;
            \While{indx in indxs or empty}{indx  $\leftarrow$ rblabla\;}}
        blabla\;
        \For{condition}{
          blabla\;
          blabla\;}}}
          %here I should put something to stop the numbering
    \end{tcolorbox}
  \end{adjustbox}
  \caption{my caption}
\end{algorithm}

\end{document}

We set \NlSty to \@gobble the line numbering outside the tcolorbox, and restore it inside. Crude, but functional.


text:
Q: Submitted form results, print to second url? I have no idea how to do this so looking for some direction. I've got a form on 'page-a' behind a staff login and a separate public 'page-b'. I would like the submitted form fields from 'page-a' to populate the content on 'page-b' until the next time it is submitted.
I was thinking I might need to create a JSON file that outputs the results of the form and call upon that JSON in page-b?

A: This is an example of passing state between HTML pages on different URLS.
You are correct that the state can be saved by the php application (eg as an associative array or JSON structure).
You would need also to decide if form B was likely to be activated very soon after form A, or "next week" for example. In the latter case you would need to persist the data in a database or file at the server side.
When "form B" needs the data, it would issue an Ajax request on the server. The server would recover the data, format it (eg JSON), and send it back. At the browser end, you then need to populate the "form B" DOM with the recovered data.

A: It is all about communication between different pages. Hence, to achieve this you can create a singleton storage service and whenever form is submit you can set the response as per the filled data into the storage service from page-a and then you can get the stored data into the page-b.
storageService = {

    formData: {
        name: '',
        email: ''
    },

    SaveState: function () {
        localStorage.setData = JSON.stringify(storageService.formData);
    },

    getState: function () {
        storageService.formData = JSON.parse(localStorage.setData);
    }
}


text:
Q: aiohttp + uvloop parallel HTTP requests are slower than without uvloop I'm writing a script to make millions of API calls in parallel.
I'm using Python 3.6 with aiohttp for this purpose.
I was expecting that uvloop would make it faster, but it seems to have made it slower.  Am I doing something wrong?
with uvloop: 22 seconds
without uvloop: 15 seconds
import asyncio
import aiohttp
import uvloop
import time
import logging

from aiohttp import ClientSession, TCPConnector

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

urls = ["http://www.yahoo.com","http://www.bbcnews.com","http://www.cnn.com","http://www.buzzfeed.com","http://www.walmart.com","http://www.emirates.com","http://www.kayak.com","http://www.expedia.com","http://www.apple.com","http://www.youtube.com"]
bigurls = 10 * urls

def run(enable_uvloop):
    try:
        if enable_uvloop:
            loop = uvloop.new_event_loop()
        else:
            loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        start = time.time()
        conn = TCPConnector(limit=5000, use_dns_cache=True, loop=loop, verify_ssl=False)
        with ClientSession(connector=conn) as session:
            tasks = asyncio.gather(*[asyncio.ensure_future(do_request(url, session)) for url in bigurls]) # tasks to do
            results = loop.run_until_complete(tasks) # loop until done
            end = time.time()
            logger.debug('total time:')
            logger.debug(end - start)
            return results
        loop.close()
    except Exception as e:
        logger.error(e, exc_info=True)

async def do_request(url, session):
    """
    """
    try:
        async with session.get(url) as response:
            resp = await response.text()
            return resp
    except Exception as e:
        logger.error(e, exc_info=True)

run(True)
#run(False)

A: aiohttp recommends to use aiodns
also, as i remember, this with ClientSession(connector=conn) as session: should be async

A: You're not alone; I actually just got similar results (which led me to google my findings and brought me here).
My experiment involves running 500 concurrent GET requests to Google.com using aiohttp.
Here is the code for reference:
import asyncio, aiohttp, concurrent.futures
from datetime import datetime
import uvloop

class UVloopTester():
    def __init__(self):
        self.timeout = 20
        self.threads = 500
        self.totalTime = 0
        self.totalRequests = 0

    @staticmethod
    def timestamp():
        return f'[{datetime.now().strftime("%H:%M:%S")}]'

    async def getCheck(self):
        async with aiohttp.ClientSession() as session:
            response = await session.get('https://www.google.com', timeout=self.timeout)
            response.close()
        await session.close()
        return True

    async def testRun(self, id):
        now = datetime.now()
        try:
            if await self.getCheck():
                elapsed = (datetime.now() - now).total_seconds()
                print(f'{self.timestamp()} Request {id} TTC: {elapsed}')
                self.totalTime += elapsed
                self.totalRequests += 1
        except concurrent.futures._base.TimeoutError: print(f'{self.timestamp()} Request {id} timed out')

    async def main(self):
        await asyncio.gather(*[asyncio.ensure_future(self.testRun(x)) for x in range(self.threads)])

    def start(self):
        # comment these lines to toggle
        uvloop.install()
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

        loop = asyncio.get_event_loop()
        now = datetime.now()
        loop.run_until_complete(self.main())
        elapsed = (datetime.now() - now).total_seconds()
        print(f'{self.timestamp()} Main TTC: {elapsed}')
        print()
        print(f'{self.timestamp()} Average TTC per Request: {self.totalTime / self.totalRequests}')
        if len(asyncio.Task.all_tasks()) > 0:
            for task in asyncio.Task.all_tasks(): task.cancel()
            try: loop.run_until_complete(asyncio.gather(*asyncio.Task.all_tasks()))
            except asyncio.CancelledError: pass
        loop.close()

test = UVloopTester()
test.start()

I haven't planned out and executed any sort of careful experiment where I'm logging my findings and calculating standard deviations and p-values. But I have run this a (tiring) number of times and have come up with the following results.
Running without uvloop:

*

*loop.run_until_complete(main()) takes about 10 seconds.

*average time to complete for request takes about 4 seconds.

Running with uvloop:

*

*loop.run_until_complete(main()) takes about 16 seconds.

*average time to complete for request takes about 8.5 seconds.

I've shared this code with a friend of mine who is actually the one who suggested I try uvloop (since he gets a speed boost from it). Upon running it several times, his results confirm that he does in fact see an increase in speed from using uvloop (shorter time to complete for both main() and requests on average).
Our findings lead me to believe that the differences in our findings have to do with our setups: I'm using a Debian virtual machine with 8 GB RAM on a mid-tier laptop while he's using a native Linux desktop with a lot more 'muscle' under the hood.
My answer to your question is: No, I do not believe you are doing anything wrong because I am experiencing the same results and it does not appear that I am doing anything wrong although any constructive criticism is welcome and appreciated.
I wish I could be of more help; I hope my chiming in can be of some use.

A: I tried a similar experiment and see no real difference between uvloop and asyncio event loops for parallel http GET's:
asyncio event loop: avg=3.6285968542099 s. stdev=0.5583842811362075 s.
uvloop event loop: avg=3.419699764251709 s. stdev=0.13423859428541632 s.

It might be that the noticeable benefits of uvloop come into play when it is used in server code, i.e. for handling many incoming requests.
Code:
import time
from statistics import mean, stdev
import asyncio
import uvloop
import aiohttp

urls = [
    'https://aws.amazon.com', 'https://google.com', 'https://microsoft.com', 'https://www.oracle.com/index.html'
    'https://www.python.org', 'https://nodejs.org', 'https://angular.io', 'https://www.djangoproject.com',
    'https://reactjs.org', 'https://www.mongodb.com', 'https://reinvent.awsevents.com',
    'https://kafka.apache.org', 'https://github.com', 'https://slack.com', 'https://authy.com',
    'https://cnn.com', 'https://fox.com', 'https://nbc.com', 'https://www.aljazeera.com',
    'https://fly4.emirates.com', 'https://www.klm.com', 'https://www.china-airlines.com',
    'https://en.wikipedia.org/wiki/List_of_Unicode_characters', 'https://en.wikipedia.org/wiki/Windows-1252'
]

def timed(func):
    async def wrapper():
        start = time.time()
        await func()
        return time.time() - start
    return wrapper

@timed
async def main():
    conn = aiohttp.TCPConnector(use_dns_cache=False)
    async with aiohttp.ClientSession(connector=conn) as session:
        coroutines = [fetch(session, url) for url in urls]
        await asyncio.gather(*coroutines)

async def fetch(session, url):
    async with session.get(url) as resp:
        await resp.text()

asycio_results = [asyncio.run(main()) for i in range(10)]
print(f'asyncio event loop: avg={mean(asycio_results)} s. stdev={stdev(asycio_results)} s.')

# Change to uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

uvloop_results = [asyncio.run(main()) for i in range(10)]
print(f'uvloop event loop: avg={mean(uvloop_results)} s. stdev={stdev(uvloop_results)} s.')


text:
Q: get time and date in each button click android I have this button that will generate time and date and set it as a child in a database tree, the problem is whenever I click buttons it generates the said time but the time is not changing,
for example i clicked on the button and it generates the time 12:27 Pm, and it will be recorded into the database, now i clicked the button again for the second time and it doesn't change still printing out the 12:27 Pm Instead 12:30 Pm.
the code looks like this
 btnadd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Integer num1 = Integer.parseInt(edt1.getText().toString());
            Integer num2 = Integer.parseInt(edt2.getText().toString());
            Integer result = num1+num2;
            String data = "Date Computed: " + Date + Hrs +"Result: "+ result;

            DateView.setText(data);

            HashMap<String, String> userMap = new HashMap<>();
            userMap.put("Add", data);

            rootNode = FirebaseDatabase.getInstance();
            reference = rootNode.getReference("Users").child("UserID").child(Date);
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (snapshot.exists()){
                        maxid = (snapshot.getChildrenCount());
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });

            reference.child("Transaction"+maxid).setValue(userMap);
        }
    });

    edt1 = findViewById(R.id.edt1);
    edt2 = findViewById(R.id.edt2);
    btnadd = findViewById(R.id.btnadd);
    btnmin = findViewById(R.id.btnmin);
    DateView = findViewById(R.id.DateView);
    calendar = Calendar.getInstance();
    simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");
    Date = simpleDateFormat.format(calendar.getTime());
    simpleHoursFormat = new SimpleDateFormat(" hh:mm:ss ");
    Hrs = simpleHoursFormat.format(calendar.getTime());

A: Hi from the code it looks like you haven't updated your Date and Time in your onClickListener. The updated code should be like this :-
btnadd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // This will fetch your updated date and time
            Date = simpleDateFormat.format(calendar.getTime());
            Hrs = simpleHoursFormat.format(calendar.getTime());
            Integer num1 = Integer.parseInt(edt1.getText().toString());
            // Rest of your code

A: Try to use this
import java.util.Calendar
Date currentTime = Calendar.getInstance().getTime();


text:
Q: Problema na array do Foreach Meu problema é o seguinte, espero que possam me ajudar:
Estou buscando alguns registros da tabela "Produtos" do meu banco de dados e exibindo ela no front. Estou usando um Foreach para trazer esses registros e há também um botão que irá criar uma sessão e adicionar esses produtos ao meu carrinho. O problema não é no carrinho em si e sim na lista onde está localizado o botão que irá adicionar. Ele chama um Action referenciando se há uma ação (o action, né) e o id do produto. O caminho fica mais ou menos assim:
---> localhost/LoginandRegisterLanchenet/carrinho.php?add=carrinho&id=
O id fica vazio e não referencia a nada resultando em um erro de URL não encontrada. Segue abaixo o código que abaixo:
<?php
$conect = new db();
$conect = $conect ->conectar();

$query = mysqli_query($conect, "SELECT * FROM produto");
$result = mysqli_fetch_all($query);

echo "
CRIAR RESERVA

";
echo "
 Cardápio

";
foreach ($result as $item){
    echo "
";
    echo "
".$item[1]."<input class='btn btn-primary' type='button' value='+' style='display: relative; float : right; margin-right :1rem; margin-top: 0.5rem;'>
".$item[3]."  Valor: R$ ".$item [5]."

";
}

echo "

";
echo "

";
?>

Alguém conseguiu identificar o erro?
Caso precise de mais detalhes é só dizer que eu acrescento.
Grato!!
Att.

A: Simulei como poderia estar o array e abaixo tem um código explicativo. Execute o var_dump para ver a saída. Parece ser o que você procura.
É necessário validar que o ID não seja vazio para não dar erro em sua URL. Você tem que validar para que não seja passado um produto sem id.
<?php

$result[] = [
    0 => 7, //id
    1 => 'mouse', //produto
    2 => 14, // quantidade
    3 => 12.00 //valor Unitario
];

$result[] = [
    0 => NULL, //id
    1 => 'pendrive', //produto
    2 => 140, // quantidade
    3 => 35.00 //valor Unitario
];

$result[] = [
    0 => '', //id
    1 => '', //produto
    2 => '', // quantidade
    3 => '' //valor Unitario
];

$result[] = [
    0 => NULL, //id
    1 => NULL, //produto
    2 => NULL, // quantidade
    3 => NULL //valor Unitario
];

//var_dump($result);

foreach ($result as $item) {
    $id = $item[0];
    $produto = $item[1];

    if ($id != '' || !empty($id)) {
        echo "\n Existe " . "ID: " . $id;
        //continue; // Ou seja pula estes nulos
    } else {
        echo "\n Nulos ou vazios (Sem id)";
    }
}

Simulando o array de result acima para listar em view segundo seu código listado seria:
(apenas troquei umas variáveis e fiz a validação de vazio primeiro para depois listar os dados)
<?php
// Abre conexão
$conect = new db();
$conect = $conect ->conectar();

// Executa a query
$query = mysqli_query($conect, "SELECT * FROM produto");
// Retorna um array com os dados
$result = mysqli_fetch_all($query);

echo "
iFood

";
echo "
 Cardápio

";

// Percorre os dados
foreach ($result as $item) {
    $id = $item[0];
    $produto = $item[1];
    $qtdeEstoque = $item[2];
    $valor = $item[3];

    if ($id == '' || empty($id)) {
        // Se tiver um id vazio ele pula
        continue;
    } else {
        // Se tiver id ele mostra o produto
        echo "
";
        echo "
" . $produto . "<input class='btn btn-primary' type='button' value='+' style='display: relative; float : right; margin-right :1rem; margin-top: 0.5rem;'>
" . $qtdeEstoque . "  Valor: R$ " . $valor . "

";
    }
}

echo "

";
echo "

";


text:
Q: Add @GeneratedValue on a later point, when data in table is already present An entity which has ID but the data in corresponding table was added manually, for this reason @GeneratedValue annotation was never added. Now I need to create records in this table through code and want my ID to be auto-incremented.
On adding @Id @GeneratedValue(strategy = GenerationType.AUTO) Integer id;
The exception I get is:
java.sql.SQLException: Field 'id' doesn't have a default value

Is there a way to make this work?

A: You need to change the column definition in the database to add a default value of "AUTO_INCREMENT".
For Mysql:
ALTER TABLE yourtable MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT;

I think you should also set the next AUTO_INCREMENT value for the table to the actual maximum value of the id + 1:
ALTER TABLE yourtable AUTO_INCREMENT = new_value;


text:
Q: Conditional CSS - Only showing Box-Shadow if Background Colour is not Opaque I've searched around for this quite a bit but haven't found anyone trying to solve this problem which I find weird. I'd preface this with me having 6 years+ of front end experience and I honestly don't know the best approach.
We have an app where Users create dynamic divs and they decide the size/color/shape off these divs. To stylise them a bit we have given the divs a box-shadow to make them look better. The problem comes in when a user decides to have a transparent background (we use rgba for bg-color and you have a slider that can make the opacity 0) and then the box shadow still remains and it does not look good. I've been trying to look at writing conditional CSS for this but don't think it is possible.
The only solution I can think off is having a class that has no box-shadow with important to overrule it, and with jQuery parse the bg-color and look for the Opacity value - if its 0 then add this class. This seems very clunky and like a bad approach, but maybe this problem is unique enough that this is the only solution?
Interested in hearing peoples thoughts.

A: You can replace box-shadow width drop-shadow. The latter will show nothing for a transparent div:

.box {
  display:inline-block;
  margin:5px;
  height:100px;
  width:100px;
  filter:drop-shadow(5px 5px 5px #000);
}

Or like below if you want the drop-shadow to only be around borders:

.box {
  display:inline-block;
  margin:5px;
  height:100px;
  width:100px;
  position:relative;
}
.box::before,
.box::after{
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  z-index:-1;
}
.box::before {
  background:inherit;
  filter:drop-shadow(5px 5px 5px #000);
}
.box::after {
  background:#fff; /* this should be equal to main background */
}

A: https://jsfiddle.net/chille1987/9gd7ukqh/27/
If you use inline styles to control bg color than it could be done with some Jquery.

CSS
.box {
    width: 150px;
    height: 150px;
    margin: 5px 0;
    border: 1px solid #000000;
    box-shadow: 1px 1px 5px rgba(0,0,0,.5);
}

.box.no-shadow {
    box-shadow: none;
}

JS
$('.box').each(function() {
    var el = $(this);
    var currentColor = $(this).css('background-color');
    var rgba = currentColor.match(/\d+/g);
    var counter = 0;

    for(var i in rgba) {
      counter++;
      var last = rgba[i];
    }

    if(counter === 4 && last == 0) {
        el.addClass('no-shadow');
    }
});


text:
Q: How to avoid quotes around table name in Laravel Illuminate Firebird I am creating project with Laravel Illuminate that connects to existing Firebird database using jacquestvanzuydam project. The problem is that Firebird doesn't use quotes around table and field names, but my present configuration tries to add quotes around table names in each select that it creates automatically.
How to configure Laravel or Illuminate to create SQL statements without quotes?

A: try to write table name like it named in your database. in your model.
protected $table = 'TABLE_NAME';

i had that problem and solved it by written table name in uppercase


text:
Q: Swift - Present UIAlertController in extension function I've wrote a label extension which detect links in the label.
It's attributed text with NSLinkAttributeName for links and I'm using
func handleTapOnLabel(_ tapGesture:UITapGestureRecognizer){} to detect where is the tap and which link to choose to open. The problem is that I use the function in extension for UILabel and I want to present an UIAlertController to ask the person - "You are about to open this link in Safari. Would you like to proceed?"... So I can't access viewcontroller to use the function present(UIAlertController... to display the alert. Any suggestions how this can be happened in extension? How to access label's viewcontroller directly from extension ?

A: Method 1) Present UIAlertController on top most ViewController in ViewController's hierarchy
extension UILabel { //your extension
   func openLinkAction() {  //your extension custom method
     //code
      if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
      }

    // topController should now be your topmost view controller
    // present alert on this controller
}
       //and present here with vcInstance
   }
}

Method 2) Pass ViewController's object as parameter
extension UILabel { //your extension
   func openLink(vc: UIViewController) { //your extension custom method function
       // code
       // present alert on this vc
   }
}

// For getting top most controller you ca use..
extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

//  topController
if let topController = UIApplication.topViewController() {

}


text:
Q: How get the variable value outside javascript function I have a code which is used to send a GET request via javascript. I'm new to javascript and would like to seek your help for the following issue.
Following is my javascript code and is there a way to call var title value outside the function. As an example after the line request.send(); . I would be obliged if you could help me out.
let request = new XMLHttpRequest();
  request.open("GET", "https://jsonplaceholder.typicode.com/todos/1");

  request.onload = function () {
    console.log(request);
    if (request.status == 200){
      console.log(JSON.parse(request.response));
      var obj = JSON.parse(request.response);

      if (obj.id == 1)
      {
        var title = obj.title;
        //document.getElementById("demo").innerHTML = title;
      }

    }else {
      console.log(`error ${request.status} ${request.statusText}`);
      document.getElementById("demo").innerHTML = "Error";
    }

  }
  request.send();
  document.getElementById("demo").innerHTML = title;


text:
Q: Why min-width is needed on window resize? I have seen in some web pages that blank spaces is added after divs (specially in header and footer areas) when the browser window is resized. I found the solution is using min-width for those area.
For seeing the problem I said please resize any page of Stack Overflow.com, for example the page you are reading now. I've seen many sites with this problem.
But why is it so? Why is it needed? Div is a block element and should be stretch to this parent width when no width is defined, so the header, and footer should be 100% without any blank space.
Here's a screenshot:
xx http://thesis.um.ac.ir/Screenshot-16.jpg

A: Yes, as a block level element, it will stretch to it's relative containers width. That is to say, any parent or container that has a non-static position or has dimensions. If there are no elements in the hierarchy that have a set dimension or position, then the window is used. The <html> and <body> elements aren't actually the elements the width is based upon by default. By default, the window is actually setting the size of the <html> and <body> elements, which are block*, and even though its children are running outside of it, the element will still get smaller.
So what you are seeing is the size of the <body> element getting smaller, even though the contents on the page are running off the end.
* NOTE: <html> and <body> are not actually block, but they can be thought of as block level for this purpose.


text:
Q: How can i remove unwanted extra double values from timer i have the following duration result
0:00:01.110000

and i am trying to make it look like following , one for minute and one for seconds .. single digit minutes since my case don't require more than 9 minutes
0:01

the problem i can't control the source of duration because it comes from plugin i use , and i need to handle it in Text widget with the previous patron
duration myResulDuration  = 0:00:01.110000;
Text(myResulDuration.toString()),

outouts : 0:00:01.110000

wanted result is 0:01

How can i achieve with this ?

A: Write a function that gives two digits of formatted data
String twoDigits(int n) => n.toString().padLeft(2, '0');

final minutes = twoDigits(myResultTimer.inMinutes.remainder(60));
final seconds = twoDigits(myResultTimer.inSeconds.remainder(60));

show these minutes and seconds in Text Widget
Text(''$minutes:$seconds')


text:
Q: how to override GET method in django to make a seen status I wanna make this thing on the model as I'm using REST API too.
I have a model named as Seen
class Seen(models.Model):
    seen = models.BooleanField(
        verbose_name=_("Is active"), default=True,
        help_text=_("Inactive devices will not be sent notifications")
    )
    user = models.ForeignKey(
        SETTINGS["USER_MODEL"], blank=True, null=True, on_delete=models.CASCADE
    )
    post = models.ForeignKey(Posts)

and I wanna to override my custom class-based view, so that everytime an authenticated user visits a DetailView I create an instance of the Seen.

A: In your class-based view you can override method get:
def get(self, request, *args, **kwargs):
    # fetch your values from request.GET.get('key')
    # and play around with it
    return self.render_to_response(context)

Or since you're using DetailView:
def get_object(self, queryset=None):
    # key for Post's id (consider it as 'id'),  you maybe named it differently
    post_id = self.kwargs.get('id')
    if post_id is None:
        raise Http404
    try:
        post = Post.objects.get(id=post_id) # fetch your post
        user = self.request.user # considering your user is authenticated
        # Create Seen object and save it with params,
        # seen field is optional, since you set defaul value
        seen_object = Seen.objects.create(post=post, user=user, seen=True)
    except Post.DoesNotExist: # if wrong id was passed
        raise Http404
    return post # return an object for your DetailView

P.S.: To make sure that your user is authenticated add LoginRequiredMixin to your view, like: PostDetailView(LoginRequiredMixin, DetailView) and set login_url='login'


text:
Q: Which is the best way to update VF page input fields using Javascript? Why? I have seen both of these being used to update VF page inputs in Javascript dynamically.
Approach 1:
document.getElementById('{!$Component.thePage.theForm.theField}').required = true;

Approach 2:
document.getElementById('thePage:theForm:theField').required = true;

Are there any scenarios that either of them may fail? or better than the other.

A: Since DOM IDs in Visualforce components are dynamically generated in order to ensure IDs are unique, the advantage of using $Component is this will give you the dynamic order and you dont have to manually create it , in the absolute sense as you have created in Approach 2. So if you  have nested tags and in the inner tag you can just reference $Component.idOfElement instead of manually trying to figure out what the ids will be.
In the example below : you can just use {!$Component.theSectionItem} to get j_id0:theForm:thePageBlock:theSection:theSectionItem.
When creating the id for the 'form', VF dynamically named the form id as "j_id0:theForm"
The value for $Component is relative to  where you are calling it from. In this scenario its "j_id0:theForm:thePageBlock:theSection".
If you have not broken the chain while referencing the id in getElementById,  both approaches will work. Its a mater of convenience what you want to use and how much you want to figure out
<apex:form id="theForm">
    <apex:pageBlock id="thePageBlock" >
        <apex:pageBlockSection id="theSection">
             <apex:pageBlockSectionItem id="theSectionItem">

The full DOM ID resembles something like this:

                j_id0:theForm:thePageBlock:theSection:theSectionItem

            </apex:pageBlockSectionItem>
            <apex:outputPanel layout="block" styleClass="clicker"
                onclick="alert('{!$Component.theSectionItem}');">
                First click here
            </apex:outputPanel>

A: Sometimes that kind the code requires maintenance if you add element in the hierarchy.
Better, use getElementbyClassName() approach, instead of getElementById().
<apex:inputField value="{!cust.Name}" styleClass="myElement"/>

Javascript
var form1 = document.getElementById('{!$Component.form1}');
var elements = form1.getElementsByClassName('myElement');

You could loop through the elements and update accordingly.
If there are any elements (table, div etc.) in between form and field, it will not create any issue. Only thing, you need to provide identifiable styleClass name
Also, you can explore document.getElementsByClassName('myElement')


text:
Q: Force query results to paginate/divide large query into smaller ones to avoid timeout with crummy API I am using the provided Epicor Prophet 21 database API to form queries to our database. All is well until I form a query to return data on about 200 inventory parts at once. The 1 minute request TimeOut seems to be built into the assembly files, and there is no functionality for pagination or specific output selection.
I have thought about trying to divide the list alpha-numerically by the itemIDs, (eg. returning all itemIDs > GGGGGGG, then all itemIDs < GGGGGGG). But the IDs are all of different lengths, and the middle point shifts about. This seems clunky, and there must be a better way to divide the query results without knowing what the specific results will be. The API provides standard query filters: comparison operators =><, and/or, startsWith, endsWith, subStringOf.
Any ideas?


text:
Q: How to use a custom type correctly in Symfony? I am trying to use all the power of Symfony to build a site. I already have 2 years of experience in Symfony but for the first time, I am trying to use the concept of custom form type to create a specific registration form. I already have a registration form for basic users but now, I want to create another one for managers whom operate hotels.
I have already created a form type named RegistrationFormType and another one named HotelType. My thing is that I want to use both of these form types in one form. But I keep getting an exception which says

Neither the property "user" nor one of the methods "getUser()",
  "user()", "isUser()", "hasUser()", "__get()" exist and have public
  access in class "App\Entity\User"

I have followed whatever was said in the Symfony official documentation about custom form types.
I made this form type RegistrationHotelFormType which is made up of another form RegistrationFormType used elsewhere as a form for basic users to create accounts and HotelType generated by Symfony itself.
<?php

namespace App\Form;

use App\Entity\User;
use App\Form\HotelType;
use App\Form\RegistrationFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;

class RegistrationHotelFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('user', RegistrationFormType::class, ['mapped' => false])
            ->add('hotel', HotelType::class, ['mapped' => false])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

This above use to work but in the Symfony documentation, I don't need to set a mapped parameter to false knowing that I want form values to be assigned to objects fields which are Hotel and User. How can I get this done? (https://symfony.com/doc/current/form/create_custom_field_type.html#creating-form-types-created-from-scratch).
RegistrationFormType:
<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Validator\Constraints\File;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class, ['error_bubbling'=>true, 'label' => 'Email', 'attr' => ['type'=>'text','class'=>'form-control', 'placeholder'=>'Email', 'aria-label'=>"Username", 'aria-describedby'=>"basic-addon1"]])
            ->add('plainPassword', RepeatedType::class, [
                'type' => PasswordType::class,
                'label' => 'Mot de passe',
                'attr' => ['error_bubbling'=>true,
                'type'=>'text',
                'class'=>'form-control',
                'placeholder'=>'Mot de passe',
                'aria-label'=>"Username",
                'aria-describedby'=>"basic-addon1"],
                'mapped' => false,
                'constraints' => [
                    new NotBlank([
                        'message' => 'Mot de passe requis',
                    ]),
                    new Length([
                        'min' => 8,
                        'minMessage' => 'Le mot de passe doit avoir au moins {{ limit }} caractères',
                        // max length allowed by Symfony for security reasons
                        'max' => 128,
                        'maxMessage' => 'Le mot de passe ne doit pas dépasser {{ limit }} caractères',
                    ]),
                    // new Regex([
                    //     'pattern' => '/^\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$/',
                    //     'message' => 'Le mot de passe doit contenir au moins 1 lettre et 1 chiffre',
                    // ])
                ],
            ])
            ->add('firstname', TextType::class, ['error_bubbling'=>true, 'label' => 'Prénom', 'attr' => ['type'=>'text','class'=>'form-control', 'placeholder'=>'Prénom', 'aria-label'=>"Username", 'aria-describedby'=>"basic-addon1"]])
            ->add('surname', TextType::class, ['error_bubbling'=>true, 'label' => 'Nom', 'attr' => ['type'=>'text','class'=>'form-control', 'placeholder'=>'Nom', 'aria-label'=>"Username", 'aria-describedby'=>"basic-addon1"]])
            ->add('phoneNumber', TextType::class, ['error_bubbling'=>true, 'label' => 'Téléphone', 'attr' => ['type'=>'text','class'=>'form-control', 'placeholder'=>'Téléphone', 'aria-label'=>"Username", 'aria-describedby'=>"basic-addon1"]])
            ->add('city', TextType::class, ['error_bubbling'=>true, 'label' => 'Ville', 'attr' => ['type'=>'text','class'=>'form-control', 'placeholder'=>'Ville', 'aria-label'=>"Username", 'aria-describedby'=>"basic-addon1"]])
            ->add('termsAccepted', CheckboxType::class, [
                'error_bubbling'=>true,
                'mapped' => false,
                'constraints' => new IsTrue(),
                'attr' => ['type'=>"checkbox", 'class'=>"form-check-input"]
            ])
            ->add('resumePDF', FileType::class, [
                'error_bubbling'=>true,
                'label' => 'CV (Fichier PDF)',
                'mapped' => false,
                'required' => true,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/pdf',
                            'application/x-pdf',
                        ],
                        'mimeTypesMessage' => 'Téléchargez un fichier PDF valide',
                    ])
                ],
                'attr' => ['type'=>"file", 'class'=>"custom-file-input"]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

HotelType
<?php

namespace App\Form;

use App\Entity\Hotel;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class HotelType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('address');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Hotel::class,
        ]);
    }
}

RegistrationController.php
    /**
 * @Route("/inscription-hotel", name="app_register_hotel")
 */
public function registerHotel(Request $request, UserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer): Response
{
    $session = new Session();
    // $session->start();

    $user = new User();
    $form = $this->createForm(RegistrationHotelFormType::class, $user);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
    }

    return $this->render('registration/register-hotel.html.twig', [
        'registrationForm' => $form->createView(),
    ]);
}

Thanks in advance for your help

A: Cerad diagnosed why the error is triggered (the second argument to createForm will be used and the form will try to access the user and hotel property on it), the simplest solution follows:
I would remove the data_class from the combined form, and just omit the second parameter to createForm in your controller. The return value of $form->getData() would be an array:
['user' => {User object}, 'hotel' => {Hotel object}]
(you can also provide a similarly structured array to your createForm call as the second parameter)
of course, you can create a new class that contains both the user and the hotel...


text:
Q: Steroids and Angular: Preloading Multiple Webviews from data I'm working with a Steroids generator ng-resource, which has generated controller/model/views based on some local json data. It has an index.html and a detailed.html
The boilerplate code provides a list of cars which you click on, bringing you to a new webview of the car's detailed page. Easy enough. The problem is, this view is not preloaded - it loads in after you click a car in the car list. This creates a laggy experience.
I've read up on preloading webviews - which works great if you don't have a bunch of webviews powered by dynamic data. I would like to preload all detailed webviews based on the initial listing of "cars". I've been reading the following resources:
Preloaded Webviews from different parts of your app
Sharing Data Between webviews
Preloading Webviews
I don't have a lot of raw code to provide - just boilerplate examples of ng-resource. I'm wondering what the best technical approach is for my needs. Trying to get that native app feel when navigating.

A: EDIT: Here is a better answer from the Appgyver/Steroids Team
From what you have described your use case to be like I would suggest that you would preload the show.html in your app once and then whenever you need to show the show.html you would send a postmessage from the view you are moving from to show.html that it should load the content for the id provided.
If you have to load the content from a remote server, you should send two postmessages, with the first one including whatever info you already have on the previous page that would be used on the show.html page.
I don't know if I was able to explain this in the most easily understandable way, but please ask more questions if my explanation was unclear )
Turns out it was pretty easy:

The main problem from my solution below is memory issues from creating a vast amount of webviews
Old Answer:
        for(var i =0; i

       var webView = new steroids.views.WebView({location:"/views/cars/show.html?        id="+id,id:id});
console.log(webView);
webView.preload({}, {
onSuccess: function() {
//steroids.layers.push(webView);
console.log('working');
 }
});
}

Then with another function call a webview with the same id:
  $scope.open = function(id) {

var webView = new steroids.views.WebView({location:"/views/cars/show.html?id="+id,id:id});
steroids.layers.push(webView);
};


text:
Q: How to send a var to router Maybe in express, there are some thing changed. But I don't know how to send the session:
var session = require('express-session');
app.use('/', routes);

to another .js file router.
var express = require('express');
var router = express.Router();
module.exports = router;

A: generally seesion we configure in configure section like this
var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')

var app = express()

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}))

in controller level we can access the session like
req.session
we can access seesion
to regenerate the session
req.session.regenerate(function(err) {
  // will have a new session here
})

destroy seesion
req.session.destroy(function(err) {
  // cannot access session here
})

store the value in session
req.session.key = value;

retrieving value from session
req.session.key

refer the given link
https://github.com/expressjs/session
we can pass api object to route configuration like this ;
var api = require('express');
require('../api/routes/authorization.routes.js')(api);

in route configuration
   module.exports = function (api) {

        api.route('/api/authorization/token')
            .post( authorization.token);

    };


text:
Q: PayPal v2 Orders API - difference between OrdersGetRequest and OrdersCaptureRequest I'm using checkout-sdk with angular and spring boot. Here is the code I have on the angular side
           paypal
            .Buttons({
              style: {
                color:  'blue',
                shape:  'pill',
                label:  'pay',
                height: 40
              },
              createOrder: (data, actions) => {
                return actions.order.create({
                  purchase_units: [
                    {
                      description: 'Order id: '+this.order.id,
                      amount: {
                        currency_code: 'EUR',
                        value: this.order.totalPrice
                      }
                    }
                  ]
                });
              },
              onApprove: async (data, actions) => {
                const order = await actions.order.capture();
                this.paidFor = true;
                this.checkoutPaypal(this.id,order.id)
              },
              onError: err => {
              }
            })
            .render(this.paypalElement.nativeElement);

This is function used to retrieve payment, and save details to database..
 public String checkoutPaypal(Integer id, String orderId) {
        OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
        request.requestBody(buildRequestBody());
        HttpResponse<com.paypal.orders.Order> response;

        try {
            response = payPalClient.client().execute(request);
        } catch (IOException e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
        }

        for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
            purchaseUnit.amountWithBreakdown();
            for (Capture capture : purchaseUnit.payments().captures()) {
                if (capture.status().equals("COMPLETED")) {
                    Order order = orderRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found!"));
                    order.setOrderState(OrderState.PAID);
                    order.setPaymentDetails("Charge id: " + capture.id() + "; Status: " + capture.status() + "; Time paid: " + capture.createTime() + " GMT");
                    order.addOrderStateChange(OrderState.PAID, false);

                    sendEmail(order, " paid successfully!", "Thanks for your purchase!<br>We will work as hard as we can, to deliver the order to you, as soon as possible!");
                    orderRepository.save(order);
                }
            }
    }
    return "Successfully paid!";
}

Which worked few days ago.. But now I'm getting this error
{"name":"UNPROCESSABLE_ENTITY","details":[{"issue":"ORDER_ALREADY_CAPTURED","description":"Order already captured.If 'intent=CAPTURE' only one capture per order is allowed."}],"message":"The requested action could not be performed, semantically incorrect, or failed business validation.","debug_id":"f058cb447ccbb","links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-ORDER_ALREADY_CAPTURED","rel":"information_link","method":"GET"}]}

But after replacing
 OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
 request.requestBody(buildRequestBody());
 HttpResponse<com.paypal.orders.Order> response;

with
 OrdersGetRequest request = new OrdersGetRequest(orderId);
 HttpResponse<com.paypal.orders.Order> response;

It works as it should.
So my question is, what is the difference between
https://developer.paypal.com/docs/checkout/reference/server-integration/capture-transaction/
and
https://developer.paypal.com/docs/checkout/reference/server-integration/get-transaction/ ?

A: One is to get the status of the order, the other is to capture the order.
Capturing should not be done once you have called actions.order.capture() on the client side, and will always return an error in such a case. It may also also return an error when the order has been created on the client side (actions.order.create())

A correct server-based integration uses neither actions.order.create() nor actions.order.capture() on the client side. It is very important not to do so, as transactions will be created without your server receiving any immediate direct response from PayPal.
Instead, create two routes on your server, one for 'Create Order' and one for 'Capture Order' as documented here.  These routes should return JSON data. Before returning data, the capture route should check for success and act accordingly to send an email or whatever other business operation you need.
The approval flow to pair with the above two routes is https://developer.paypal.com/demo/checkout/#/pattern/server


text:
Q: Can I use Ubuntu on an old PC? I would like to know if I can install Ubuntu on an old computer
Their characteristics are:
Intel core i3 380M 2.53 GHZ processor
2 GB ram memory
320GB hard drive

A: Since the system is equipped with 2 GB of RAM only, you should use a 32-bit operating system which is not supported any more.
A 64-bit system will use approximately 600-700 MB of memory, leaving approximately 1.3 GB available for the user. If this is enough for you, go ahead and try a light flavour, like Lubuntu or Xubuntu for example. Maybe you'd like to add some more memory before you install a 64-bit system though.


text:
Q: JCL - Incluir sortin en un fichero Quisiera saber cómo incluir en un paso de SORT un fichero que a su vez contiene la ficha sortin, es decir el contenido del fichero se ha creado dinámicamente y tiene esta pinta:
//SORTIN   DD DSN=DES.LQHISE03.ENTRADA,
//            DISP=SHR

A: No se si este paso te servirá, tiene de entrada un sortin y es un paso de sort. Seria el paso siguiente a seguir después de la creación para que te ordene según necesites.
PASORT01 EXEC SORTD
//SORTIN   DD DSN=DES.LQHISE03.ENTRADA,DISP=OLD
//SORTOUT  DD DSN=XX.XXXXXXXX.XXXXXXX,
//            DISP=(,CATLG,DELETE),
//            SPACE=(TRK,(5,5),RLSE),
//            DCB=(RECFM=FB,LRECL=80,BLKSIZE=0,DSORG=PS)
//SORTWK01 DD SPACE=(CYL,10)
//SORTWK02 DD SPACE=(CYL,10)
//SORTWK03 DD SPACE=(CYL,10)
//SYSIN    DD *
  SORT FIELDS=(n,n,A),FORMAT=BI
  RECORD LENGTH=(nn),TYPE=F


text:
Q: Dragging and dropping incorrect item from array I am trying to follow the vue-draggable docs to create draggable lists but when I drag/drop an item, a different one is being moved. For example, if I drag standard1 into the Term2 list, standard2 ends up on the second list. What's going on here?
data(){
  return {
    terms: [
      {
        "id": 1,
        "label": "Term1",
        "term_standards": [
          {"id": 1, "label": "standard1"},
          {"id": 2, "label": "standard2"},
        ]
      },
      {
        "id": 2,
        "label": "Term2",
        "term_standards": [
          {"id": 3, "label": "standard3"},
          {"id": 4, "label": "standard4"},
        ]
      },
    ]
  }
}

<draggable
  v-model="terms[0].term_standards"
  class="dragArea"
  :options="{group:'ITEMS'}"
  :key="terms[0].id">
    {{ terms[0].label }}
  <li
    v-for="item in terms[0].term_standards"
    :key="item.id">
      {{ item.label }}
  </li>
</draggable>

<draggable
  v-model="terms[1].term_standards"
  class="dragArea"
  :options="{group:'ITEMS'}"
  :key="terms[1].id">
    {{ terms[1].label }}
  <li
    v-for="item in terms[1].term_standards"
    :key="item.id">
      {{ item.label }}
  </li>
</draggable>

A: When the template is rendered, you are missing ul around the li elements.
Also, {{ terms[0].label } and {{ terms[1].label } should be placed outside of <draggable> element.
Your template should look like this

{{ terms[0].label }}
<draggable
  element="ul"
  v-model="terms[0].term_standards"
  class="dragArea"
  :options="{group:'ITEMS'}"
>
  <li
    v-for="item in terms[0].term_standards"
    :key="item.id">
      {{ item.label }}
  </li>
</draggable>

{{ terms[1].label }}
<draggable
  element="ul"
  v-model="terms[1].term_standards"
  class="dragArea"
  :options="{group:'ITEMS'}"
>
  <li
    v-for="item in terms[1].term_standards"
    :key="item.id">
      {{ item.label }}
  </li>
</draggable>


text:
Q: Get hwnd by process id c++ How can I get the HWND of application, if I know the process ID? Anyone could post a sample please? I'm using MSV C++ 2010.
I found Process::MainWindowHandle but I don't know how to use it.

A: A single PID (Process ID) can be associated with more than one window (HWND). For example if the application is using several windows.
The following code locates the handles of all windows per a given PID.
void GetAllWindowsFromProcessID(DWORD dwProcessID, std::vector <HWND> &vhWnds)
{
    // find all hWnds (vhWnds) associated with a process id (dwProcessID)
    HWND hCurWnd = NULL;
    do
    {
        hCurWnd = FindWindowEx(NULL, hCurWnd, NULL, NULL);
        DWORD dwProcID = 0;
        GetWindowThreadProcessId(hCurWnd, &dwProcID);
        if (dwProcID == dwProcessID)
        {
            vhWnds.push_back(hCurWnd);  // add the found hCurWnd to the vector
            wprintf(L"Found hWnd %d\n", hCurWnd);
        }
    }
    while (hCurWnd != NULL);
}

A: Thanks to Michael Haephrati, I slightly corrected your code for modern Qt C++ 11:
#include <iostream>
#include "windows.h"
#include "tlhelp32.h"
#include "tchar.h"
#include "vector"
#include "string"

using namespace std;

void GetAllWindowsFromProcessID(DWORD dwProcessID, std::vector <HWND> &vhWnds)
{
    // find all hWnds (vhWnds) associated with a process id (dwProcessID)
    HWND hCurWnd = nullptr;
    do
    {
        hCurWnd = FindWindowEx(nullptr, hCurWnd, nullptr, nullptr);
        DWORD checkProcessID = 0;
        GetWindowThreadProcessId(hCurWnd, &checkProcessID);
        if (checkProcessID == dwProcessID)
        {
            vhWnds.push_back(hCurWnd);  // add the found hCurWnd to the vector
            //wprintf(L"Found hWnd %d\n", hCurWnd);
        }
    }
    while (hCurWnd != nullptr);
}

A: You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.

A: HWND g_HWND=NULL;
BOOL CALLBACK EnumWindowsProcMy(HWND hwnd,LPARAM lParam)
{
    DWORD lpdwProcessId;
    GetWindowThreadProcessId(hwnd,&lpdwProcessId);
    if(lpdwProcessId==lParam)
    {
        g_HWND=hwnd;
        return FALSE;
    }
    return TRUE;
}
EnumWindows(EnumWindowsProcMy,m_ProcessId);


text:
Q: PHP FPDF Arabic Text Isolated I am trying to generate a pdf document in the Arabic language, I have the same in English format using fpdf. After doing some research, I ended up replacing fpdf with tfpdf and tcpdf. The later messed up my pdf layout and did not work 100% with arabic words. So I opted for tfpdf.
After more research of tfpdf I ended up with the following code:
//to add custom font from unicode folder
$pdf->AddFont('Tajawal', '', 'Tajawal-Medium.ttf', true);
//to set the custom font
$pdf->SetFont('Tajawal','',18,true);

//helper function to rever the arabic string since I get the output reversed in the pdf
function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return implode(array_reverse($ar[0]));
}
//$answer comes from a php and is an arabic string
$pdf->MultiCell(0 , 7, utf8_strrev($answer),1);

As depicted in the picture (screenshot from generated pdf), the Arabic letters are separated/disjoint but have a correct order thanks to the reverse helper function. How can we fix this issue in tfpdf?
Additional Information
The font I used is Tajawal, it's an Arabic google font: https://fonts.google.com/specimen/Tajawal?subset=arabic
I have added these to my html document:
ini_set('default_charset', 'UTF-8');

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

I also tried inserting the same Arabic fields in a database and they work perfectly.

A: After trying for a while, I found out that the best solution is to use TCPDF for laravel instead of FPDF. You can build your code starting with this small example:
$html_content = '
يسبي
';
PDF::SetTitle('Sample PDF');
PDF::SetFont('aealarabiya', '', 18);
PDF::AddPage();
PDF::writeHTML($html_content, true, false, true, false, '');
PDF::Output('SamplePDF.pdf');

You can also check this link for more details on the TCPDF library for arabic pdf generation.


text:
Q: Netbeans/Maven development: how to make it faster? I'm using Maven for the heavy lifting. However, when working on small parts (like unit tests), the reaction time of "mvn test" inside Netbeans is too slow. I have already written a ClassReloader that sets up directory watches and uses Netbeans' compile-on-save. However, that is a bit clumsy because it requires me to modify the test unit class and add a main method.
Is there a nicer way? I already thought of setting up a parallel view of the same modules, one that uses ant build scripts. You guys have any better idea? Or tools to make that easier?
For example, the maven-dependency-plugin is able to copy dependencies and write the classpath to a file. That's a start. But how do I import the classpath into the ant build file, or even better, into the netbeans project configuration? And what about the system props set up in the configuration section of the maven-surefire-plugin?
There is the maven-ant-plugin, however it has nearly no configuration options and it does not work without modifying the output files.
Are there better tools? Maybe a netbeans project generator that transforms maven projects into netbeans project configurations?
Then there is yet another problem: you cannot use the same source folder twice in netbeans, not even if the other instance is inside a not currently open project group....
The solution need not be perfect: like I said, it is only needed for the small parts.
Maybe I start using Eclipse for the simple and small stuff.
I won't start discussing about what's better, Netbeans eclipse etc. I use Netbeans because it is the only IDE with native Maven support. Eclipse's maven support is crap and I wasted too much time already because of it being that way.

A: Typically while mvn test (running all tests) is as slow as running on the command line, running single tests should be significantly faster with Compile on Save turned on. You would just effectively execute surefire:surefire  via mvn as the classes were compiled for you on the fly. It still does take up to a few seconds, as new JVM is created, maven project loaded and surefire goal is executed which again spawns another jvm, your mileage may vary.
You can trigger the Run Test action while having both the test or tested class in editor.


text:
Q: In Xpath how do I check the time difference in 2 dateTimes Say I have 2 dateTime elements in XML:
<effectivedate>2018-08-28 15:45:00</effectivedate>
<startdate>2018-08-28 15:44:00</startdate>

I can subtract the 2 to get the difference like so:
xs:dateTime(replace(//effectivedate," ","T")) - xs:dateTime(replace(//startdate," ","T"))

but this returns PT1M. How can I use this to check if the time difference is less than 5 minutes?

A: There are two ways. Either convert the duration to a number (of minutes, say) by dividing by a constant duration and then compare with a number:
$duration div xs:dayTimeDuration('PT1M') lt 5

or subtract two durations directly:
$duration lt xs:dayTimeDuration('PT5M')


text:
Q: Pythonic way to manage mutual exclusion for flags' values I have a function to conduct the argument parsing for my program, let's say I have
def parse_program_args():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--A",
        type='str'
        )
    parser.add_argument(
        "--B",
        type='str'
        )
    parser.add_argument(
        "--C",
        type=int
        )

...
...

A can have one of a few options as well as B and C (each of them has another set of optional values).
I'm trying to manage restriction on the user choices and mutual exclude some values for those arguments.
For example, I want to ban the following combinations of arguments:

*

*--A apple" and "--B red

*--B red --C 1
The problem is that I don't want to impose an order restriction on the user, so I can't rely on the argument order.
I'm looking for a pythonic way to do so.


text:
Q: Getting error "Firebase Functions Deploy: Error occurred while parsing your function triggers" I have a parsing problem with the functions.pubsub when doing a Firebase deploy and I don't know why, I check everything on Stack Overflow but nothing seems to work.
Why is this happening? I don't know what I am doing wrong at this point.
This is the code :
const functions = require("firebase-functions");
const axios = require("axios");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();
const page = 1;
const fiat = "RON";
const tradeType = "BUY";
const asset = "USDT";
const payTypes = ["ING"];
let finalData = [];
let tempDataBeforeProccessing = [];

const baseObj = {
  page,
  rows: 20,
  publisherType: null,
  asset,
  tradeType,
  fiat,
  payTypes,
};

const stringData = JSON.stringify(baseObj);

const getTheData = async function() {
  tempDataBeforeProccessing=[];
  await axios.post("https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search", baseObj, {
    hostname: "p2p.binance.com",
    port: 443,
    path: "/bapi/c2c/v2/friendly/c2c/adv/search",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Content-Length": stringData.length,
    },
  }).then((res)=>{
    tempDataBeforeProccessing=res.data.data;
  });
};

const processData = function() {
  finalData=[];
  let obj = [];
  for (let i = 0; i < tempDataBeforeProccessing.length; i++) {
    let payTypesz = "";
    for (let y = 0; y <
    tempDataBeforeProccessing[i]["adv"]["tradeMethods"].length; y++) {
      payTypesz +=
      tempDataBeforeProccessing[i]["adv"]["tradeMethods"][y]["identifier"];
      if (y <
      tempDataBeforeProccessing[i]["adv"]["tradeMethods"].length - 1) {
        payTypesz += ", ";
      }
    }
    obj = {
      tradeType: tempDataBeforeProccessing[i]["adv"]["tradeType"],
      asset: tempDataBeforeProccessing[i]["adv"]["asset"],
      fiatUnit: tempDataBeforeProccessing[i]["adv"]["fiatUnit"],
      price: tempDataBeforeProccessing[i]["adv"]["price"],
      surplusAmount:
      tempDataBeforeProccessing[i]["adv"]["surplusAmount"],
      maxSingleTransAmount:
      tempDataBeforeProccessing[i]["adv"]["maxSingleTransAmount"],
      minSingleTransAmount:
      tempDataBeforeProccessing[i]["adv"]["minSingleTransAmount"],
      nickName:
      tempDataBeforeProccessing[i]["advertiser"]["nickName"],
      monthOrderCount:
      tempDataBeforeProccessing[i]["advertiser"]["monthOrderCount"],
      monthFinishRate:
      tempDataBeforeProccessing[i]["advertiser"]["monthFinishRate"],
      payTypes: payTypesz,
    };
    finalData.push(obj);
  }

  console.log(finalData);
};

const entireCall = async function() {
  await getTheData();
  processData();
};

exports.scheduledFunctionBRCSEBI = async functions.pubsub
      .schedule("* * * * *")
      .onRun(async (context) => {
        await database.collection("SebiBinanceSale").doc("BCR Bank").delete();
        await entireCall();
        for (let i = 0; i < finalData.length; i++) {
          database.collection("SebiBinanceSale").doc("BCR Bank")
              .collection("1").doc(i.toString())
              .set({
                "tradeType": finalData[i]["tradeType"],
                "asset": finalData[i]["asset"],
                "fiatUnit": finalData[i]["fiatUnit"],
                "price": finalData[i]["price"],
                "surplusAmount": finalData[i]["surplusAmount"],
                "maxSingleTransAmount": finalData[i]["maxSingleTransAmount"],
                "minSingleTransAmount": finalData[i]["minSingleTransAmount"],
                "nickName": finalData[i]["nickName"],
                "monthOrderCount": finalData[i]["monthOrderCount"],
                "monthFinishRate": finalData[i]["monthFinishRate"],
                "payTypes": finalData[i]["payTypes"],
              });
        }
        console.log("Succes Upload of the data ");
      });

Error is in this line: exports.scheduledFunctionBRCSEBI = async functions.pubsub where you can see functions.pubsub , world functions is the error.
This is the error:
functions: Finished running predeploy script.
⚠  functions: package.json indicates an outdated version of firebase-functions. Please upgrade using npm install --save firebase-functions@latest in your functions directory.
⚠  functions: Please note that there will be breaking changes when you upgrade.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled

Error: Error occurred while parsing your function triggers.

/Users/ivanoiualexandrupaul/StudioProjects/BeconCryptoProject/binance/functions/index.js:87
exports.scheduledFunctionBRCSEBI = async functions.pubs
                                         ^^^^^^^^^

SyntaxError: Unexpected identifier
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
    at loadModule (/usr/local/lib/node_modules/firebase-tools/lib/deploy/functions/runtimes/node/triggerParser.js:10:16)
    at /usr/local/lib/node_modules/firebase-tools/lib/deploy/functions/runtimes/node/triggerParser.js:34:21
    at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/deploy/functions/runtimes/node/triggerParser.js:72:3)

Having trouble? Try firebase [command] --help

This is the eslintrc:
module.exports = {

  root: true,
  env: {
    es6: true,
    node: true,
  },
  extends: [
    "eslint:recommended",
    "google",
  ],
  rules: {
    quotes: ["error", "double"],
  },
  parserOptions: {
    parser: "babel-eslint",
    ecmaVersion: 8,
    sourceType: "module",
  },
};

This is package.json
{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "main": "index.js",
  "dependencies": {
    "async": "^3.2.4",
    "cors": "^2.8.5",
    "firebase-admin": "^10.3.0",
    "firebase-functions": "^4.0.1",
    "request": "^2.88.2",
    "request-promise": "^4.2.6"
  },
  "devDependencies": {
    "eslint": "^8.9.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

A: In order to fix it you have to delete the async world in front of the functions.pubsub and it will work. I know a small mistake and it is also a stupid one since async should not go there.
 exports.scheduledFunctionBRCSEBI = functions.pubsub
          .schedule("* * * * *")
          .onRun(async (context) => {
            await database.collection("SebiBinanceSale").doc("BCR Bank").delete();
            await entireCall();
            for (let i = 0; i < finalData.length; i++) {
              database.collection("SebiBinanceSale").doc("BCR Bank")
                  .collection("1").doc(i.toString())
                  .set({
                    "tradeType": finalData[i]["tradeType"],
                    "asset": finalData[i]["asset"],
                    "fiatUnit": finalData[i]["fiatUnit"],
                    "price": finalData[i]["price"],
                    "surplusAmount": finalData[i]["surplusAmount"],
                    "maxSingleTransAmount": finalData[i]["maxSingleTransAmount"],
                    "minSingleTransAmount": finalData[i]["minSingleTransAmount"],
                    "nickName": finalData[i]["nickName"],
                    "monthOrderCount": finalData[i]["monthOrderCount"],
                    "monthFinishRate": finalData[i]["monthFinishRate"],
                    "payTypes": finalData[i]["payTypes"],
                  });
            }
            console.log("Succes Upload of the data ");
          });


text:
Q: Javascript, encodeURI() function not encoding most characters I'm trying to validate a string to put inside an url as a site's subdirectory, the problem is that my encodeURI() function leaves most of my special characters as they're and I really can't get why since I tried using the same function on W3School code editor and it works just fine.
Let's say I do a test and put a random string into the function

var string = encodeURI("àèìòù°*;£$#"); //these are some of the special characters that the encoding doesn't work on
console.log(string);

the output I get is the string "àèìòù°*;£$#" as it is,
yet on the W3School console the output is "%C3%A0%C3%A8%C3%AC%C3%B2%C3%B9%C2%B0*;%C2%A3$#"
What's the problem with my function?
p.s. I tried to use encodeURIComponent() too, which I don't know if is more appropriate to use in my case and I noticed it works a bit differently but still gives me the same results
!!EDIT!!
I just found something really unusual in my code and I have less of a clue that I had before on what's happening:
var stringTest = encodeURI("àèìòù°");
console.log(stringTest);
//outputs: %C3%A0%C3%A8%C3%AC%C3%B2%C3%B9%C2%B0
$scope.myDictionary["randomkey"] = stringTest;
//gets "àèìòù°" as the value of stringTest


text:
Q: Thingsboard: change of database I have installed thingsboard on Linux. initially it was using Cassandra database, but now i have changed it to postgresql. But the issue is that both the thingsboard and postgresql are not running. The only error in postgresql log file is "Incomplete startup Packet" and thingsboard log file has "all hosts tried query failed(tried: /127.0.0.1:9042)" error.
I have stopped the Cassandra service and also configured the thingsboard.yml file to use postgresql database.
How to fix this issue.

A: Without knowing more log details, I suggest to fresh install a new ThingsBoard+PostgreSQL instance and migrate the Cassandra db to the new instance using the REST API feature of ThingsBoard, this way you avoid the corruption of PostgreSQL.
The steps are:

*

*Install a new instance of ThingsBoard and PostgresSQL

*Retrieve data via REST API from old instance

*Send data via MQTT or other supported protocols to new instance

You can find a script which does this automatically in this repo.

A: I am not sure but In my experience that you should check up as below.

*

*install PostgreSQL on your server.

*create database like thingsboard inside postgreSQL.

*configure for using PostgreSQL in thingsboard.yml

*Run installation script again

https://thingsboard.io/docs/user-guide/install/linux/#memory-update-for-slow-machines-1gb-of-ram