text:
Q: Prove upper bound from gaussian quadrature Let $I = \int_{0}^1 ln(1+sin(x))dx$, and P be the polynomial with degree less or equal than 5 using the minimum square method to approximate the function $ln(1+sin(x))$ on [0,1].
Show that $$2\underset{x\in[0,1]}{sup}|ln(1+sin(x))-P(x)|$$ is an upper bound of the maximum absolute error of I using gaussian quadrature with 3 points

A: I've tried to several things like:
By the mean value theorem of integrals, there exists an $\alpha \in [0,1]$ such that $ln(1+sin(\alpha)) = I $, so if a is the gaussian quadratue with 3 points, $|I-a| = |I-P(x) + P(x) - a| \leq |I-P(x)| + |P(x) - a|$, if I could show that $|P(x) - a| \leq |I-P(x)|$ I'd have the problem solved, but can't progress from here...
Also, I tried to rewrite $I = \displaystyle \sum_0^5 1/(n+1)a_n $, but couldn't progress from here as well (this is the first equation to approximate f(x) using the minimum square method).


text:
Q: Python - Extracting data from the table I am trying to extract data from the table and that I accessed by using beautiful soup library. I get the table as html but I am strugling to extract data in consumable form since the table itself has two columns with headers in first and values in second.
Here is my code:
html = browser.html
soup = bs(html, "html.parser")

table = soup.find("table", {"id":"productDetails_techSpec_section_1"})
table

Results of printing table:
"

                    Part Number

              3885SD

                  Item Weight

              1.83 pounds

                  Product Dimensions

              9 x 6 x 3.5 inches

                  Item model number

              3885SD

                  Item Package Quantity

              1

                  Number of Handles

              1

                  Batteries Included?

              No

                  Batteries Required?

              No

"

I tried using this line of code to access each header and data point:
headings = [table.get_text() for th in table.find("tr").find_all("th")]
print(headings)

And this is the response i get:
['\n\n\n                  \tPart Number\t\n                \n\n              3885SD\n            \n\n\n\n                  Item Weight\n                \n\n              1.83 pounds\n            \n\n\n\n                  Product Dimensions\n                \n\n              9 x 6 x 3.5 inches\n            \n\n\n\n                  Item model number\n                \n\n              3885SD\n            \n\n\n\n                  Item Package Quantity\n                \n\n              1\n            \n\n\n\n                  Number of Handles\n                \n\n              1\n            \n\n\n\n                  Batteries Included?\n                \n\n              No\n            \n\n\n\n                  Batteries Required?\n                \n\n              No\n            \n\n']

I have been researching different approaches to get this data into pandas dataframe and this is the closes i got so far.
My questions is how do i get this data into data frame where my headers and values would be like example below?

A: *

*pandas.read_html() - Read HTML tables into a list of DataFrame objects.

Ex.
 import pandas as pd

html = """

Part Number
 3885SD

 Item Weight	1.83 pounds

Product Dimensions
 9 x 6 x 3.5 inches

Item model number
 3885SD

Item Package Quantity
 	1

 Number of Handles
 	1

 Batteries Included?
 	No

  Batteries Required?	No

"""

#read table data
df = pd.read_html(html)[0]
cols = df[0]
vals = df[1]

table = pd.DataFrame(vals).T
#reset columns name
table.columns = cols
print(table)

O/P:
0 Part Number  Item Weight  Product Dimensions Item model number Item Package Quantity Number of Handles Batteries Included? Batteries Required?
1      3885SD  1.83 pounds  9 x 6 x 3.5 inches            3885SD                     1                 1                  No                  No

A: Solution:
Create the function to parste the table:
def parse_table(table):
    """ Get data from table """
    return [
        [cell.get_text().strip() for cell in row.find_all(['th', 'td'])]
           for row in table.find_all('tr')
    ]

Then create new table by using the function and convert the table into panda dataframe:
new_table = parse_table(table)
df = pd.DataFrame(new_table)
df =df.T
df.columns = df.iloc[0]
df = df[1:]
df

A: You can use zip() to transpose values in table:
from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'html.parser') # data is your table from question

rows = []
for tr in soup.select('tr'):
    rows.append([td.get_text(strip=True) for td in tr.select('th, td')])

rows = [*zip(*rows)]    # transpose values

for row in rows:
    print(''.join(r'{: <25}'.format(d) for d in row))

Prints:
Part Number              Item Weight              Product Dimensions       Item model number        Item Package Quantity    Number of Handles        Batteries Included?      Batteries Required?
3885SD                   1.83 pounds              9 x 6 x 3.5 inches       3885SD                   1                        1                        No                       No

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\langle f,g\rangle_H$ is $\mu$-mesurable Let $H$ be a Hilbert space and $(X,\mu,\mathcal{A})$ a $\sigma$-finite, complete measure space. My textbook states that $L_2(X,\mu,H)$ together with $$\langle\cdot,\cdot\rangle_2\colon L_2(X,\mu,H)^2\to\mathbb{K},\quad (f,g)\mapsto\int_X\langle f,g\rangle_H\, d\mu$$
is a hilbert space and that this would be obvious using some result  $(\star)$ and Hölder's inequality.
This is not obvious to me as I fail to see how, given $f=[f'],g=[g']\in L_2(X,\mu,H)$, it is$\langle f',g'\rangle_H\in\mathcal{L}_0(X,\mu,\mathbb{K})$:  I know that $(f',g')\in\mathcal{L}_0(X,\mu,H^2)$. The result $(\star)$ states that

In separable Banach spaces $E$, $F$, given $u\in\mathcal{L}_0(X,\mu,E)$, $v\in\mathcal{C}(f(X), F)$, it is $u\circ v\in\mathcal{L}_0(X,\mu,F)$.

However, $E=H^2$ is not assumed to be separable, so how is this result applicable?

A: I have looked at the method used by Folland to prove that $fg$ is measurable if $f$ and $g$ are, and think that the same method can be applied to this case.
Let $f,g : X \to H$ be fixed and let $h : X \to \mathbb K$ be defined by $h(x) = \langle f(x), g(x) \rangle$. Then we can write $h = \langle \cdot, \cdot \rangle \circ p$ where $p: X \to H^2$ is given by $p(x) = (f(x), g(x))$.
Now, $\langle \cdot, \cdot \rangle : H^2 \to \mathbb K$ is continuous and therefore measurable $(\mathcal B_{H^2}, \mathcal B_{\mathbb K})$-measurable. Here $\mathcal B_Y$ denotes the Borel-sets on $Y$. Also, $p$ is $(\mathcal B_X, \mathcal B_{H^2})$-measurable (here $\mathcal B_X = \mathcal A$ according to your notation) as a tuple of $(\mathcal B_X, \mathcal B_{H})$-measurable functions. Then the composition $\langle \cdot, \cdot \rangle \circ p$ is $(\mathcal B_X, \mathcal B_{\mathbb K})$-measurable.


text:
Q: minecraft auto status bot download on github is error I downloaded a bot that periodically modifies the Minecraft server status on Discord from Github, and this error pops up. How can I fix it?
C:\Users\Administrator\Downloads\minecraft-bot-main\events\interactionCreate.js:4
if (interaction.type !== InteractionType.ApplicationCommand) return;
^
TypeError: Cannot read properties of undefined (reading 'ApplicationCommand')
at module.exports (C:\Users\Administrator\Downloads\minecraft-bot-main\events\interactionCreate.js:4:46)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\discord.js\src\client\actions\InteractionCreate.js:83:12)
at module.exports [as INTERACTION_CREATE] (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\discord.js\src\client\websocket\WebSocketManager.js:346:31)
at WebSocketShard.onPacket (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\discord.js\src\client\websocket\WebSocketShard.js:478:22)
at WebSocketShard.onMessage (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\discord.js\src\client\websocket\WebSocketShard.js:317:10)
at callListener (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\ws\lib\event-target.js:290:14)
at WebSocket.onMessage (C:\Users\Administrator\Downloads\minecraft-bot-main\node_modules\ws\lib\event-target.js:209:9)
at WebSocket.emit (node:events:513:28)
Node.js v18.8.0
Reinstall node 18.14.0 to 18.8.0 and command 'npm insatll'


text:
Q: Manually defined legend in Plotly on Python I have some data that is broken down by day. For each day, I have a datapoint at the start and end of the day, each with a value between 0 and 100. I need to display this data as a grouped bar plot with the days on the x axis, values on the y axis and the bars colors are determined by their values. For each day, the left bar needs to have the corresponding start value, and the right bar displays the day's end value. The legend however needs to display information on the color rather than the trace
The plot basically needs to look like this but the legend needs to display "green", "amber", "red" instead of "start", "end".
I need the plot to look like this but with a legend describing the colors rather than the traces
Here is some code to reproduce the plot:
x = ["day"+str(i) for i in range(1,8)]
starts = [10, 50, 70, 75, 20, 50, 90]
ends = [95, 5, 80, 20, 50, 10, 75]
starts_colors = ['green', 'orange', 'red', 'red', 'green', 'orange', 'red']
ends_colors = ['red', 'green', 'red', 'green', 'orange', 'green', 'red']

And here is the code I have for the plot above.
layout = go.Layout(showlegend=True)
fig = go.Figure(layout=layout)
fig.add_trace(go.Bar(x=x, y=starts, name = 'start', marker=dict(color=starts_colors)))
fig.add_trace(go.Bar(x=x, y=ends, name = 'end', marker=dict(color=ends_colors)))
fig.show()

If I rearrange the data into 3 traces (one for each color) with the corresponding values in starts and ends, I end up with gaps between the bars. For example "day1" would have a gap in the middle because there is no orange bar for "day1".
This seems like a simple problem but I'm at a loss as to how to get it to work the way I'm supposed to.

A: *

*this creates exactly the graph you requested

*start by putting your sample data into a dataframe to open up Plotly Express

*start by updating traces to use colors columns

*adding legend is done.  Really is not a functional legend as it cannot be used for filtering the figure, will just show unique colors used in figure.  This is achieved by adding additional small traces

import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "day": ["day" + str(i) for i in range(1, 8)],
        "starts": [10, 50, 70, 75, 20, 50, 90],
        "ends": [95, 5, 80, 20, 50, 10, 75],
        "starts_colors": ["green", "orange", "red", "red", "green", "orange", "red"],
        "ends_colors": ["red", "green", "red", "green", "orange", "green", "red"],
    }
)

# build figure, hover_data / customdata is used to hold colors
fig = px.bar(
    df,
    x="day",
    y=["starts", "ends"],
    barmode="group",
    hover_data={"starts_colors":False, "ends_colors":False},
)

# update colors of bars
fig.plotly_update(
    data=[
        t.update(marker_color=[c[i] for c in t.customdata])
        for i, t in enumerate(fig.data)
    ]
)

# just for display purpose, create traces so that legend contains colors.  does not connect with
# bars
fig.update_traces(showlegend=False).add_traces(
    [
        go.Bar(name=c, x=[fig.data[0].x[0]], marker_color=c, showlegend=True)
        for c in np.unique(df.loc[:,["starts_colors","ends_colors"]].values.ravel())
    ]
)


text:
Q: Customizing the 'back' arrow color in Actionmode with appcompat-v7 My main theme is based on Theme.AppCompat.Light as follows:
<style name="core" parent="Theme.AppCompat.Light" >
    <!-- Material, Yo!-->
    <item name="colorPrimary">@color/theme_main_color</item>
    <item name="colorPrimaryDark">@color/deep_purple</item>
    <item name="colorAccent">@color/theme_accent_color</item>
    <item name="android:navigationBarColor" tools:ignore="NewApi">?attr/colorPrimary</item>
    <!-- Toolbar -->
    <item name="theme">@style/my_toolbar_theme</item>
    <item name="drawerArrowStyle">@style/my_drawer_arrow</item>
    <!-- Actionbar -->
    <item name="android:actionBarDivider">@null</item>
    <item name="android:actionBarTabStyle">@null</item>
    <item name="android:actionBarTabBarStyle">@null</item>
    <!-- Contextual Actionbar -->
    <item name="windowActionModeOverlay">true</item>
    <item name="actionModeBackground">?attr/colorAccent</item>
    <item name="actionModeStyle">@style/my_actionmode_style</item>
</style>

<style name="my_drawer_arrow" parent="Widget.AppCompat.DrawerArrowToggle" >
    <item name="spinBars">true</item>
    <item name="color">@color/theme_accent_color</item>
</style>

<style name="my_toolbar_style">
    <item name="android:id">@id/toolbar</item>
    <item name="android:minHeight">?attr/actionBarSize</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:background">?attr/colorPrimary</item>
    <item name="android:elevation" tools:ignore="NewApi">5dp</item>
</style>

<style name="my_actionmode_style" parent="Widget.AppCompat.Light.ActionMode.Inverse" >
    <item name="titleTextStyle">@style/my_actionmode_title_style</item>
    <item name="subtitleTextStyle">@style/my_actionmode_subtitle_style</item>
</style>

<style name="my_toolbar_style.gradient">
    <item name="android:background">@drawable/ab_gradient_bg</item>
</style>

<style name="my_toolbar_theme" parent="ThemeOverlay.AppCompat.Dark.ActionBar" >
    <!-- Customize the toolbar here -->
</style>

<style name="my_actionmode_title_style" parent="TextAppearance.AppCompat.Widget.ActionMode.Title">
    <item name="android:textColor">@color/std_white</item>
</style>

<style name="my_actionmode_subtitle_style" parent="TextAppearance.AppCompat.Widget.ActionMode.Subtitle">
    <item name="android:textColor">@android:color/white</item>
</style>

In actionmode I'd like to see white title/subtitles with a white back arrow. I've been able to set the title and subtitle text colors to white, but the back arrow remains black. This issue only occurs in places where I'm using the SupportActionbar and not the toolbar (the back arrow in toolbar is white).
This is my toolbar in ActionMode.

This is the actionbar in ActionMode. Same phone, same app, same themes, just a different activity.

I can't find anything in the themes that would determine this color. According to the source, the icon is @drawable/abc_ic_ab_back_mtrl_am_alpha, which is white, so something must be tinting it. Where does this black-ish color come from?

A: To customize this using AppCompat:
In your app level theme:
<style name="MyTheme" parent="Theme.AppCompat.Light">
    <item name="actionModeCloseButtonStyle">@style/myclosebutton</item>
</style>

In the CloseButtonStyle:
<style name="myclosebutton" parent="Widget.AppCompat.Light.ActionButton.CloseMode">
    <item name="android:tint">#ff0</item> <!-- whatever color -->
</style>

A: I had the same problem and I have solved it by explicitly declaring the icon I want to use in the style:
<item name="android:actionModeCloseDrawable">@drawable/ab_back</item>

Where @drawable/ab_back is provided by me.
This is not ideal, as I would like to correctly set the style and let it work inheriting the right colours from the parent theme, without the need of declaring so specific details. But, I feel everything around the ActionBar, SupportActionBar, SherlockActionBar, ActionBarActivity, FragmentActivityWithASherlockSupportActionToolbar is SO broken and bad engineered that I'm happy to solve it with a workaround.

A: Try "colorControlNormal" Property Like given Below in your "NoActionBar Theme"
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="colorControlNormal">@android:color/white</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

A: I have best answer for this
 Spannable text = new SpannableString( mode.getTitle());
                    text.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimaryDark)),
                            0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    mode.setTitle(text);


text:
Q: How can I export my websites data to an .xlsx file? I am displaying a table on my website and want to provide users the option to download it. So far, I've been wrapping it in an HTML file with an .xls extension. When downloaded, this opens in excel and displays the correct data.
Of late, users have been complaining that when they open the file, they get a "The file format and extension of filename.xls don't match..." error. Turns out that Microsoft had released a security patch that would show this warning.
My question is, what kind of file should I write my data into so that the warnings don't come up?
I would like to write the file myself instead of using PHP or any 3rd party libraries.


text:
Q: System Console over JTAG fails to execute master_write_32 — can't do this while target is running? I had a simple controller written in Verilog that was configuring Altera's TSE MAC. Up to this point, it was fairly simple. However, what I wanted to do next is to set a lot of Marvel PHY's settings as well as keep monitoring both PHY and MAC for statistics and errors, etc. Doing that in HW seems like an overkill, so I have decided to incorporate a Nios CPU. But before going ahead and implementing the component in software, I wanted to quickly prototype the idea using System Console. Anyhow, here is my QSys base system:

The MAC instance is called tse_mac and the idea is to configure it by reading/writing to control_port through CPU's data_master.
After getting the system up and running, I've connected to it using System Console. I assume it generally works because it is able to get master service path:
% get_service_paths master
{/devices/EP2AGX260@1#7-1/(link)/JTAG/(70:34 v3 #0)/nios2_0}

It also opens fine. However, it fails right away when trying to write 32-bit value:
% get_service_paths master
{/devices/EP2AGX260@1#7-1/(link)/JTAG/(70:34 v3 #0)/nios2_0}
% open_service master "/devices/EP2AGX260@1#7-1/(link)/JTAG/(70:34 v3 #0)/nios2_0"

% master_write_32 "/devices/EP2AGX260@1#7-1/(link)/JTAG/(70:34 v3 #0)/nios2_0" 0x400 0x00000000;
error: com.altera.systemconsole.internal.plugin.jtag.oci.Nios2DebugException: Can't do this while target is running
    while executing
"master_write_32 {/devices/EP2AGX260@1#7-1/(link)/JTAG/(70:34 v3 #0)/nios2_0} {0x400} {0x00000000}"
    while executing
"master_write_32 "/devices/EP2AGX260@1#7-1/(link)/JTAG/(70:34 v3 #0)/nios2_0" 0x400 0x00000000"
%

Here is the exception:
Jul 22, 2012 12:17:39 PM com.altera.systemconsole.internal.core.SystemConsole logSevere
SEVERE: com.altera.systemconsole.internal.plugin.jtag.oci.Nios2DebugException: Can't do this while target is running
java.util.concurrent.ExecutionException: com.altera.systemconsole.internal.plugin.jtag.oci.Nios2DebugException: Can't do this while target is running
    at com.altera.systemconsole.internal.core.SimpleFuture$Sync.innerGet(SimpleFuture.java:169)
    at com.altera.systemconsole.internal.core.SimpleFuture.get(SimpleFuture.java:66)
    at com.altera.systemconsole.scripting.StandardCommandSet.waitForFutureResponse(StandardCommandSet.java:233)
    at com.altera.systemconsole.scripting.StandardCommandSet.peekMemoryService(StandardCommandSet.java:161)
    at com.altera.systemconsole.scripting.StandardCommandSet.readByte(StandardCommandSet.java:120)
    at com.altera.systemconsole.scripting.ScriptEngine$16.execute(ScriptEngine.java:1117)
    at com.altera.systemconsole.scripting.ScriptEngine$LegacyCommandAdapter.execute2(ScriptEngine.java:199)
    at com.altera.systemconsole.scripting.SystemConsoleThreadTCLInterpreter$2$1.run(SystemConsoleThreadTCLInterpreter.java:181)
    at com.altera.systemconsole.internal.core.SystemExecutor$4.run(SystemExecutor.java:516)
    at com.altera.systemconsole.internal.core.SystemExecutor$ComparableTask.run(SystemExecutor.java:148)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.altera.systemconsole.internal.plugin.jtag.oci.Nios2DebugException: Can't do this while target is running
    at com.altera.systemconsole.internal.plugin.jtag.oci.Nios2Debug.readMemoryIndirect(Native Method)
    at com.altera.systemconsole.internal.plugin.jtag.oci.Nios2Debug.readMemory(Nios2Debug.java:186)
    at com.altera.systemconsole.internal.plugin.jtag.oci.OciMemoryService.peek(OciMemoryService.java:158)
    at com.altera.systemconsole.internal.core.legacymaster.LegacyMasterChannel$1.run(LegacyMasterChannel.java:88)
    at com.altera.systemconsole.internal.core.SystemExecutor.addTaskIfNecessary(SystemExecutor.java:536)
    at com.altera.systemconsole.internal.core.legacymaster.LegacyMasterChannel.doReadMemory(LegacyMasterChannel.java:77)
    at com.altera.systemconsole.internal.core.legacymaster.LegacyMasterChannel.readMemory(LegacyMasterChannel.java:69)
    at com.altera.systemconsole.scripting.StandardCommandSet.peekMemoryService(StandardCommandSet.java:157)
    ... 9 more

I have never used System Console before and could not find anything related on the Internet or in the manual. So the question is — what wrongdoing am I committing? Any help solving the problem is appreciated.

A: The exception means that you have to pause/stop CPU to execute master_write_32. To keep the CPU running, JTAG to Avalon Master Bridge must be used. It will get exported as another service (i.e. with index 1) and can be used to communicate with Avalon MM component. The credit for an answer goes to guys at Altera's forum.


text: Q: react-native-video player goes in buffer mode and taking long time to laod video. I am using snap carousel library I am using react-native-video with react-native-snap-carousel because I want to show full screen video with vertical scroll like tik-tok. Sometimes videos goes in buffer mode and taking very long time to load video and sometimes it is not loading and if I scroll in between then other video stops loading. Can anyone tell me how to fix it. Releasing video while scrolling will work? If yes how can I release video player. If video is in buffering mode and if it is taking long time to load, is there any way I can resolve it(maybe pause/play video). When it goes in buffering mode, I logged it but after few times log is not printing and even no error.


text:
Q: i want to create a common regex function for AB 1111, A.B 1111,A.B.C. 1111 and A.B. 1111 I tried using
(\D+)[^/](\D+)[\s](\d+)

but I'm not able to exclude the forward slash.

A: You may use
^[A-Z](?:\.?[A-Z])*\.?\s\d+$

See the regex demo.
Details

*

*^ - start of string

*[A-Z] - an uppercase ASCII letter

*(?:\.?[A-Z])* - 0 or more occurrences of an optional . and then an uppercase ASCII letter

*\.? - an optional .

*\s - a whitespace

*\d+ - 1+ digits

*$ - end of string.


text:
Q: How to render png to a HTML canvas in React? Got this error:
'HTMLCanvasElement': Tainted canvases may not be exported.

when I add following 3 lines to mydraw method:
let newImage = new Image()
        newImage.src = 'https://fjolt.com/images/misc/202203281.png'
        ctx.drawImage(newImage, 0, 0, 250, 208)

import React, { useEffect, useRef } from 'react'

const Canvas = (props) => {
    const canvasRef = useRef(null)

    const draw = (ctx) => {
        ctx.fillStyle = '#000000'
        ctx.beginPath()
        ctx.arc(50, 100, 20, 0, 2 * Math.PI)
        ctx.fill()
        let newImage = new Image() // <--- HERE
        newImage.src = 'https://fjolt.com/images/misc/202203281.png'
        ctx.drawImage(newImage, 0, 0, 250, 208)
    }

    useEffect(() => {
        const canvas = canvasRef.current
        const context = canvas.getContext('2d')

        //Our draw come here
        draw(context)
        canvas.toBlob(
            (b) => {
                console.log(b)
            },
            'image/jpeg',
            0.95
        )
    }, [draw])

    return <canvas ref={canvasRef} {...props} />
}

export default Canvas

Strange, bacause I allowed images to use from that domain:
module.exports = {
    images: {
        domains: [
            'https://fjolt.com',
        ],
        deviceSizes: [320, 375, 450, 540, 640, 750, 828, 1080, 1200, 1920],
    },

I tried this approach also, ipired from here: Display Browser Image within Canvas in React
let newImage = new Image()
        newImage.src = 'https://fjolt.com/images/misc/202203281.png'
        newImage.onload = () => {
            ctx.drawImage(newImage, 0, 0, 500, 500)
        }


text:
Q: Why are cellspacing and cellpadding not CSS styles I don't know why this bothers me so much, but when I create websites, I always try to do all my styling with CSS.  However one thing I always have to remember to do when I'm working with tables is add cellspacing="0" and cellpadding="0"
Why is there not a CSS property to override these antiquated HTML 4 attributes?

A: Eric Myer's reset stylesheet contains the following 'reset' style for table :
/* tables still need 'cellspacing="0"' in the markup */
table {
    border-collapse: collapse;
    border-spacing: 0;
}

In addition TD, TR are reset :
thead, tr, th, td {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}

The reason I mention this is that he has a comment 'tables still need cellpadding=0'. I assume he put this in here for a reason - probably needed by some old browsers. Judging by the fact that this is one of the very few comments he included I'm guessing its important and that there's a good reason for it.
Based on this comment - and this comment alone! - i'm continuing to use cellspacing="0" in the markup unless someone tells me definitively (below) why I dont need to. It could however likely be unnecessary in any modern browser worth supporting these days.

A: Cellspacing :
table { border-collapse: collapse; }

As for cellpadding, you can do
table tr td, table tr th { padding: 0; }

A: mat already answered, but just for completeness:

*

*padding → cellpadding

*border-spacing → cellspacing

*border-collapse → no HTML equivalent

It's also worth remembering that you can set separate horizontal and vertical values for the CSS ones e.g. border-spacing: 0 1px.

A: table { border-collapse:collapse; }

A: I guess somebody considered cell spacing a "bad practice". How I understand it is equivalent included in CSS2 standard but IE does not support this property. border-collapse allows to set spacing to 0 value. Cell padding may be achieved setting padding property to TD elements of a table.

A: It's still a shame that cells cannot inherit their default padding from a CSS property of the row (tr), otherwise from rowgroup (thead/tbdy/tfoot) if it's not "initial", colgroup if it's not "initial", or the whole table.
"cellspacing" dos not have this problem (but in fact they are margins around cells, and these outer margins collapse with margins of the neighouring cells, and with the inner paddings of the table/rowgroup or row, where they are filled by the table's "background" setting (the table background also includes the table's "border" which is drawn on top of it and that also clips this background on the outer edge of the table's border, notably when this border has rounded corners).
But for the cellpadding, It would be jut simpler to defined "cell-padding: n" as a table or group property rather than on each cell separately and explicitly with its own "border: n" style (which should only be used if we need to override the padding in some specific cells).


text:
Q: Show that $\sqrt{ab}$ is the limitpoint of the nested interval I already know that positve $a,b$ we have
$\frac{a+b}{2}\geq\sqrt{ab}\geq\frac{2ab}{a+b}$
Given, $0<a<b$ and $I_n=[a_n,b_n]$ with $I_1=[a,b]$ and $I_{n+1}=[\frac{2a_nb_n}{a_n+b_n},\frac{a_n+b_n}{2}]$. I should show that $I_n$ is a nested interval and that the unique Point it converges to is $\sqrt{ab}$.
I have got Problems to show that the Point that it converges to is $\sqrt{ab}$

To show that it is a nested interval I work with induction
I show
$a<\frac{2ab}{a+b}\iff a(a+b)-2ab<0\iff a^2-ab<0\iff a(a-b)<0$. Since $b>a$ this is true.
Also
$b>\frac{a+b}{2}\iff b>a$ which is also true by assumption
The inequality in the middle follows from the Formula above
Inductionstep
I can assume $a_{n}<b_{n}$ The proof for the inductionstep works the same way which means it was not necessary to prove it by induction.
We have proved $I_{n+1}\subset I_n$
Now assume $\epsilon>0$
We have a look at $|I_{n+1}|$
Then $b_{n+1}-a_{n+1}=\frac{a_n+b_n}{2}-\frac{2a_nb_n}{a_n+b_n}=\frac{(a_n+b_n)^2-4a_nb_n}{2(a_n+b_n)}=\frac{a_n^2+2a_nb_n+b_n^2}{2(a_n+b_n)}=\frac{(a_n-b_n)^2}{2(a_n+b_n)}=\frac{(b_n-a_n)^2}{2(a_n+b_n)}=(b_n-a_n)\frac{b_n-a_n}{2(a_n+b_n)}<(b_n-a_n)\frac 1 2$
$\Longrightarrow$
$|I_{n+1}|=b_{n+1}-a_{n+1}<(\frac{1}{2})^n(b-a)<\epsilon$ We know that such an $n$ exists by archimedian property
So $I_n$ is a nested interval

Now I have to prove that $\sqrt{ab}$ is within every interval.
It is true for $I_1$
because
$a<\sqrt{ab}\iff a<b$ and $b>\sqrt{ab}\iff b>a$
The inductionstep is too hard
I have to show
$\sqrt{ab}>\frac{a_n+b_n}{2}$
and
$\sqrt{ab}<\frac{2a_nb_n}{a_n+b_n}$
How can I start?

A: You have
$$
a_{n+1}b_{n+1} = \frac{2a_nb_n}{a_n+b_n} \cdot\frac{a_n+b_n}{2} = a_nb_n \, ,
$$and consequently $a_n b_n = ab$ for all $n$. The inequality between the harmonic/geometric/arithmetic means then shows that
$$
 b_{n+1} = \operatorname{HM}(a_n, b_n) \le \sqrt{ab} \le \operatorname {AM}(a_n, b_n) = a_{n+1}
$$
for all $n$, i.e. $\sqrt{ab} \in I_{n+1}$.
You already showed that the $I_n$ are a sequence of nested intervals with lengths converging to zero, therefore $\sqrt{ab}$ is the unique point contained in all intervals.


text:
Q: Type of item in pandas DataFrame bug or feature? If I have a pandas DataFrame
df = read_csv("infile.csv")

where infile looks something like
i1,i2,f1,f2
3,1,0.1,2.0
2,1,0.3,0.5

i.e. two columns of integers and one of floats.
If I query this DataFrame with:
print type(df["i1"].ix[0])

the type is (as I would expect it too be!) np.int64
Whereas if I use:
print type(df.ix[0]["i1"])

The type is np.float64
Is this correct behaviour or a bug?
I guess that this is because:
df.ix[0]

creates a series object which ["i1"] then selects from? But still this is annoying.

A: As you note yourself, this is indeed expected behaviour because in df.ix[0]["i1"] you first create a Series for the first row (so all items are upcasted to float to get one dtype), and only then you take the item with label "i1"
The solution is easy: don't use this chained indexing, but combine both look-ups (for row and column) in one indexing call:
df.ix[0, "i1"]

There are also other good reasons to avoid this chained indexing (getting problems with view/copy): http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy


text:
Q: ¿Por qué no puedo utilizar un "setter" para establecer el valor de un atributo cuando he instanciado como un vector? Aquí va a lo que me refiero: (Este código me da error)
public class PruebaPOO {

    public static void main(String[] args) {
        // TODO code application logic here

        Multimedia imagenes[] = new Multimedia[5];

        imagenes[1].setNombre("leon"); //Aquí me produce el error
        imagenes[1].setTamaño(20);

        System.out.println(imagenes[1]);
        //System.out.println(imagenes[2]);

    }

}

Esta es la clase Multimedia:
public class Multimedia {

    private String nombre;
    private int tamaño;

    public String getNombre(){
        return this.nombre;
    }

    public int getTamaño(){
        return this.tamaño;
    }

    public void setNombre(String nombre){
        this.nombre = nombre;
    }

    public void setTamaño(int tamaño){
        this.tamaño = tamaño;
    }

    @Override
    public String toString() {
        return "nombre : " + nombre + " / peso : " + tamaño;
    }

}

Por lo contrario esto sí me funciona:
public class PruebaPOO {

    public static void main(String[] args) {
        // TODO code application logic here

        Multimedia imagenes[] = new Multimedia[5];

        imagenes[1] = new Multimedia("leon", 20);

        System.out.println(imagenes[1]);
        //System.out.println(imagenes[2]);

    }

}

public class Multimedia {

    private String nombre;
    private int tamaño;

    Multimedia(String nombre, int tamaño){

        this.nombre = nombre;
        this.tamaño = tamaño;

    }

    @Override
    public String toString() {
        return "nombre : " + nombre + " / peso : " + tamaño;
    }

}

Me da como resultado: nombre : leon / peso : 20
(Que es lo que espero del primer programa.)

A: Buenas al igual que en el segundo caso debes instanciar el objeto. Es decir en tu primer caso (el que no funciona) debes hacer
imagenes[1] = new Multimedia();
imagenes[1].setNombre("Juan") ;
imagenes[1].setTamaño(20);

por lo contrario, estarás intentando acceder a un método de un objeto que es igual a null. Toda clase por defecto tiene un constructor vacío (excepto que tu declares alguno), es por esto que puedes hacer new Multimedia() aunque no esté explícito en la clase.
Cuando haces
  Multimedia imágenes[5] = new Multimedia[5];

simplemente estás creando un vector que referencia a 5 instancias Multimedia, por defecto estas instancias son igual a null. Las debes inicializar cada una.
Actualización
En Java, el índice arranca en 0 y no en 1. Por lo tanto, en un vector de tamaño 5, el índice va desde 0 - 4 (5 elementos en total). Si intentas acceder con  indice = 5 (objeto número seis: imagenes[5]) te va a tirar una excepción indicando que estas por fuera del array.
Asi que si buscas completar tu array desde el principio recuerda arrancar siempre desde 0.
imagenes[0] = new Multimedia(); //primer elemento
imagenes[1] = new Multimedia(); //segundo elemento
imagenes[2] = new Multimedia(); //tercer elemento
imagenes[3] = new Multimedia(); //cuarto elemento
imagenes[4] = new Multimedia(); //quinto elemento
imagenes[5] = new Multimedia(); //error indice fuera de rango!!


text:
Q: Integrate Instamojo Payment Gateway API I tried all the suggestions and tips given by Instamojo for my ASP.net 4.5(C#) application but even I face the problem on this line for
Creating Payment Request.
 PaymentRequest npr = awit im.CreatePaymentRequest(pr);

It shows error on CreatePaymentRequest(pr);
Github link: https://github.com/pkbnaveen/Instamojo.NET


text:
Q: Android Studio navigation xml file can't type keyboard keys MacOS
Android studio version 4.1.1
Navigation:
'androidx.navigation:navigation-fragment-ktx:2.2.2'
'androidx.navigation:navigation-ui-ktx:2.2.2'

Inside the navigation.xml file in split/design screen when adding a New Destination typing the letter 'e' in the searchbox doesn't add it but instead it pops out an Issues window.
Also when pressing 'o' the screens rotate to landscape mode.
I know this is not a huge deal and I found a workaround but would be great to solve it somehow.

A: While in the split/design screen, Android Studio catches your input as keyboard shortcuts. You can either remap/completely delete chosen keys or type only in code screen.
For more info on key mappings in design screen and how to change them, see
Keyboard shortcuts
We can see from the shortcuts docs that the letters(keys)
Toggle between Design and Blueprint modes   B
Toggle between Portrait and Landscape modes O
Toggle devices  D
Force refresh   R
Toggle render errors panel  E
Will generate problems when typing in the split/design screen
UPDATE 28.01.2021
on Android Studio Arctic Fox | 2020.3.1 Canary 4 it seems that in split/design screen you can type without any shortcut catches as long as you are focused on the code part. If you change  your focus on design, shortcuts are working again


text:
Q: Laravel Forge 500 Internal Server Error I have updated the git repository (developer branch - this is the only branch on the repo) and deploy on Forge but I am getting 500 Internal Server Error
.env configurations are correct (database, username, password and other configs.)
Also, PHP version on the server is 7.2 and this same site has worked before When I made the last push (changes: routes and controller functions) it started showing the error.
I read this question but even after following these steps the 500 error is showing!
Any suggestion how can I solve this issue!?
PS: I am new to Forge!

A: i know this is a very late reply i had the same issue
check your routes something is conflicting


text:
Q: Using JWT for Authorization in Node So I've been following a Udemy course that uses POSTMAN to teach authentication, but I have been wonder how it works in an actual app that uses the browser. We are taught to store the JWT token with res.header('x-auth-token', token). And then when we try to access a route that is protected, we manually add the token in POSTMAN header and get the token with req.header('x-auth-token') on the server and verify the token.
But in a real app, I logged in using the browser and it did indeed set the header up with a token, but once I type in the URL to go into the restricted/authenticated required path, lets say /user/profile, it asks for me to log back in. Is the token not carrying over when I type in the new URL?
How do I get it so the token is carried around in the browser till it expires?

A: Similar to how you manually add the token in every request with POSTMAN, your client side application needs to handle (Obviously in coordination with server side ) how you send the token to server. It will not be carried on every request automatically. You need to store the JWT token returned by the server.
If you store the JWT token in a cookie, then browser will send token every time you make a request. But it is also recommended to not use a cookie. Check various ways on how to store the JWT token in the client side and how to repeatedly add the token on every future requests until logout. There is also a concept of refresh token to get a new token in case the token is expired.
Check the below blogs to get more information. You can find other resources on the internet as well.
https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/
https://blog.nextzy.me/implementing-json-web-token-jwt-to-secure-your-app-c8e1bd6f6a29


text:
Q: Pass and get parameters in react navigation 5 how can I pass and get parameters in react navigation?
I have tried
 this.props.navigation.getParams('name',defaultValue)

to get the parameter.

A: get param:
const name = props.route.params.name

pass params:
navigation.navigate({
  name: 'RouteName',
  params: {
      name: 'nameParam'
  }
})

or:
navigation.navigate('RouteName', {name: 'nameParam'})


text:
Q: Visual Studio Configuraiton manager Deploy column disabled I am having a problem with the configuration manager in Visual Studio 2013.  The Deploy column is disabled no.  The only thing I did was a Repair of Visual Studio 2013 and not my WebAPI project not longer has the Deploy option enabled in Configuration Manager.  I used to be able to do a file system deploy to the folder on the Web Server that hosted my WebAPI process.  I am not sure what is going on.  Any assistance would be greatly appreciated.
FYI - The CGSAPI project type is class library but that is what it has always been.

A: OK so I was just being silly.  I have to right mouse button click on the actual WebAPI project and Publish will be available in the dropdown list. :)


text:
Q: Anime in which a man wields a gun loaded with different-coloured shells, each action scene is preceded by a pumping heart clip So this is when I was still quite young so it might not be accurate.
The details I could vividly remember is this man's weapon, it is sort of a gun.
Before his epic action scene, there will always be a heart pumping scene and some mechanical stuff starts running.
He will load the gun with 3 different colour tubes (and starts describing them) into the gun and fire one very strong projectile to kill the enemy.

A: Sounds like Final Fantasy: Unlimited, where the character Kaze wields the Magun, a gun capable of summoning monsters. Each time he fires it, the gun "unfolds" in a transformation sequence, then he picks three cartridges of colored "soil" whose signification he explains before firing the gun.
At various points in the sequence, the gun is shown to have a beating heart, which is shown beating faster in the last plan just before it fires.
There are a few examples of it being used in this YouTube clip:


text:
Q: How to swap out child of a gameobject in Unity? I want my player to pick up a gun prefab that is a dropped item then swap the old gun for a new gun. Current structure looks like this:

So the idea is my player picks up the prefab on the ground:

This what I tried. My idea was to instantiate a child to the player then somehow remove the Gun child and place the new gun in the same position. The fire point is already a child of my new prefab. So I just need to swap the two. The following script would be added to the drop on the ground.
public class WeaponPickUp : MonoBehaviour
{

    public GameObject launcher;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    void  OnCollisionEnter2D(Collision2D col){
         if(col.gameObject.name =="Player"){

            GameObject go = Instantiate(launcher, new Vector3(0,0,0), Quaternion.identity) as GameObject;
            go.transform.parent = GameObject.Find("Player").transform;
            Destroy(gameObject);
        }
    }

}

Any ideas where to go from here? I'd really appreciate any kind of feedback.

A: You don't need to find the Player game object because the collision already detected it, and you can get the location of the gun you are replacing to use as the position for the new gun:
void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.name == "Player")
    {
        Vector3 spawnPosition = col.transform.GetChild(0).position;
        Destroy(col.transform.GetChild(0).gameObject);
        Instantiate(launcher, spawnPosition, Quaternion.identity, col.transform);
        Destroy(gameObject);
    }
}

A: Attach script to your player. In Scene view adjust your gun position and the make the prefab that's it.
  public GameObject gunPrefab;
     void  OnCollisionEnter2D(Collision2D col){
        if(col.gameObject.name =="gun"){
           Instantiate(gunPrefab, transform); //Instantiate(prefab, parent);
           Destroy(col.gameObject);
        }
}


text:
Q: Factoring business growth into linear regression I am looking to run a pretty basic linear regression in excel with the products price as the Independent Variable and QTY sold as the Dependent variable. I have 5 years of sales data with each row showing month of month growth.
The issue is our company has been in a steady state of growth over that time, 50%, 30%, 40%, and 25% from 2015 to 2019.
Is there anyway to factor this organic growth into the regression?
Thanks
Weekly Data

A: To get the Regression, first check whether Regression Add In is added or not, if not then do the following.
Step 1:

*

*Hit File, Option, Add In.

*Select the Analysis ToolPak & click Go, finish
with Ok.

Step 2:

*

*Hit Data tab then select Data Analysis.

*Find the Regression option and click OK.

*Next is data selection, hit the Input Y Range
box and then select dependent variable.

*For Input X Range select independent variable
data.

*Select Output Range.

*If Required you may select either residual or
probability graph.

*Click OK to finish


text:
Q: how to resolve the error "ADMIN option not granted for role 'my_role_1'" I am trying to grant a role to user.
grant my_role_1 to ktest1 with admin option;

But i am getting the below error
Error report - ORA-01932: ADMIN option not granted for role 'my_role_1'
01932. 00000 -  "ADMIN option not granted for role '%s'
*Cause:    The operation requires the admin option on the role.
*Action:   Obtain the grant option and re-try.

I have also tried the below statement. Still i am getting the same error. I am able to grant different roles but only with this role i am getting this error.
grant my_role_1 to ktest1;

A: You do not have the admin option yourself on my_role_1, so you cannot grant the role to other users. Get your DBA to grant the admin option for my_role_1 to you and you will be then be able grant the role to ktest1.


text:
Q: Add username token to Axis2 Web service (Which is not running in axis 2 engine) I have created a web service using Maven2 WSDL2Code Plug-in in axis.
    https://axis.apache.org/axis2/java/core/tools/maven-plugins/maven-wsdl2code-plugin.html

    Which create a .war file as build result and which is running on the tomcat server and it does not need to deploy into axis2 engine. Since I have done a mapping in "web.xml" file as bellow.

    -web.xml-

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
      <display-name>MavenAxis2WS</display-name>
      <servlet>
        <servlet-name>AxisServlet</servlet-name>
        <servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>AxisServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
      </servlet-mapping>
    </web-app> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">
      <display-name>MavenAxis2WS</display-name>
      <servlet>
        <servlet-name>AxisServlet</servlet-name>
        <servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>AxisServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
      </servlet-mapping>
    </web-app>

-services.xml-

<module ref="rampart"/>
<wsp:Policy wsu:Id="UsernameTokenOverHTTPS" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
        <wsp:ExactlyOne>
          <wsp:All>
            <sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
              <wsp:Policy>
                <sp:TransportToken>
                  <wsp:Policy>
                    <sp:HttpsToken RequireClientCertificate="false"/>
                  </wsp:Policy>
                </sp:TransportToken>
                <sp:AlgorithmSuite>
                  <wsp:Policy>
                    <sp:Basic256/>
                  </wsp:Policy>
                </sp:AlgorithmSuite>
                <sp:Layout>
                  <wsp:Policy>
                    <sp:Lax/>
                  </wsp:Policy>
                </sp:Layout>
                <sp:IncludeTimestamp wsp:Optional="true"/>
              </wsp:Policy>
            </sp:TransportBinding>
            <sp:SignedSupportingTokens xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
                <wsp:Policy>
                    <sp:UsernameToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient" />
              </wsp:Policy>
            </sp:SignedSupportingTokens>
            <ramp:RampartConfig xmlns:ramp="http://ws.apache.org/rampart/policy">
                <ramp:passwordCallbackClass>security.rampart.PWCBHandler</ramp:passwordCallbackClass>
            </ramp:RampartConfig>
          </wsp:All>
        </wsp:ExactlyOne>
    </wsp:Policy>

So here; to where should I put the Rampart module (Since I don't use Axis2.war here)?
Is there any maven dependencies that I can use here for Rampart module?


text:
Q: Karate API Testing - How do i read the response and validate from another service consuming the messages from the queue - see diagram below We have multiple services posting and consuming from multiple Rabbit queues. I want to post my request from the first service and read the response generated by the last service and validate that in Karate API test framework.
Here is the flow of the application -
my feature post to rest service -> message queue1 -> consumed by service 2 -> message queue -> consumed by service 3 and a response is generated (I want to read and assert this response in my feature)
here is the image with the flow of services and message queues in between

A: Yes, use Java interop and write some custom code (one time). Here's an example that should answer all your questions, including how to handle async events: https://stackoverflow.com/a/69406420/143475
Also see: https://stackoverflow.com/a/55235584/143475


text:
Q: how to change background of button on every click I am working on music app
so I am trying to do a button when I click it the song
be repeating and the background change
I have two background one of them I want to make it background of the button
when play the song once
and the another when the song is repeating
    package khaledbanafa.shaylat;
    import android.media.MediaPlayer;
    import android.os.Build;
    import android.support.annotation.RequiresApi;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.RelativeLayout;
    import android.widget.SeekBar;
    import android.widget.TextView;
    import android.widget.ToggleButton;
    import java.io.IOException;
    import static android.app.PendingIntent.getActivity;
    import static khaledbanafa.shaylat.R.drawable.play;
    public class ha extends AppCompatActivity {
    MediaPlayer x;
    RelativeLayout mylayout;
    TextView textView;
    TextView textView2;
    TextView textView3;
    SeekBar seekBar;
    boolean pressed = false;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_on);
        final Button a = (Button) findViewById(R.id.button1);
        a.setText("ارفع الراس يا حربي");
        final Button b = (Button) findViewById(R.id.button2);
        b.setText("سما سما");
        final Button c = (Button) findViewById(R.id.button3);
        c.setText("الحربي للحربي فدا");
        final Button d = (Button) findViewById(R.id.button4);
        d.setText("العبو ياحرب دام العمر فاني");
        final Button e = (Button) findViewById(R.id.button5);
        e.setText("حرب الحرايب");
        final Button f = (Button) findViewById(R.id.button6);
        f.setText("حرب الحرايب لحن دحة");
        final Button g = (Button) findViewById(R.id.button7);
        g.setText("حرب الدول");
        final Button h = (Button) findViewById(R.id.button8);
        h.setText("حرب ماتنقص تزود");
        final Button i = (Button) findViewById(R.id.button9);
        i.setText("حنا اهل الفخر");
        final Button j = (Button) findViewById(R.id.button10);
        j.setText("ياحرب شوشو والعبو");
        Button play = (Button) findViewById(R.id.buttonplay);
        Button pause = (Button) findViewById(R.id.buttonpause);
        Button stop = (Button) findViewById(R.id.buttonstop);
        final Button repeat = (Button)findViewById(R.id.repeat);
        Button nextmedia = (Button)findViewById(R.id.nextmedia);
        textView = (TextView)findViewById(R.id.textView);
        textView2 = (TextView)findViewById(R.id.textView2);
        textView3 = (TextView)findViewById(R.id.textView3);
        seekBar = (SeekBar)findViewById(R.id.seekBar);

        final SeekBar SEK = new SeekBar(ha.this);
        SEK.setPadding(150,0,140,0);
        SEK.setX(0);
        SEK.setY(1659);
        SEK.setProgressDrawable(getDrawable(R.drawable.red_scrubber_progress));
        SEK.setThumb(getDrawable(R.drawable.red_scrubber_control));
        mylayout = (RelativeLayout)findViewById(R.id.onrel);
        SEK.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(x != null)
                    x.start();
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(x != null)
                x.stop();
                textView.setText("");
                mylayout.removeView(SEK);
                mylayout.addView(SEK);
                SEK.setProgress(0);
                SEK.setMax(0);

            }
        });
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(x != null)
                x.pause();
            }
        });

        a.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);
                mylayout.removeView(SEK);
                stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.haone);
                class mythread extends Thread {
                    public void run() {
                        while (x != null) {
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e) {
                            }
                            SEK.post(new Runnable() {
                                @Override
                                public void run() {
                                    SEK.setProgress(x.getCurrentPosition());
                                    int tim = (SEK.getMax() / 1000);
                                    int m = tim / 60;
                                    int s = tim % 60;
                                    /////////
                                    int tim0 = (SEK.getProgress() / 1000);
                                    int m0 = tim0 / 60;
                                    int s0 = tim0 % 60;
                                    textView2.setText(m0 + ":" + s0);
                                    textView3.setText(m + ":" + s);
                                }
                            });
                        }
                    }
                }
                SEK.setMax(x.getDuration());
                mythread my = new mythread();
                textView.setText(a.getText());
                mylayout.addView(SEK);
                my.start();
                x.start();

                        SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });}
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.hatwo);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(b.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });
            }
        });

        c.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.hathree);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(c.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
        d.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.hafour);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(d.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
        e.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.hafive);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(e.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });

        f.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.hasix);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(f.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
        g.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.haseven);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(g.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
        h.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.haeight);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(h.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
        i.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.hanine);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(i.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
        j.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying();
                x = MediaPlayer.create(ha.this, R.raw.haten);class mythread extends Thread {
                    public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {}
                        SEK.post(new Runnable() {
                            @Override
                            public void run() {
                                SEK.setProgress(x.getCurrentPosition());
                                int tim = (SEK.getMax()/1000);
                                int m = tim/60;
                                int s= tim %60;
                                /////////
                                int tim0 = (SEK.getProgress()/1000);
                                int m0 = tim0/60;
                                int s0 = tim0%60;
                                textView2.setText(m0+":"+s0);
                                textView3.setText(m+":"+s);}});}}}
                SEK.setMax(x.getDuration());mythread my = new mythread();
                textView.setText(j.getText());
                mylayout.addView(SEK);
                my.start();x.start();
                SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    int progresval;
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        progresval = progress;}
                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}
                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {
                        x.seekTo(progresval);
                    }
                });

            }
        });
    }

    public void onDestroy(){
        super.onDestroy();
        if(x != null)
        x.stop();

    }

    private void stopPlaying() {
        if (x != null) {
            x.stop();
            x.release();
            x = null;

        }
    }

}

A: you can get repeat state from your mediaPlayer
repeat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(x != null ){
                if ( x.isLooping()) {
                    //player is in repeat mode , so turn it off and change repeat buttun background to normal
                    repeat.setBackgroundResource(R.drawable.repeat_off);
                    x.setLooping(false);
                }else {
                    //player isn't in repeat mode , so turn it on and change repeat buttun background to repeating image
                    repeat.setBackgroundResource(R.drawable.repeat_on);
                    x.setLooping(true);
                }
            }else {
                //player is null
            }
        }
    });

note that setLooping just set repeat mode for your media player so if your x (media player) is not playing you can also set x.start() or x.resume() base on your player state.

A: You might find your answer in this post: How set background drawable programmatically in Android
As you are dealing with button, check out this this interesting link : https://developer.android.com/reference/android/widget/Button.html
In order to detect when the background changes. I advise you to implementing a class which extends MediaPlayer and use it. You should implement an public interface iinside your activity in order to observe the change of backgrounds.


text:
Q: Ordering result over non-trivial expression I have a posts/comments database that I am unable to order correctly.
I need it to be ordered primarily by its id but if its parent_id does not equal its id, it is placed after its parent and also these children would ordered by id.
Here is my current database.
CREATE TABLE `questions` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) NOT NULL,
  `entry_type` varchar(8) NOT NULL,
  `entry_content` varchar(1024) NOT NULL,
  `entry_poster_id` varchar(10) NOT NULL,
  `entry_status` varchar(1) NOT NULL,
  `entry_score` varchar(10) NOT NULL,
  `time_posted` varchar(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `questions`
--

INSERT INTO `questions` VALUES(1, 1, 'question', 'How do I does SQL?', 'CodyC', '0', '2', '1308641965');
INSERT INTO `questions` VALUES(2, 1, 'answer', 'Easy, you eat cheese!', 'PatrickS', '0', '-4', '1308641965');
INSERT INTO `questions` VALUES(3, 2, 'comment', 'WTF are you on noobass?!', 'FraserK', '0', '100', '1308641965');
INSERT INTO `questions` VALUES(4, 1, 'answer', 'blah', '5', '0', '0', '1308642204');
INSERT INTO `questions` VALUES(5, 4, 'comment', 'blah2', '4', '0', '0', '1308642247');
INSERT INTO `questions` VALUES(6, 2, '2', '3', '3', '3', '3', '3');

and my current query
SELECT *
FROM questions
WHERE parent_id =1
OR parent_id
IN (
    SELECT id
    FROM questions
    WHERE parent_id =1
    AND parent_id != id
)

how do I order so that order id to that each object comes after its parent, where the id = parent_id means is a base level and has no parent?

A: This seems to work:
SELECT *
FROM questions
order by case when parent_id != id then parent_id else id end, id;

But it depends whether you want grandchildren before children etc. Your question doesn't specify.
However, if you use this technique you can make your ordering term(s) as complicated as you like - it doesn't need to be a selected column - just make up what you need.

A: Looks a bit complicated with mysql, but you can use PHP for it.  Use recursive function.  This will be easy to handle.
here is a function from code bank.  It simply creates a unorder list tree.  You can modify it to suit your requirments
function output_lis_pages($parentID = 0)
{
    $stack = array(); //create a stack for our
's

    $arr = array();
    $sql = "select pageid, pagetitle, pagelink, parentid
        from pages
        where parentid =  $parentID
        order by orderid";

    $crs = mysql_query($sql);

    if(mysql_num_rows($crs)==0)
    {
            // no child menu exists for this page
            return false;
    }
    else
    {
            while($crow = mysql_fetch_array($crs))
            {
                $arr [] =  array(
                    'pagetitle'=> stripslashes($crow["pagetitle"]),
                    'pagelink'=> $crow["pagelink"],
                    'parentid'=>$crow["parentid"],
                    'pageid'=>$crow["pageid"]
                    );
            }
    }

    foreach($arr as $a)
    {
            $str = '';
                    //if the item's parent matches the parentID we're outputting...
            if($a['parentid']==$parentID)
            {
                if($a['pagelink']=="")
                        $tmplink = "page.php?pageid=".$a['pageid'];
                else
                        $tmplink = $a['pagelink'];

                $str.='
'.$a['pagetitle']."";

                $subStr = output_lis_pages($a['pageid']);

                if($subStr){
                        $str.="\n".'
'.$subStr.'
'."\n";
                }

                $str.='
'."\n";
                $stack[] = $str;
            }
    }
    //If we have
's return a string
    if(count($stack)>0)
    {
            return  join("\n",$stack);
    }

    //If no
's in the stack, return false
    return false;
}

A:     SELECT *
         , CASE WHEN parent_id = 1 THEN id ELSE parent_id END AS sort_level
    FROM questions
    WHERE parent_id = 1
       OR parent_id
          IN (
              SELECT id
              FROM questions
              WHERE parent_id = 1
                AND parent_id != id
             )
    ORDER BY sort_level
           , id

A: You've run into the old bugbear of relational database systems. They aren't fun to work with when your data is hierarchic. You have the issue of trying to produce what is really a particular walk of a graph from database records. That is tough without recursive features in your SQL dialect. Here is a link that might help:
http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/
See also, on StackOverflow: What are the options for storing hierarchical data in a relational database?

A: looking into your question and reading your comment - "i need to get ONE specific question, with ALL the answers and comments", I think you are looking to show every question followed by its answer followed by its comments. Right?
And if so, this is your query:
SELECT `id`,
(CASE
    WHEN `entry_type` = 'question' THEN CONCAT(`id`, '-', `parent_id`)
    WHEN `entry_type` = 'answer' THEN CONCAT(`id`, '-', `parent_id`)
    WHEN `entry_type` = 'comment' THEN CONCAT(`parent_id`, '-', `id`)
END) `sort_order`,
`entry_type`, `entry_content`
FROM `questions`
ORDER BY `sort_order`;

The above query will give you every question, followed by its first answer, followed by the comments to its first answer; then the second answer, followed by the comments to the second answer and so on.
So for the INSERTs that you had given, this will be the output:
+----+------------+------------+--------------------------+
| id | sort_order | entry_type | entry_content            |
+----+------------+------------+--------------------------+
|  1 | 1-1        | question   | How do I does SQL?       |
|  2 | 2-1        | answer     | Easy, you eat cheese!    |
|  3 | 2-3        | comment    | WTF are you on noobass?! |
|  6 | 2-6        | comment    | 3                        |
|  4 | 4-1        | answer     | blah                     |
|  5 | 4-5        | comment    | blah2                    |
+----+------------+------------+--------------------------+

Hope it helps.
EDIT: Updated query to fetch answers and comments for only ONE question
SELECT `id`,
(CASE
    WHEN (`entry_type` IN ('question', 'answer')) THEN `id`
    WHEN `entry_type` = 'comment' THEN `parent_id`
END) `sort_order_1`,
(CASE
    WHEN (`entry_type` IN ('question', 'answer')) THEN `parent_id`
    WHEN `entry_type` = 'comment' THEN `id`
END) `sort_order_2`,
(CASE
    WHEN (`entry_type` IN ('question', 'answer')) THEN `parent_id`
    WHEN `entry_type` = 'comment' THEN (SELECT `Q1`.`parent_id` FROM `questions` `Q1` WHERE `Q1`.`id` = `Q`.`parent_id`)
END) `question_id`,
`entry_type`, `entry_content`
FROM `questions` `Q`
HAVING `question_id` = 1
ORDER BY `sort_order_1`, `sort_order_2`;

OUTPUT:
+----+--------------+--------------+-------------+------------+--------------------------+
| id | sort_order_1 | sort_order_2 | question_id | entry_type | entry_content            |
+----+--------------+--------------+-------------+------------+--------------------------+
|  1 | 1            | 1            |           1 | question   | How do I does SQL?       |
|  2 | 2            | 1            |           1 | answer     | Easy, you eat cheese!    |
|  3 | 2            | 3            |           1 | comment    | WTF are you on noobass?! |
|  6 | 2            | 6            |           1 | comment    | 3                        |
|  4 | 4            | 1            |           1 | answer     | blah                     |
|  5 | 4            | 5            |           1 | comment    | blah2                    |
+----+--------------+--------------+-------------+------------+--------------------------+

You can change the HAVING part to fetch answers and comments for a specific question. Hope this helps!
EDIT 2: another possible implementation might be (but I think it might have some performance implications for large tables):
SELECT `a`.`id` AS `question_id`, `a`.`entry_content` AS `question`,
    `b`.`id` AS `answer_id`, `b`.`entry_content` AS `answer`,
    `c`.`id` AS `comment_id`, `c`.`entry_content` AS `comment`
FROM `questions` `a`
LEFT JOIN `questions` `b` ON (`a`.`id` = `b`.`parent_id` AND `b`.`entry_type` = 'answer')
LEFT JOIN `questions` `c` ON (`b`.`id` = `c`.`parent_id` AND `c`.`entry_type` = 'comment')
WHERE `a`.`entry_type` = 'question'
AND `a`.`id` = 1
ORDER BY `a`.`id`, `b`.`id`, `c`.`id`;

OUTPUT:
+----+--------------------+------+-----------------------+------+--------------------------+
| id | question           | id   | answer                | id   | comment                  |
+----+--------------------+------+-----------------------+------+--------------------------+
|  1 | How do I does SQL? |    2 | Easy, you eat cheese! |    3 | WTF are you on noobass?! |
|  1 | How do I does SQL? |    2 | Easy, you eat cheese! |    6 | 3                        |
|  1 | How do I does SQL? |    4 | blah                  |    5 | blah2                    |
+----+--------------------+------+-----------------------+------+--------------------------+

A: After a week of trying i could not get it to work with the query, so i decided just to do it in PHP, this will also reduce load off the MySQL engine. Here is my php for anyone that wishes to reference it.
$question_id = $database->escape_string($question_id); //escape input
$q = "SELECT * FROM questions WHERE parent_id = $question_id OR parent_id IN (SELECT id FROM questions  WHERE parent_id = $question_id AND parent_id != id) ORDER BY parent_id , id";
$database->dbquery($q);//query the DB
while($row = $database->result->fetch_assoc()){//Process results to standard array.
    //other irrelevant stuff happens here
    $unsorted[] = $row;
}
$question = array_shift($unsorted);//take the question off the array
$sorted[] = $question;//add it to the start of the sorted array
$qusetion_id = $question['id'];
foreach($unsorted as $row){//this creates a multidimensional hierarchy of the answers->comments
    if($row['parent_id'] == $question_id){//if its an answer
        $sorted_multi[$row['id']] = array();//create a new answer sub-array
        $sorted_multi[$row['id']][] = $row;//append it
    }else{
        $sorted_multi[$row['parent_id']][] = $row;//append the answer to the correct sub-array
    }
}
foreach($sorted_multi as $temp){//converts the multidimensional into a single dimension appending it to the sorted array.
    foreach($temp as $row){
        $sorted[] = $row;
    }
}

Tedious yes, but it works out better in the end because of other unforeseen processing that needs to be done post-mysql.
Thanks for all the responses though :):):)

A: Simply use the "ORDER BY" clause to select the ordering you want!

SELECT *
    FROM questions
    WHERE parent_id =1
    OR parent_id
    IN (
        SELECT id
        FROM questions
        WHERE parent_id =1
        AND parent_id != id
    )
    ORDER BY Parent_id , id


text:
Q: Sorting tableView data by timestamp with firebase I'm looking to sort the data / arrays in my tableView by which date it was created. I don't have any code to support this but I have the code for the cells and images from the database.
Database.database().reference().child("Projects").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String : AnyObject]
            {
                let project = Project(dictionary: dictionary)
                self.ProjectsArray.append(project)

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
            else
            {
                print("fucked ")
            }
            self.FilterdProjectsArray = self.ProjectsArray
        }, withCancel: nil)

Database

A: You just need to add one line:
self.ProjectsArray.append(project)
self.ProjectsArray = self.ProjectsArray.sorted { (lhs, rhs) in lhs.timestamp < timestamp }

where date is the name of the date property on your Project object
Update
You could extend Optional to conform to Comparable, but a simpler way to handle it might be:
self.ProjectsArray = self.ProjectsArray.sorted { (lhs, rhs) in
    let lTimestamp = lhs.timestamp ?? NSNumber(integerLiteral: 0)
    let rTimestamp = rhs.timestamp ?? NSNumber(integerLiteral: 0)
    return lTimestamp < rTimestamp
}

Update 2
Turns out that NSNumbers aren't comparable. Looks like you'll need to use Int or Double, whichever makes more sense for your data (are you using whole or floating-point numbers?
self.ProjectsArray = self.ProjectsArray.sorted { (lhs: Project, rhs: Project) in
    let lTimestamp: Int
    if let lNum = lhs.timestamp {
      lTimestamp = Int(lNum)
    } else {
      lTimestamp = 0
    }

    let rTimestamp: Int
    if let rNum = rhs.timestamp {
      rTimestamp = Int(rNum)
    } else {
      rTimestamp = 0
    }
    return lTimestamp < rTimestamp
}


text:
Q: How to Run Git commands on Netbeans 8.0.2 I want to run some git commands locally to clean up some stuffs. I am on Windows and i am unable to use the netbeans terminal. Git command is not recognized. So my question is i there is a way to run
   git rm *.exe

or some other commands. I don't want to use GUI of Netbeans here.

A: Sure; unzip the archive PortableGit-2.7.4-64-bit.7z.exe anywhere you want, add its folder (/bin) to your %PATH%, and git will be recognized.
Go to the root folder of your git repo, and do a git status to check that git is working.


text:
Q: Android WebView: use firefox/gecko browser engine on Lineage OS On Lineage OS (and maybe on any Android?), it is possible to change the default WebView render (which is set by default to AOSP Browser, the default android browser without GAPPS). When I install Chrome (even without GAPPS installed), I can change this default to Chrome in the Setting/Development (which is practical in my case as the default browser has some annoying bugs).
Is it possible to also use Firefox's engine instead of Browser/Chrome (I don't want to have chrome installed and rely on proprietary software)? Installing Firefox (Fennec on FDroid) is not enough.
Thanks!

A: Besides the common Chrome WebView, there's also Mozilla GeckoView.
The quick start shows how it can be added - and there's also an example app.
The down-side is, that geckoview-70.0.20191022130254.aar has 149.8 MB.
This would be it's API documentation and it's home on GitHub.

A: This is not possible because GeckoView does not implement the WebView API according to one of the authors.
https://github.com/mozilla/geckoview/issues/167#issuecomment-902022285


text:
Q: How to do binding of a grid using mvvm to render UI elemnts on it I am a c# Silverlight beginner and i am using silverlight5 with MVVM approach.
What i have to do ?
I have created a xaml suppose  this :
<UserControl x:Class="DEV_CENTER.TabControlStuff.UIeLementRender"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">

     </Grid>
</UserControl>

Now i want to bind this grid to a viewModel class which will render a grid containing combobox on it . How to do that ?
I tried adding "{Binding UIElements}" by changing grid like this
 <Grid x:Name="LayoutRoot" Background="White" {Binding UIElements}>

which is ofcourse not supported.
So how to bind this grid to render UIElemnts on it (combo box) using MVVm approach ?
EDIT : Situation is that i have a grid which already contain a Combobox (obtained dynamically using c# code) and that grid i want to render on a grid(this grid is default grid obtained on creating xaml)(by binding using MVVM i have to render the previously obtained grid (using c# ,containign combobox) by binding it to this xaml degault created grid using MVVM by doing something like {Binding  AlreadComboContainingGrig}).
Whereas my ViewModel class which will be binded will look like this :
 public class uiElementRendererViewModel : GenericViewModel
    {

        private Grid alreadComboContainingGrig;
        public Grid AlreadComboContainingGrig
        {
            get { return alreadComboContainingGrig; }
            set { alreadComboContainingGrig= value; OnPropertyChanged("AlreadComboContainingGrig"); }
        }
    }

Is it possible ? If not then could u please tell me any alternative ?Thanks .

A: Probably the best way is to have container element in outer Grid, such as ContentController or Frame as placeholder, and bind it's content to inner Grid.
Something like this in XAML:
<Grid Name="GlobalGrid">
   <ContentControl Name="ComboGridPlaceholder" Content = "{Binding alreadComboContainingGrig}"/>
</Grid>

The only thing remains is not to forget setting correct DataContext for ComboGridPlaceholder.


text:
Q: Invalid parameter number - PHP Estou usando o mesmo código que uso para fazer o UPDATE de outra tabela do meu banco, mas quando uso o código para a tabela post de meu banco da o erro, A unica coisa que está alterando é a imgem.
Não faço ideia porque não está funcionando pois é o mesmo código
Fatal error: Uncaught PDOException:
  SQLSTATE[HY093]: Invalid parameter number: number of bound variables
  does not match number of tokens in C:\RR\admin\edit_post.php:75
    Stack trace:
      #0 C:\RR\admin\edit_post.php(75): PDOStatement->execute()
      #1 {main} thrown in C:\RR\admin\edit_post.php on line 75

o código é
<?php

error_reporting( ~E_NOTICE );
error_reporting(E_ERROR | E_PARSE);
require_once 'dbconfig.php';

if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
    $id = $_GET['edit_id'];
    $stmt_edit = $DB_con->prepare('SELECT titulo,descricao,texto,img FROM posts WHERE id =:uid');
    $stmt_edit->execute(array(':uid'=>$id));
    $edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
    extract($edit_row);
}
else
{
    header("Location: painel_posts.php");
}

if(isset($_POST['btn_save_updates']))
{
    $titulo = $_POST['titulo'];
    $descricao = $_POST['descricao'];
    $texto = $_POST['texto'];

    $imgFile = $_FILES['user_image']['name'];
    $tmp_dir = $_FILES['user_image']['tmp_name'];
    $imgSize = $_FILES['user_image']['size'];

    if($imgFile)
    {
        $upload_dir = 'posts_images/'; // upload directory
        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
        $userpic = rand(1000,1000000).".".$imgExt;
        if(in_array($imgExt, $valid_extensions))
        {
            if($imgSize < 5000000)
            {
                unlink($upload_dir.$edit_row['img']);
                move_uploaded_file($tmp_dir,$upload_dir.$userpic);
            }
            else
            {
                $errMSG = "Imagem grande demais, max 5MB";
            }
        }
        else
        {
            $errMSG = "Imagens apenas nos formatos JPG, JPEG, PNG & GIF files are allowed.";
        }
    }
    else
    {
        // if no image selected the old image remain as it is.
        $userpic = $edit_row['img']; // old image from database
    }

    // if no error occured, continue ....
    if(!isset($errMSG))
    {
        $stmt = $DB_con->prepare('UPDATE posts
                                     SET titulo=:utitulo,
                                         descricao=:udescricao,
                                         texto=:utexto,
                                         img=:upic
                                   WHERE id=:uid');
        $stmt->bindParam(':utitulo',$titulo);
        $stmt->bindParam(':udescricao',$descricao);
        $stmt->bindParam(':utexto',$texto);
        $stmt->bindParam(':upic',$userpic);

        if($stmt->execute()){
            ?>
            <script>
            alert('Post Atualizado ...');
            window.location.href='painel_posts.php';
            </script>
            <?php
        }
        else{
            $errMSG = "Sorry Data Could Not Updated !";
        }

    }

}

A: No seu update está faltando definir o id, precisa inserir essa linha antes de executar:
$stmt->bindParam(':uid',$id);


text:
Q: How to write Db in Wordpress? I have written a custom query to retrieve data in WordPress and it works fine in my local so when I move to the real environment its syntax will be like?
$dbconnect =  mysqli_connect('localhost','root','','goldenstatecanna');
$query = mysqli_query($dbconnect,"SELECT *
FROM wp_terms JOIN wp_termmeta
WHERE wp_terms.term_id = wp_termmeta.term_id
and wp_termmeta.meta_key = \"display_type\"
and wp_termmeta.meta_value != \"subcategories\"");
Need to know how to write that with Wordpress Syntax

A: You can use the wpdb Class, this global WordPress class is key for using queries. In fact, every function uses this class.
$query = "SELECT COUNT(apple) FROM fruits";
$wpdb->query($query);

A: You can achieve this by this code
  global $wpdb;

    $querystr = "
    SELECT *
    FROM $wpdb->terms termss JOIN $wpdb->termmeta termssmeta
    WHERE termss.term_id = termssmeta.term_id
    AND termssmeta.meta_key = 'display_type'
    AND termssmeta.meta_value != 'subcategories' ";

    $dataa = $wpdb->get_results($querystr);
    print_r($dataa);

You can also refer this https://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query

A: You should declare $wpdb as global before use it. It does work as an ORM for the Wordpress application, and there is a very extensive documentation about it, take a look, https://codex.wordpress.org/Class_Reference/wpdb


text:
Q: Max requests in IIS Does anyone know if there is a maximum number of concurrent requests for IIS (Specifically IIS 7), I understand that there is a maximum number of threads so this will limit the max number of concurrent requests. Is this true?

A: In IIS 7.0 you can limit your web site usage by setting the following values:
Bandwith usage (maxBandwidth)
Connection (maxConnections)
Connection time-out (connectionTimeout)

The connection limit specifies the maximim number of permitted connections for a particular website. By limiting connections to Web sites, you can effectively allocate system resources.You can set all three limits from a single dialog box in IIS manager(inetmgr). Connection limit can range from 0 to 4294967295.