text:
Q: error con Xampp MySQL shutdown unexpectedly Anteriormente se abría sin problema ¡Hola! De la noche a la mañana, el servicio de mysql de mi Xampp no se inicia. No uso Skype ni similares. Apache sí se inicia perfectamente.
El netstat del propio Xammp me muestra como old socket la conexión de mysql en la ip 0.0.0.0 puerto 3306. Nombre: mysqld.exe.
También he comprobado que esté libre con la cmd de windows. Y,efectivamente, no está en uso. También he probado a cambiar el puerto a 3307 tanto en la configuración del propio mysql (my.ini) como en la configuración del propio Xampp en  la sección de "Service and  Port Settings".
Y seguía igual. Y, por supuesto, he probado reiniciando el portátil tras haberlo cambiado. Pero no  hay novedad aparente.  Sigue dándome el mismo error.  Por eso lo  he  vuelto a dejar en el 3306.
Os dejo el mensaje completo del Xampp control panel

21:41:14  [main]  Initializing Control Panel 21:41:14  [main]     Windows
  Version:  Home  64-bit 21:41:14  [main]   XAMPP Version: 7.1.32
  21:41:14  [main]  Control Panel Version: 3.2.4  [ Compiled: Jun 5th
  2019 ] 21:41:14  [main]   You are not running with administrator
  rights! This will work for 21:41:14  [main]   most application stuff
  but whenever you do something with services 21:41:14  [main]  there
  will be a security dialogue or things will break! So think  21:41:14
  [main]    about running this application with administrator rights!
  21:41:14  [main]  XAMPP Installation Directory: "c:\xampp\" 21:41:14
  [main]    Checking for prerequisites 21:41:14  [main]     All prerequisites
  found 21:41:14  [main]    Initializing Modules 21:41:14  [main]   The
  FileZilla module is disabled 21:41:14  [main]     The Mercury module is
  disabled 21:41:14  [main]     The Tomcat module is disabled 21:41:14
  [main]    Enabling autostart for module "Apache" 21:41:14  [main]
    Enabling autostart for module "MySQL" 21:41:14  [main]  Starting
  Check-Timer 21:41:14  [main]  Control Panel Ready 21:41:14  [Apache]
    Autostart active: starting... 21:41:14  [Apache]    Attempting to start
  Apache app... 21:41:14  [mysql]   Autostart active: starting...
  21:41:14  [mysql]     Attempting to start MySQL app... 21:41:15  [Apache]
    Status change detected: running 21:41:15  [mysql]   Status change
  detected: running 21:41:16  [mysql]   Status change detected: stopped
  21:41:16  [mysql]     Error: MySQL shutdown unexpectedly. 21:41:16
  [mysql]   This may be due to a blocked port, missing dependencies,
  21:41:16  [mysql]     improper privileges, a crash, or a shutdown by
  another method. 21:41:16  [mysql]     Press the Logs button to view error
  logs and check 21:41:16  [mysql]  the Windows Event Viewer for more
  clues 21:41:16  [mysql]   If you need more help, copy and post this
  21:41:16  [mysql]     entire log window on the forums 21:55:28  [mysql]
    Attempting to start MySQL app... 21:55:29  [mysql]  Status change
  detected: running 21:55:31  [mysql]   Status change detected: stopped
  21:55:31  [mysql]     Error: MySQL shutdown unexpectedly. 21:55:31
  [mysql]   This may be due to a blocked port, missing dependencies,
  21:55:31  [mysql]     improper privileges, a crash, or a shutdown by
  another method. 21:55:31  [mysql]     Press the Logs button to view error
  logs and check 21:55:31  [mysql]  the Windows Event Viewer for more
  clues 21:55:31  [mysql]   If you need more help, copy and post this
  21:55:31  [mysql]     entire log window on the forums

Y el mensaje del log es:

InnoDB: using atomic writes. 2020-04-25 21:41:15 0 [Note] InnoDB:
  Mutexes and rw_locks use Windows interlocked functions 2020-04-25
  21:41:15 0 [Note] InnoDB: Uses event mutexes 2020-04-25 21:41:15 0
  [Note] InnoDB: Compressed tables use zlib 1.2.11 2020-04-25 21:41:15 0
  [Note] InnoDB: Number of pools: 1 2020-04-25 21:41:15 0 [Note] InnoDB:
  Using SSE2 crc32 instructions 2020-04-25 21:41:15 0 [Note] InnoDB:
  Initializing buffer pool, total size = 16M, instances = 1, chunk size
  = 16M 2020-04-25 21:41:15 0 [Note] InnoDB: Completed initialization of buffer pool 2020-04-25 21:41:15 0 [Note] InnoDB: 128 out of 128
  rollback segments are active. 2020-04-25 21:41:15 0 [Note] InnoDB:
  Creating shared tablespace for temporary tables 2020-04-25 21:41:15 0
  [Note] InnoDB: Setting file 'C:\xampp\mysql\data\ibtmp1' size to 12
  MB. Physically writing the file full; Please wait ... 2020-04-25
  21:41:15 0 [Note] InnoDB: File 'C:\xampp\mysql\data\ibtmp1' size is
  now 12 MB. 2020-04-25 21:41:15 0 [Note] InnoDB: Waiting for purge to
  start 2020-04-25 21:41:15 0 [Note] InnoDB: 10.4.6 started; log
  sequence number 1926016; transaction id 2085 2020-04-25 21:41:15 0
  [Note] InnoDB: Loading buffer pool(s) from
  C:\xampp\mysql\data\ib_buffer_pool 2020-04-25 21:41:15 0 [Note] Plugin
  'FEEDBACK' is disabled. 2020-04-25 21:41:15 0 [Note] Server socket
  created on IP: '::'.

Lo más chocante es que en todas las veces en el log me pone created on IP: '::' aunque sí me haya funcionado.
Uso Windows 10 Home.
¿En caso de que no quede otra que desinstalar... ¿la base de datos seguiría intacta al volver a instalar
 o habría problema?
¡Espero que podáis ayudarme! ¡Muchas gracias!

A: Por lo errores registrados tienes una o varias tablas corruptas en tu base de datos, te propongo realizar el siguiente procedimiento:

*

*Ejecutar mysql en modo recovery. Para lograr esto debes modificar el
archivo my.ini y agregar la propiedad innodb_force_recovery
Luego de modificar el archivo puedes iniciar Mysql desde la consola. Este cambio permite que el servidor se ejecute incluso si detecta una página corrupta.. Info
innodb_force_recovery = 1

*Ejecutar mysqlcheck en tu base de datos para determinar las tablas
corruptas.Esto te ayudara a identificar las tablas corruptas.Ayuda sobre esta instruccion Info
mysqlcheck -u user -p --analyze --all-databases

*Exportar las tablas corruptas con mysqldump. Ayuda sobre esta instruccion Info
 mysqldump -u user -p  mydb t1 > mydb_tables.sql

*Eliminar las tablas corruptas. Ayuda sobre esta instruccion Info
 DROP TABLE t1;

*Detener el servicio de mysql y editar el archivo my.ini eliminando
la propiedad que agregamos en el punto 1

*Iniciar Mysql modo normal e importar las tablas exportadas en el
punto 3. Ayuda sobre esta instruccion Info
 mysql -u user -p mydb < mydb_tables.sql

Espero haber sido lo mas explicito posible, segun tu entorno los pasos o las propiedades de las instrucciones pueden variar para resolver tu problema por esa razon agregue un enlace en cada paso para que puedas ayudarte.


text:
Q: Ubuntu 12.04 increase swap I have installed Ubuntu 12.04 and want to increase my swap size from 1Gb to 4Gb.
how can I do this?
/dev/sda5                               partition       1046524 568284  -1

A: Here is it
https://help.ubuntu.com/community/SwapFaq#How_do_I_add_more_swap.3F
You will need a Ubuntu LiveCD for this

A: If you only have occasional need of >1GB of swap space, you may consider creating a swap file in addition to the dedicated swap partition, which will avoid having to dig up a live CD/USB and resize partitions.
Create a swap file:
sudo fallocate -l 3G /swapfile
sudo chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

Add it to your /etc/fstab file so that you don't have to manually re-enable it each boot.
/swapfile none swap sw 0 0

You can set the priority of the two swap areas separately if you want the system to use the dedicated partition with higher priority. Add a pri=N option to the mount options in /etc/fstab, eg:
UUID=xxx...yyy none swap sw,pri=10 0 0
/swapfile none swap sw,pri=1 0 0

A: GParted (available in the repositories) allows you to play with partitions, including resizing them without data loss, but you are strongly suggested to back up all your data before doing so...
RAM is really cheap these days (4GB module around 20$). You might want to consider just buying more RAM if you are making heavy use of your swap partition. It is faster and having more than one module is always good anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pandas - send warnings when data's shape changes I am using opendata, and sometimes the shape of the datasets changes : some rows are missing for example. I would like to be warned when it happens.
I figured this out :
import pandas as pd

old_data = [["apple",1,"red"], ["banana", 5, "yellow"], ["peach", 3, "pink"]]
new_data = [["apple",1,"red"], ["banana", 5, "yellow"], ["peach", 3, "pink"],
               ["orange", 7, "orange"]]

old_dataset = pd.DataFrame(old_data, columns = ["fruit", "nb", "colour"])
new_dataset = pd.DataFrame(new_data, columns = ["fruit", "nb", "colour"])

compare_lengths = len(old_dataset) == len(new_dataset)

if compare_lengths == False:
    lengths_warning = "Dataset's length changed"
if compare_lengths == True:
    lengths_warning = "OK"

Then I would gather all the warnings in a file, where I could see them all. I would do this by importing every variable like this.
from file_1 import lengths_warning

Is there a better way to do it ?
Is it possible to set up warnings/controls in a more efficient way ? With a specific module maybe ?
Thks


text:
Q: Formulating a problem involving sets with ILP Consider set $\mathcal{G} = \{G_1, \ldots, G_K\}$. We are given $\mathcal{A}_i \subset \mathcal{G}$, $i \in
\mathcal{N}= \{1,\ldots, N\}$ and for each $\mathcal{A}_i$, there is a corresponding cost denoted by $C_i$. We want to choose $\mathcal{A}_j$, $j \in \mathcal{J} \subset \mathcal{N}$ with minimum cost such that union of $\mathcal{A}_j$, $j \in \mathcal{J}$ is the set $\mathcal{G}$. Therefore, the problem is to $\min_{\alpha_1, \ldots, \alpha_N} \sum_{i \in \mathcal{N}}\alpha_i C_i$ subject to $\cup_{i \in \mathcal{N}, \alpha_i=1} \mathcal{A}_i = \mathcal{G}$, $\alpha_i \in \{0,1\}$ for $i \in \mathcal{N}$.
Is it possible to write this problem as a standard ILP?

A: Let me recapitulate (so that I understand this):

*

*You have a base set $G$ with $K$ elements.

*Then you have $N$ subsets $A^{(i)}$ of $G$, each comes with cost $C_i$.

*You want to cover $G$ with a selection of $A^{(i)}$ such that the cost is minimal.

We can model the selection of subsets via the vector of unknowns
$x \in \{ 0, 1 \}^N$.
For each set $A^{(i)}$ we have a vector $y^{(i)} \in \{ 0, 1 \}^K$ which is kind of its index function regarding $G$:
$$
y_j^{(i)} =
\begin{cases}
1 & \text{if } A^{(i)}_j \in G \\
0 & \text{else}
\end{cases}
$$
To cover $G$ a feasible selection $x$ of subsets $A^{(i)}$ must have at least one of each element of $G$ and thus fulfill the constraint
$$
1_K \le \sum_i x_i y^{(i)} = Y x
$$
where $1_K = (1, \dotsc, 1)^\top \in \{0,1\}^K$ and
$Y = (y^{(1)}, \dotsc, y^{(N)}) \in \{0,1\}^{K \times N}$.
So we got the ILP:
$$
\begin{array}{ll}
\min & c^\top x \\
\text{w.r.t.} & Y x \ge 1_K \\
& x \in \{ 0, 1 \}^N
\end{array}
$$
where $c$ is the cost vector with components $C_i$.


text:
Q: Facebook Javascript SDK extend access token get "Invalid OAuth access token" - 190 - "OAuthException" I try to use javacript SDK to get access token and then extend that access token for 60 day. I got reponse error like this from response: Object { message="Invalid OAuth access token.", type="OAuthException", code=190}
My expectation:

*

*Get new access token with 60 days expire

*Console to screen.

My Code:
window.onload = function() {

var isLogin = true;

FB.init({appId:422642254433770, cookie:true, status:true, xfbml:true });

FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
        // the user is logged in and connected to your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token
        // and signed request each expire
        var uid = response.authResponse.userID;
        var accessToken = response.authResponse.accessToken;
        var accessTokenOld = response.authResponse.accessToken;

        //Extend access token
        var OauthParams = {};
        OauthParams['client_id'] = '//REMOVED APP ID';
        OauthParams['client_secret'] = '//REMOVED APP SECRET';
        OauthParams['grant_type'] = 'fb_exchange_token';
        OauthParams['fb_exchange_token'] = 'accessToken';
        OauthParams['response_type'] = 'token';

        console.log("Old accessToken => " + accessToken);
        FB.api('/oauth/access_token', 'post', OauthParams, function(response) {
            console.log(response);

            if (!response || response.error) {
                console.log(response.accesstoken);
            } else {
                console.log("Lay new access token bi loi " + response.error.message);
            }
        });
    }
});
};

I try to search every where for this trouble 3 days without any clue. I there any one have experience? please help.
Many thanks

A: Doing this in a client is a bad idea because of the requirement to include the app secret in the actual client, which is very dangerous. It's best to call a endpoint on your server that handles this separately so that app secret stays in your controlled environment.

A: If in Advanced Settings of your FB App you have 'Remove offline_access permission' enabled, all your access tokens will be 60 days by default.
We ran into this same issue recently and this fixed the problem.
Hope this helps!

A: I found a simple solution to get extended access token using Jquery valide upto 2 months
Variables to pass to the URL:
var accessToken = 'CURRENT_ACCESS_TOKEN';
var appid       = 'APPID';
var appsecret   = 'APPSECRET';

Your URL should point to
var exchangeUrl = "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&fb_exchange_token="+accessToken+"&client_id="+appid+"&client_secret="+appsecret;

Make an Ajax request as
$.ajax({
type: "GET",
url: exchangeUrl,
success: function(data)
{
   extended = data.split('=');
   extendedAT = extended['1'].replace('&expires','');
       alert(extendedAT);

}

});


text:
Q: .bat How to replace text and preserve blank lines The code below does preserve space before each line in the example.yaml.  However, it removes all blank lines AND most importantly it doesn't even replace the text.
Does anyone know how to edit this code so that it will:

*

*Preserve blank lines

*Replace "filters:" with "filters: !yaml_filters!"

@echo off
echo how many filters
set /p yaml_filters=

for /f "delims=" %%i in ('"FINDSTR /B filters: example.yaml"') do set edit_line=%%i
SETLOCAL=ENABLEDELAYEDEXPANSION
        rename example.yaml example.tmp
        for /f "delims=" %%a in (example.tmp) do (
            set foo=%%a
            if "!foo!"=="%edit_line%" (set foo=filters: !yaml_filters!)
            echo !foo! >> example.yaml)
    del example.tmp

A: As others already noted, batch isn't a good tool for this task (not saying it's impossible but there are many caveats and quirks.
If you're willing to accept a third-party tool, I recommend jrepl.bat which makes your script just three lines (without having to worry about special chars, empty lines or leading (or trailing) spaces or tabs):
@echo off
set /p "yaml_filters=how many filters: "
call jrepl.bat "filters: \d*" "filters: %yaml_filters%" /f example.yaml /o -

If there is no other code afterward, you can even scratch the call command.
Downloadlink jrepl.bat. The author dbenham is a highly respected and trusted member on StackOverflow.

A: You're not terribly far off:
@Echo Off & Setlocal EnableDelayedExpansion & CD "%~dp0"
rem // Qualify Parameters
If "%~3"=="" (Echo/^<Input File.ext^> ^<Search String^> ^<Insertion String^> & Exit /B 1)
rem // declare source file %1
  Set "Input=%~1"
  If not Exist "%Input%" Exit /B 1
rem // ensure no conflicting output file
  If Exist "tmp!Input!" Del /Q "tmp!Input!"
rem // iterate over source and output lines modified according to search pattern %2 and injected string %3
  For /F "Tokens=* Delims=" %%A in (!Input!) Do (
    Set "Line=%%A"
    ((Echo/!Line! | Findstr /B /I /L "%~2" >Nul 2> Nul) && Set "Line=%~2 %~3")
    Echo/!Line!
  )>>"tmp!input!"
rem // cleanup
  Del /Q "!input!"
  Set "RenFile=REN tmp!input! !input!"
  %RenFile%
  Endlocal & Exit /B 0

Note: The script is to be called with parameters indicated - I don't make a habit of posting 'exact' solutions as I find it better to provide a versatile answer that can easily be used by others with similar questions / problems

A: Editing yaml files with batch files is not really the greatest idea, but that is what you request so I will give you a solution. Some notes:

*

*The file cannot contain ! as it will skip the characters due to delayedexpansion

*The line you search for must match exactly, it cannot be partial line as we do not match for partial strings (substrings) So make sure you understand that if you want to match parts of the string, you need to modify the script to do so.

@echo off
set "myfile=example.yaml"
set "search=line to match"
set /p "replace=How many filters: "
for /f "tokens=1*delims=[]" %%a in ('type "%myfile%" ^| find /v /n "" ^& break ^> "%myfile%"') do (
       set "line=%%b"
       setlocal enabledelayedexpansion
       if "!line!"=="%search%" set "line=filters: !replace!"
       (echo(!line!)>>"%myfile%"
       endlocal
)


text:
Q: Overload Python 'in' to return non-bool I'm trying to overload the in operator for a class to return a non-bool object, but it seems to cast anyway. Here is my use case:
class Dataset(object):
  def __init__(self):
    self._filters = []

  def filter(self, f):
    self._filters.append(f)
    return self

class EqualFilter(object):
  def __init__(self, field, val):
    ...

class SubsetFilter(object):
  def __init__(self, field, vals):
    ...

class FilterBuilder(object):
  def __init__(self, field):
    self._field = field

  def __eq__(self, val):
    return EqualFilter(self._field, val)

  def __contains__(self, vals):
    return SubsetFilter(self._field, vals)

veggie = FilterBuilder('veggie')
fruit = FilterBuilder('fruit')
ds = Dataset().filter(veggie == 'carrot').filter(fruit in ['apple', 'orange'])

At the end of the code, ds contains an EqualFilter for veggie == 'carrot', and True for fruit in ['apple', 'orange']. Is there any way for ds to end up with a SubsetFilter?

A: There are two problems here. First, in always casts the result of __contains__ to a bool, so what you're looking for isn't possible. The second problem is that
fruit in ['apple', 'orange']

calls
['apple', 'orange'].__contains__(fruit)

There's no way for the left operand of in to override the operator, so that's also going to defeat what you're trying to do.

A: The real problem here is that, as the documentation says:

For user-defined classes which define the __contains__() method, x in y is true if and only if y.__contains__(x) is true.

Also see here and here.
user2357112's answer explains this better than I could. You're calling list.__contains__, not FilterBuilder.__contains__.

But why does it work that way?
Well, how else could it work?
Imagine that 3 in [1, 2, 3] called int.__contains__. And so did 3 in {1, 2, 3}, and 3 in my_custom_sorted_bintree. How could int.__contains__(container) possibly be implemented? Certainly not by iterating over the container. That would mean slow, exhaustive search for looking things up in sets and bintrees, which would defeat the whole point. My bintree class might not even be iterable, and yet may still have a concept of membership.
But what if they call list.__contains__, set.__contains__ and CustomSortedBintree.__contains__? Don't they have to know about int, and str, and every other possible thing you could give them? No, not at all. A list just has to know how to compare arg == elem for each of its elements. A set also needs to know how to call hash(arg). A bintree also has to know how to call arg < elem. But you don't need to know anything about the type of arg to do that.

You probably want to know how to deal with this. There are two and a half common solutions.
1: You can easily create a FilterList class. Then, you just write:
fruit in FilterList('apple', 'orange')

1.5: Or, with a bit more work, you can build a more general "value holder":
fruit in const(['apple', 'orange'])

2: Alternatively, you can write a FilterBuilder.in_ method. Then you write:
fruit.in_(['apple', 'orange'])

… or, if you prefer:
fruit.in_('apple', 'orange')

Most libraries I've seen either provide the second (sqlalchemy), or provide both but use the second in their tutorials (appscript), although "quick-lambda" libraries often go with the generic version of the first.
But you should consider the tradeoffs for your own use case. In general, the first is easier to implement, and more explicit, and has the advantage that subfilters/subqueries can return something that acts as a FilterList; the second is less verbose and arguably easier to read.
If neither one is acceptable, you could consider writing a parser for a Python-like DSL, instead of trying to build a DSL out of actual Python code via expression templates. Or using something like MacroPy (which I think even has an example similar to what you're looking for—as well as quick-lambda macros that don't need "const" and friends).

A: No. list.__contains__ always returns a bool, and C types cannot be monkeypatched (nor should you consider doing so, since you will likely break other code).


text:
Q: How can i re-run a main() function in python, if one of its function throws an error? Here is a program to return percentage of fuel when entered in fraction where the input is passed on to the another function

def main():
    # taking input from user 'x/y'
    fuel = input("Fraction: ")
    print(convert(fuel),"%",sep="")

def convert(fraction):
    # extracting nominators
    fraction.split('/')
    x = int(fraction[0])
    y = int(fraction[2])
    # returning the percentage after calculating
    try:
        per = x / y * 100
        return round(per)
    # ignoring the errors
    except ZeroDivisionError or ValueError:
        pass

# re-run the main() function, if convert() throws errors
if __name__ == '__main__':
    main()

I got the results i was intended when i wrote the whole code similar to this:

def main():
    while True:
        try:
            fuel = input("Fraction: ")
            fuel.split('/')
            x = int(fuel[0])
            y = int(fuel[2])

            print(round(x / y * 100),"%",sep="")
            break
        except ZeroDivisionError or ValueError:
            pass

if __name__ == '__main__':
    main()

But i want to pass on the input ( fuel ) to another function( convert() ) .So, how can i re-run the main() function again, if it's expecting a ZeroDivisionError and ValueError from the convert(fraction) function?

A: Once you have valid input from the user - i.e., something that you can express as a percentage, just return that value from the function and pass it to another as required.
Something like this:
def convert(fraction):
    pass

def main():
    while True:
        fraction = input('Fraction: ')
        try:
            a, b = map(float, fraction.split('/'))
            print(f'{round(a/b*100)}%')
            return fraction
        except (ValueError, ZeroDivisionError):
            print('Invalid input')

if __name__ == '__main__':
    fraction = main()
    convert(fraction)


text:
Q: Multipanels using Manipulate and variable dependence Is it possible to change the values of the variables in Manipulate? Suppose I have a Manipulate with two variables, x and y and we display the values. What I want to do is to make it in such a way that when I change the value of x, y gets updated to x*x. When I change the value of y, then x gets updated to the square root of y.
The other question is, can I have multiple panels in Manipulate? I would like to have a white panel under each slider.
Manipulate[
 Row[{x, y}, "    "],
 Row[{
   Control[{{x, 0, Style["x", "TI", 14]}, 0, 4 , Appearance -> "Labeled"}],
   Control[{{y, 0, Style["y", "TI", 14]}, 0, 16, Appearance -> "Labeled"}]
 }]
]

In the above plot I have set x to 3 and y to 9. Again, I would like to move y to say 4 and have x to move to 2. Similarly, I want to move x to 4 and have y move to 16.
Is is possible? or have I just encountered the chicken or the egg problem?

A: A bit hack-ish but to couple the sliders and get two panels, you could also do something like this
Panel[DynamicModule[{x, y, width = 250},
  Grid[{{
     Labeled[Slider[Dynamic[x, (x = #; y = #^2) &], {0, 5}],
      {Style["x", "TI", 14], Dynamic[x]}, {Left, Right}],
     Labeled[Slider[Dynamic[y, (y = #; x = Sqrt[#]) &], {0, 25}],
      {Style["y", "TI", 14], Dynamic[y]}, {Left, Right}]},

    Framed[Pane[#, width, Alignment -> Center], FrameMargins -> 10,
       Background -> White, FrameStyle -> {Gray}] & /@
     {Row[{"x=", Dynamic[x]}], Row[{"y=", Dynamic[y]}]}}, Alignment -> Left]]]

Screenshot:

A: How about
DynamicModule[{x = 0},
  {Slider[Dynamic[x], {0, 1}],
  Slider[Dynamic[x^2, (x = Sqrt@#) &], {0, 1}]}]

which is a trivial modification of a code snippet I found in tutorial/IntroductionToDynamic in the docs?
EDIT: You can add panels etc as follows:
DynamicModule[{x = 0},
  Row[{Column[{Slider[Dynamic[x], {0, 1}], Panel@Dynamic@x}],
  Column[{Slider[Dynamic[x^2, (x = Sqrt@#) &], {0, 1}],
    Panel@Dynamic@Sqrt[x]}]}]]

A: It might be better to have each question separate. Hard to answer 2 questions in same place.
For the first question, you can use your own Dynamics to obtain better control. Here is one way:
Manipulate[
  Row[{
      Dynamic[Refresh[Text@Row[{"x=",x," y=",y}],TrackedSymbols->{event}]],
      Dynamic[Refresh[event=Date[];y=x*x;"",TrackedSymbols->{x}]],
      Dynamic[Refresh[event=Date[];x=Sqrt[y];"",TrackedSymbols->{y}]]
     }],
  {{x,2,"x"},0,100,1},
  {{y,2,"y"},0,1000,1},
  {{event,0},ControlType->None},
  TrackedSymbols:>{None}
]

For your second question, a Manipulate, has one 'panel'  where output goes to. So, you can't really do it with one Manipulate. But you can nest Manipulates, so you can do it that way by having each manipulate with its own controls all under one Manipulate.
Update1:
To share variables between 2 inner Manipulate, so when one Manipulate update its own variable, the other Manipulate sees the latest update, here is one possible way. When you movbe one Manipulate slider, the second Manipulate updates automatically with the new value.
Manipulate[

   Grid[{{

    Manipulate[( gx=x; Row[{"x=",x," y=",gy}]),
               {{x,1,"x="},0,10,1}],
    Manipulate[( gy=y; Row[{"x=",gx," y=",y}]),
               {{y,1,"y="},0,10,1}]
   }}],

{{gx,0},ControlType->None},
{{gy,0},ControlType->None},

ControlPlacement->Bottom
]


text:
Q: Awk - insert a new row after the regular expression? File contents: (based on topic -> 1)
"Shimshon A",
"(blank)",
"November 24, 2012",
"13,481",
"jonathan t",
"Laguna Niguel, CA",
"November 24, 2012",
"13,480",
"scott b",
"Sussex, NJ",
"November 24, 2012",
"13,479",

How to improve the command?:
gawk --posix 'ORS="";{sub(/,[0-9]{3}/, "&&\n"); print }' file

Result:
$ gawk --posix 'ORS="";{sub(/,[0-9]{3}/, "&&\n"); print }' file
"Shimshon A","(blank)","November 24, 2012","13,481,481
","jonathan t","Laguna Niguel, CA","November 24, 2012","13,480,480
","scott b","Sussex, NJ","November 24, 2012","13,479,479
",userpc@userpc-desktop:~/Pulpit$

I want to print:
"Shimshon A","(blank)","November 24, 2012","13,481"
"jonathan t","Laguna Niguel, CA","November 24, 2012","13,480"
"scott b","Sussex, NJ","November 24, 2012","13,479"

Please only solution in awk.
Thank you for your help.

A: This one liner will work,
awk -FS="" 'BEGIN{ORS=""} {print substr($1, 1, length($1)-1) ((c%4==3)? "\n": ",");c=c+1;}' file

Here is a more elaborated version.
awk -FS="" 'BEGIN{
    ORS="";
    c=0
} {
    print substr($1, 1, length($1)-1) ((c%4==3)? "\n": ",");
    c=c+1;
}' < file

A: I think this is what you're looking for:
awk -v ORS="" '/"[0-9]{2},[0-9]{3}"/ { sub(/,$/,""); print $0 "\n"; next }1' file

Results:
"Shimshon A","(blank)","November 24, 2012","13,481"
"jonathan t","Laguna Niguel, CA","November 24, 2012","13,480"
"scott b","Sussex, NJ","November 24, 2012","13,479"

A: I know you said only awk. If you're willing to stretch:
paste -d "" - - - - < file | sed 's/,$//'


text:
Q: Powerbuilder word OLE: Run time error 35 while setformresult I am using powerbuilder 12.5 to add data to word templates using bookmarks.When I use objword.setformresult(bookmarkname,value) I get run time error 35
"error calling external object function setformresult"
Info: We have recently migrated powerbuilder 6.5 to 12.5 but still we use Office 2003

A: This is how I do it:
lole_word = CREATE OLEObject
lole_word.ConnectToNewObject ("word.application")
lole_Document = lole_word.Documents.Open (is_infile,FALSE,TRUE,FALSE)
lole_range = lole_document.Bookmarks.item(ls_bookmark).Range
lole_range.Text = ls_newText

Always put code like this a Try..Catch block and catch OleRuntimeError and RuntimeError. Note that replacing the text will remove the bookmark. If you need the bookmark you have to remember where it is (for example lole_document.Bookmarks.item(ls_bookmark).Start) and add the bookmark to the document again.


text:
Q: Advanced MultiThreading in android I'm new to android, I need to start a Thread Multiple times to do a regular work as the listen a thing. But I searched and found that can't do this. So I decided to put
while(true){
listen some thing
do another something depends for listen
}

in the run() method.
But How can I implements this idea? Is it possible ? and How?

A: If you start your thread inside a while loop with true condition, it'll kill your device. You'r device will hang. Your code should be event triggered. You can have a Service running in the background to do that and listen for your events.

A: You should use Handler.post() whenever you want to do operations in the UI thread.
So let's say in the callback (which is running in separate thread) you want to change a TextView's text, you should use Handler.post(). In Android, as in many other UI frameworks, UI elements (widgets) can be only modified from main thread.
mHandler = new Handler();

new Thread(new Runnable(
  @Override
  public void run () {
    // Perform long-running task here
    // (like audio buffering).
    // you may want to update some progress
    // bar every second, so use handler:
    mHandler.post(new Runnable() {
     @Override
     public void run () {
       // make operation on UI - on example
       // on progress bar.
     }
    });
  }
)).start();

Of course, if the task you want to perform is really long and there is a risk user might switch to some another app in the meantime, you should consider using Service.


text:
Q: iPhone Strange problem with NSString I have following code which is called numerous times:

NSString *Final =  [ NSString stringWithFormat:@"%@%@%@%@.%@%@", str1, str2, str3, str4, str5, str6];

Every  once a while Final string is set to nil, while str1 ... to str6 are perfectly valid string (I have verified in debugger)!
I had this code originally, but every once a while Final was also an invalid pointer

NSString *Final =  [ [NSString alloc] initWithFormat:@"%@%@%@%@.%@%@", str1, str2, str3, str4, str5, str6];
...
[Final release];

I am absolutely puzzled. What could this be?
Basically I am collecting values from various edit boxes, form a string from these values and eventually convert it to the number.
Thanks!

A: this is a clumsy alternative.
If your line does not work, try this:
NSString * finalstr = str1;
finalstr = [finalstr stringByAppendingString:str2];
finalstr = [finalstr stringByAppendingString:str3];
finalstr = [finalstr stringByAppendingString:str4];
finalstr = [finalstr stringByAppendingString:str5];
finalstr = [finalstr stringByAppendingString:str6];

by the way, i used to avoid those commonly used reserved words to be my variable names (though final is not a reserved word by objective-c).


text:
Q: Save image blob url in php In my controller i receive a image url in blob
https://adonai.eduxenet.com.br/290beb51-094f-4f6a-bd9f-a37cf49d1c25" >
I've tried in several ways to get the image and I can not
how can I get this image and save it to my server?
 public function store(Request $request)
{

    $detail=$request->layoutDocumento;
    debug_var($detail);

    $dom = new \domdocument();
    @$dom->loadHtml(utf8_decode($detail), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

    $images = $dom->getelementsbytagname('img');

    foreach($images as $k => $img){
        $data = $img->getattribute('src');

        //list($type, $data) = explode(';', $data);
        //list(, $data)      = explode(',', $data);

        //$data = base64_encode($data);

        $uploadArquivo = $this->salvaDocumento(\Session::get('app.cliente_id'),
                                           \Session::get('id_unidade_selecionada'),
                                            $request->id_categoria ,
                                            $request->id_documento ,
                                            $blob);

        debug_var($uploadArquivo);

        $imagem_url = \Config::get('app.storage') . '/' . $uploadArquivo;
        $img->removeattribute('src');
        $img->setattribute('src', $imagem_url);
    }

    $detail = $dom->savehtml();

    $documento = new Documento;
    $documento->id_tipo_documentos = $request->id_documento;
    $documento->st_vingente = '1';
    $documento->st_matricula = '1';
    $documento->tp_layout = 'portrait';
    $documento->layout = $detail;
    $documento->save();
    \Session::forget('msg_documentos');
    \Session::put('msg_documentos', "Documento salvo com sucesso !");
    return redirect()->back();

}


text:
Q: reading blob objects from google storage in airflow I am trying to read all the folders in a google cloud storage bucket.
I have a GCS bucket/root folder path. I am trying to read all subfolders in a root folder and perform a task for each folder.
from google.cloud import storage

def get_folders():
    BUCKET = 'bucket-name'
    PROJECT = 'project-name'
    path = 'root-path'
    client = storage.Client()
    bucket = client.bucket(BUCKET, PROJECT)
    folder_blobs = (client.list_blobs(BUCKET, prefix=path, delimiter='.'))
    folder_names = []
    for blob in folder_blobs:
        folder_names.append(blob.name.split('/')[-2])
    folder_names.sort()
    return folder_names

And it does get the folders, however airflow UI wont display the graph.
If I try to click on a dag name, it would say dag_name is not currently available.
I can see completed tasks and the results are correct, but I cannot get the DAG.
I am at a loss and don't what else to do. I know that it fails when I try to use a folder_blobs object.
Please, if anyone can help please.
FYI, it all works in stand alone Python
DAG file would be like that:
from google.cloud import storage

from datetime import datetime #, timedelta
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator

from airflow.models import Variable

def get_folders():
    BUCKET = 'MyBucket'
    PROJECT = 'MyProject'
    path = 'root_path'
    client = storage.Client()
    bucket = client.bucket(BUCKET, PROJECT)
    blobs = (client.list_blobs(BUCKET, prefix=path, delimiter='.'))1
    folder_names = []
    for blob in blobs:
        folder_names.append(blob.name.split('/')[-2])
    folder_names.sort()
    return folder_names

args = {
    'owner': 'airflow',
}

PARENT_DAG_NAME = 'Get_Folders_v1.02'

dag = DAG(
    dag_id=PARENT_DAG_NAME,
    default_args=args,
    schedule_interval='@daily',
    catchup=False,
    start_date=datetime(2021, 1, 1),
)

start = DummyOperator(task_id='Start', dag=dag)
end = DummyOperator(task_id='End', dag=dag)
for folder in folders:
    t1 = DummyOperator(
        task_id='Folder_{}_task'.format(folder),
        dag=dag
    )

start >> t1 >> end

A: I tried to use your code in my setup and I changed it since it errors out on a few lines like for folder in folders: (folders object is not declared). Also you have an extra '1' at the end of the line blobs = (client.list_blobs(BUCKET, prefix=path, delimiter='.'))1
I removed the loop and changed DummyOperator to PythonOperator to use your get_folder() function to return the folder_names. By the way I ran Airflow using Cloud Composer. I followed this quick start to set up the Cloud Composer environment.
from google.cloud import storage
from datetime import datetime #, timedelta
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import PythonOperator

from airflow.models import Variable

def get_folders():
    BUCKET = 'my-test-bucket'
    PROJECT = 'my-project'
    path = '25868628' #just a random folder in my bucket
    client = storage.Client()
    bucket = client.bucket(BUCKET, PROJECT)
    blobs = (client.list_blobs(BUCKET, prefix=path, delimiter='.'))
    folder_names = []
    for blob in blobs:
        folder_names.append(blob.name.split('/')[-2])
    folder_names.sort()
    return folder_names

args = {
    'owner': 'airflow',
}

PARENT_DAG_NAME = 'Get_Folders_v1.02'

dag = DAG(
    dag_id=PARENT_DAG_NAME,
    default_args=args,
    schedule_interval='@daily',
    catchup=False,
    start_date=datetime(2021, 1, 1),
)

start = DummyOperator(task_id='Start', dag=dag)
end = DummyOperator(task_id='End', dag=dag)
t1 = PythonOperator(
        task_id='get_folders',
        python_callable=get_folders,
        dag=dag,
        )

start >> t1 >> end

DAG file in airflow:

Graph View:

Tree view:

Output logs:
[2021-01-07 03:40:06,448] {base_task_runner.py:113} INFO - Job 19: Subtask get_folders Running <TaskInstance: Get_Folders_v1.02.get_folders 2021-01-06T00:00:00+00:00 [running]> on host airflow-worker-c985959c8-6fv56
[2021-01-07 03:40:07,164] {base_task_runner.py:113} INFO - Job 19: Subtask get_folders [2021-01-07 03:40:07,163] {python_operator.py:114} INFO - Done. Returned value was: ['25868628', 'test_images']
[2021-01-07 03:40:07,267] {taskinstance.py:1066} INFO - Marking task as SUCCESS.dag_id=Get_Folders_v1.02, task_id=get_folders, execution_date=20210106T000000, start_date=20210107T033959, end_date=20210107T034007
[2021-01-07 03:40:07,267] {base_task_runner.py:113} INFO - Job 19: Subtask get_folders [2021-01-07 03:40:07,267] {taskinstance.py:1066} INFO - Marking task as SUCCESS.dag_id=Get_Folders_v1.02, task_id=get_folders, execution_date=20210106T000000, start_date=20210107T033959, end_date=20210107T034007


text:
Q: How to identity whether a particular location comes around the path we draw on google map I am using google direction API to generate the Polygon. I have also used below methods of map utils but not get desired solution
PolyUtil.isLocationOnEdge(pbmLocation,poly,false)
    PolyUtil.containsLocation(pbmLocation,poly,false)
    PolyUtil.distanceToLine(pbmLocation, startLocation, destLocation)


text:
Q: Create new column based on conditions in other columns in R For context I am determining behavior states of a seabird using GPS relocations, time, and speed. In my case, I am trying to determine the if a foraging event occurred for each individual, given the speed they are traveling at between successive relocations, and the duration between relocations. For example, I would like to create a new column (named "event") based on the following condition for each "id":
IF "speed" < 4 AND "duration" > 240 for consecutive relocations, THEN "event" = 1.
If the condition is not met, then "event" = 0.
Below is some simplified sample data, and below that the desired output. Thanks in advance!
# Sample data
id <- c(1,1,1,1,1,
        2,2,2,2,2,
        3,3,3,3,3,
        4,4,4,4,4)
time <- c("00:00", "00:02", "00:04", "00:06", "00:08",
          "00:00", "00:02", "00:04", "00:06", "00:08",
          "00:00", "00:02", "00:04", "00:06", "00:08",
          "00:00", "00:02", "00:04", "00:06", "00:08")

x <- c(-123.1, -123.3, -123.6, -123.2, -123.4,
       -123.0, -123.2, -123.9, -123.1, -123.3,
       -123.4, -123.7, -123.3, -123.5, -123.1,
       -123.8, -123.5, -123.1, -123.0, -123.9)

y <- c(37.1, 37.2, 37.3, 37.4, 37.5,
       37.0, 37.1, 37.2, 37.3, 37.4,
       37.3, 37.4, 37.5, 37.6, 37.7,
       37.2, 37.3, 37.4, 37.5, 37.6)

duration <- c(120, 120, 120, 120, 120,
          120, 120, 120, 120, 120,
          120, 120, 120, 120, 120,
          120, 120, 120, 120, 120)

speed <-c(3, 3, 3, 3, 5,
          2, 2, 2, 5, 5,
          5, 5, 5, 2, 2,
          3, 3, 3, 3, 5)

data <- cbind(id, time, x, y, duration, speed)

> data
      id  time    x        y      duration speed
 [1,] "1" "00:00" "-123.1" "37.1" "120"    "3"
 [2,] "1" "00:02" "-123.3" "37.2" "120"    "3"
 [3,] "1" "00:04" "-123.6" "37.3" "120"    "3"
 [4,] "1" "00:06" "-123.2" "37.4" "120"    "3"
 [5,] "1" "00:08" "-123.4" "37.5" "120"    "5"
 [6,] "2" "00:00" "-123"   "37"   "120"    "2"
 [7,] "2" "00:02" "-123.2" "37.1" "120"    "2"
 [8,] "2" "00:04" "-123.9" "37.2" "120"    "2"
 [9,] "2" "00:06" "-123.1" "37.3" "120"    "5"
[10,] "2" "00:08" "-123.3" "37.4" "120"    "5"
[11,] "3" "00:00" "-123.4" "37.3" "120"    "5"
[12,] "3" "00:02" "-123.7" "37.4" "120"    "5"
[13,] "3" "00:04" "-123.3" "37.5" "120"    "5"
[14,] "3" "00:06" "-123.5" "37.6" "120"    "2"
[15,] "3" "00:08" "-123.1" "37.7" "120"    "2"
[16,] "4" "00:00" "-123.8" "37.2" "120"    "3"
[17,] "4" "00:02" "-123.5" "37.3" "120"    "3"
[18,] "4" "00:04" "-123.1" "37.4" "120"    "3"
[19,] "4" "00:06" "-123"   "37.5" "120"    "3"
[20,] "4" "00:08" "-123.9" "37.6" "120"    "5"
>

# Desired output

> data
      id  time    x        y      duration speed event
 [1,] "1" "00:00" "-123.1" "37.1" "120"    "3"   "1"
 [2,] "1" "00:02" "-123.3" "37.2" "120"    "3"   "1"
 [3,] "1" "00:04" "-123.6" "37.3" "120"    "3"   "1"
 [4,] "1" "00:06" "-123.2" "37.4" "120"    "3"   "1"
 [5,] "1" "00:08" "-123.4" "37.5" "120"    "5"   "0"
 [6,] "2" "00:00" "-123"   "37"   "120"    "2"   "1"
 [7,] "2" "00:02" "-123.2" "37.1" "120"    "2"   "1"
 [8,] "2" "00:04" "-123.9" "37.2" "120"    "2"   "1"
 [9,] "2" "00:06" "-123.1" "37.3" "120"    "5"   "0"
[10,] "2" "00:08" "-123.3" "37.4" "120"    "5"   "0"
[11,] "3" "00:00" "-123.4" "37.3" "120"    "5"   "0"
[12,] "3" "00:02" "-123.7" "37.4" "120"    "5"   "0"
[13,] "3" "00:04" "-123.3" "37.5" "120"    "5"   "0"
[14,] "3" "00:06" "-123.5" "37.6" "120"    "2"   "0"
[15,] "3" "00:08" "-123.1" "37.7" "120"    "2"   "0"
[16,] "4" "00:00" "-123.8" "37.2" "120"    "3"   "1"
[17,] "4" "00:02" "-123.5" "37.3" "120"    "3"   "1"
[18,] "4" "00:04" "-123.1" "37.4" "120"    "3"   "1"
[19,] "4" "00:06" "-123"   "37.5" "120"    "3"   "1"
[20,] "4" "00:08" "-123.9" "37.6" "120"    "5"   "0"
>

A: Seems to be a run length question, using rle you can get the results you desire
data <- data.frame(id, time, x, y, duration, speed)

library(dplyr)

data |>
  group_by(id, speed) |>
  mutate(event = +(rle(speed)$lengths * duration > 240 & speed < 4))
  |> ungroup()

    id time      x     y duration speed event
   <dbl> <chr> <dbl> <dbl>    <dbl> <dbl> <int>
 1     1 00:00 -123.  37.1      120     3     1
 2     1 00:02 -123.  37.2      120     3     1
 3     1 00:04 -124.  37.3      120     3     1
 4     1 00:06 -123.  37.4      120     3     1
 5     1 00:08 -123.  37.5      120     5     0
 6     2 00:00 -123   37        120     2     1
 7     2 00:02 -123.  37.1      120     2     1
 8     2 00:04 -124.  37.2      120     2     1
 9     2 00:06 -123.  37.3      120     5     0
10     2 00:08 -123.  37.4      120     5     0
11     3 00:00 -123.  37.3      120     5     0
12     3 00:02 -124.  37.4      120     5     0
13     3 00:04 -123.  37.5      120     5     0
14     3 00:06 -124.  37.6      120     2     0
15     3 00:08 -123.  37.7      120     2     0
16     4 00:00 -124.  37.2      120     3     1
17     4 00:02 -124.  37.3      120     3     1
18     4 00:04 -123.  37.4      120     3     1
19     4 00:06 -123   37.5      120     3     1
20     4 00:08 -124.  37.6      120     5     0


text:
Q: scala: easier way to wrap an object inside another object In a play 2.1 application I have the following code (it's just a request wrapper that gets rid of any trailing slash):
class NormalizedRequest(request: RequestHeader) extends RequestHeader {

  val headers = request.headers
  val id = request.id
  val method = request.method
  val queryString = request.queryString
  val remoteAddress = request.remoteAddress
  val tags = request.tags
  val version = request.version

  // strip first part of path and uri if it matches http.path config
  val path = if (request.path == "/") "/" else request.path.stripSuffix("/")
  val uri = path + {
    if(request.rawQueryString == "") ""
    else "?" + request.rawQueryString
  }
}

object NormalizedRequest {
  def apply(request: RequestHeader) = new NormalizedRequest(request)
}

This kind of code is pretty common, you just wrap an object inside another
I was wondering if there's an easier way to acomplish it, ideally it would be something like (pseudo code inspired on case classes):
object NormalizedRequest {
  def apply(request: RequestHeader) = {
    val path = if (request.path == "/") "/" else request.path.stripSuffix("/")
    val uri = path + {
      if(request.rawQueryString == "") ""
      else "?" + request.rawQueryString
    }
    request.copy(path = path, uri = uri)
  }
}

A: If I understand correctly, you're asking for a more concise version of the Decorator pattern in scala. You still need your "wrapper" to be the same type as you inner class (by extending it or a common base/trait) in order to be able to pass it over to some function that expects to receive an instance of the inner class (or of the common base/trait).
What you wrote in your pseudo code is actually almost legal scala, you just have to change the definition of apply in NormalizedRequest to return an anonymous class that extends RequestHeader.
I.e. instead of
class NormalizedRequest(request: RequestHeader) extends RequestHeader {
    //.... "decorated" logic here
}
object NormalizedRequest {
  def apply(request: RequestHeader) = new NormalizedRequest(request)
}

you would have
object NormalizedRequest {
  def apply(request: RequestHeader) = new RequestHeader {
    // ...
    // instead of having a separate NormalizedRequest class
    // define its behaviour here in anonymous form
    }
}

A simplified example:
// our inner class and companion object
// (a simplified version of your RequestHeader)
class Inner() {def test="hello"}; object Inner {
    def apply() = new Inner()
}

// our wrapper
object Outer {
    def apply(inner: Inner) = new Inner {
        override def test=inner.test + "!"
    }
}

however, although it saves you a few keystrokes, I really think you would lose in readability.


text:
Q: Qt DBus unmarshalling when sent as QDBusVariant / QVariant Class Dummy, derived from QObject, registered
Q_DECLARE_METATYPE(Dummy)
qRegisterMetaType<Dummy>("Dummy");
qDBusRegisterMetaType<Dummy>();

When I send Dummy as QDBusVariant, the slot is correctly called, but the value (of Dummy) is default. Have noticed that the unmarshalling operator is never called (marshalling is). Via DBusMonitor I can see the value is sent correclty.
I assume it fails because the operator QDBusArgument &operator<<(const QDBusVariant &arg); is called and works only against Qt standard types. If I wrap a QString in QVariant in QDBusVariant it works fine.
How can solve the issue?
/*!
 * \brief operator << Marshalling
 * \param argument
 * \param dummy
 * \return
 */
QDBusArgument &operator<<(QDBusArgument &argument, const Dummy& dummy)
{
    argument.beginStructure();
    argument << dummy.m_number; // qint32
    argument << dummy.m_string; // QString
    argument.endStructure();
    qDebug() << "Marshall to DBus" << dummy.m_number << dummy.m_string;
    return argument;
}

/*!
 * \brief operator >> unmarshalling
 * \param argument
 * \param dummy
 * \return
 */
const QDBusArgument &operator>>(const QDBusArgument &argument, Dummy &dummy)
{
    argument.beginStructure();
    argument >> dummy.m_number;
    argument >> dummy.m_string;
    argument.endStructure();
    qDebug() << "Unmarshall from DBus" << dummy.m_number << dummy.m_string;
    return argument;
}

Sending:
        Dummy dummy(c++, "Moep");
        qDebug() << "Dummy is" << dummy;
        QVariant qv;
        qv.setValue(dummy);
        QDBusVariant qdv = QDBusVariant(qv);
        testserviceInterface.receiveVariant(qdv);

Remarks:

*

*Qt 5.1 Win32

*This here describes a similar issue with no answer as of posting date: Qt QDbus Sending Custom Types with QVariant

A: The trick is, that the received QVariant for complex types is of type QDBusArgument. If it is possible to unmarshall to the desired target type, then the way to do it, is: qv.value<QDBusArgument>() >> someConcreteObject


text:
Q: Citing working paper that is now published I'm citing a journal paper (A, 1995), which cited another paper when it was in working paper form (B, 1994). B is now published in a journal (B, 1999).
So should I be referring to (B, 1994; A, 1995) or (B, 1999; A, 1995)?


text:
Q: Is the boundary of a $k$-manifold with corners a $(k-1)$-manifold with corners too? First of all  we remember some elementary definitions and results about manifolds with corners.

Definition
A function $f$ defined in a subset $S$ of $\Bbb R^k$ is said of class $C^r$ if it can be extended to a function $\phi$ (said $C^r$-extension) that is of class $C^r$ in a open neighborhood of $S$.
Lemma
If $f$ is a function defined in a subset $S$ of $\Bbb R^n$ such that for any $x\in S$ there exists a function $f_x$ defined in a neighborhood of $x$ that is of class $C^r$ and compatible with $f$ on $U_x\cap S$ then $f$ is of class $C^r$.
Lemma
If $U$ is an open set of $H^n_k:=\Bbb R^{n-k}\times[0,+\infty)^k$ for any $k\le n$ then the derivatives of two different extensions $\phi$ and $\varphi$ of a $C^r$-function $f$ agree in $U$.
Definition
A $k$-manifold with corners in $\Bbb R^n$ of class $C^r$ is a subspace $M$ of $\Bbb R^n$ whose points have a neighborhood $V$ in $M$ that is the immage of a homeomorphism $\phi$ of calss $C^r$ defined an open set $U$ of $\Bbb R^k$ or of $H^k_m$ and whose derivative has rank $k$.
Definition
A point $y$ of a $k$-manifold with corners $M$ is said interior point or boundary point if there exist a coordinate patch about $y$ defined in an open set of $\Bbb R^k$ or in an open set of $H^k_l$ respectively.
Theorem
Let be $M$ a $k$-manifold with corners in $\Bbb R^n$. So if $\phi:U\rightarrow V$ is a coordinate patch about any point boundary point $y$ of $M$ then necessarily
$$
y=\phi(x)
$$
for any $x\in U\cap\operatorname{bd}H^k_l$.

So with the previous definitions and efforts I ask to explain (rigorously) why the boundary points set $\partial M$ of a $k$-manifolds with corners is or is not a $(k-1)$-manifolds with corners too: indeed at the page $253$ of the text Introduction to Smooth Manifolds by John M. Lee it is explicitely said that generally the boudary of a smooth manifolds with corners is not a smooth manifolds with corners although it is not said that it is not a (not smooth) manifold with corners and so this confunsed me. Moreover I do not know if my definition of manifold with corners is effectively compatible with John M. Lee definition although it seemed to me it is.
So provided that the result is true I arranged a proof that I show to follow: I point out that the proposed solution is imperfect because I did not able to prove a little but important thing as me myself I am showing. So could someone help me, please?
MY PROOF ATTEMPT
Well by the preceding theorem we know that if $y$ is an element of $\partial M$ then there exist a coordinate patch $\phi:U\rightarrow V$ defined in an open set of $H^k_l$ such that
$$
y=\phi(x)
$$
for any $x\in\operatorname{bd}H^k_l$ and thus without loss of generality we can assume that $x^k$ is zero: indeed if $x\in\operatorname{bd}H^k_l$ then  it must be
$$
x^i=0
$$
for any $i=(k-l)+1,\dots,k$ so that if $\psi$ is the diffeomorphism that interchanges the $i$-th coordinate with the last (observe that $\psi$ is an involution that maps $H^k_l$ onto $H^k_l$) then $\phi\circ\psi$ is a coordinate patch about $y$ having the desired property. So we remember (click here for details) that if $W$ is an open set of $\Bbb R^k$ then
$$
W\cap\big(\Bbb R^{k-1}\times\{0\}\big)=A_W\times\{0\}
$$
for any open set $A_W$ of $\Bbb R^{k-1}$. Now we first assuem that it is $l=1$. So in this case the restriction of $\phi$ to $U\cap\operatorname{bd}H^k_1$ carries this set in a one to one fashion onto the open set $V\cap\partial M$ of $\partial M$. Now if $U$ is open in $H^k_1$ then there must exist an open set $W$ of $\Bbb R^k$ whose intersection with $H^k_1$ is equal to $U$ and thus putting
$$
\varphi(x):=\phi(x,0)
$$
for any $x\in A_W$ then we prove that $\varphi$ is a coordinate patch about $y$. So clearly $\varphi$ is of class $C^r$ because $\phi$ is; moreover the derivative of $\phi$ has rank $(k-1)$ because $D\varphi(x)$ consists simply of the first $(k-1)$ columns of the matrix $D\phi(x,0)$; finally $\phi$ is injective and its immage $V\cap\partial M$ is open in $M$ and the inverse function $\varphi^{-1}$ is continuous because it is equal to the function $\phi^{-1}$ followed by the projection of $\Bbb R^k$ onto its first $(k-1)$ coordinates. So we conclude that $\varphi$ is a coordinate patch about $y$ defined in an open set of $\Bbb R^{k-1}$. Now we let assume that $l>1$. So since $U$ is open in $H^k_l$ then
$$
U=W\cap H^k_l
$$
for any open set $W$ of $\Bbb R^k$ and thus
$$
U\cap\operatorname{bd}H^k_1=(W\cap H^k_l)\cap\operatorname{bd}H^k_1=(W\cap\operatorname{bd}H^k_1)\cap H^k_l=\\\big(W\cap(\Bbb R^{k-1}\times\{0\})\big)\cap(H^{k-1}_{l-1}\times[0,+\infty))=(A_W\times\{0\})\cap(H^{k-1}_{l-1}\times[0,+\infty))=(A_W\cap H^{k-1}_{l-1})\times\{0\}
$$
so that we let to prove that the function $\varphi$ defined in $A_W\cap H^{k-1}_{l-1}$ through the equation
$$
\varphi(x):=\phi(x,0)
$$
for any $x\in A_W\cap H^{k-1}_{l-1}$ is a coordinate patch about $y$. So clearly $A_W\cap H^{k-1}_{l-1}$ is open in $H^{k-1}_{l-1}$ and by analogous arguments applied above $\varphi$ is a $C^r$ injective function whose derivative has maximum rank and whose inverse is continuous but unfortunately I did not able to show that the immage of $\varphi$ is effectively open in $\partial M$ so that I can not claim that $\varphi$ is a coordinate patch about $y$.

A: Actually, every smooth manifold with corners is also a topological manifold with boundary, and therefore its boundary is a topological manifold (without boundary).
To see why, let $\overline{\mathbb R}{}^n_+$ be the "model corner space":
$$
\overline{\mathbb R}{}^n_+ = \{ (x^1,\dots,x^n)\in\mathbb R^n: x^1\ge 0,\dots,x^n\ge 0\}.
$$
It's relatively easy to show that $\overline{\mathbb R}{}^n_+$ is homeomorphic to the closed upper half-space $\mathbb H^n =\{(x^1,\dots,x^n): x^n\ge 0\}$ (see Exercise 16.18 in my ISM). Thus every smooth chart with corners can be composed with a homeomorphism $ \overline{\mathbb R}{}^n_+\to \mathbb H^n$ to obtain a topological boundary chart, and the result follows.


text:
Q: Sending binary data via WebSocket in NodeJS/ESP32 - how to recognize binary and text messages I'm working on a CCTV camera with ESP32-Cam and NodeJS server. The way I want to do it is to use WebSocket client on the ESP and send binary data with captured frames to NodeJS server, which then will forward it to connected users. I can't use socket.io, so I'm using plain websockets (on node 'ws' module).
What I'm struggling about is that while sending binary data I can't tell what kind of message it is, meaning if it is stream, thumbnail, or a plain json message.
My ESP32-Cam client code (C++):
void liveCam(uint8_t num){
    //capture a frame
    camera_fb_t * fb = esp_camera_fb_get();
    if (!fb) {
        Serial.println("Frame buffer could not be acquired");
        return;
    }

    webSocket.sendBIN(num, fb->buf, fb->len);

    //return the frame buffer back to be reused
    esp_camera_fb_return(fb);
}

And what I'm working on in Node:
this.socket.on("connection", (ws) => {
            ws.on("message", (msg) => {
                // recognize channel of msg and process it (ArrayBuffer / JSON String)
            })
        })

To send JSON I would use webSocket.sendTXT (using WebSocketsServer library) method on the ESP, just I don't know how to handle both binary and text messages on the server, and how to let the server recognize them (something like message tag, so binary stream would be "stream" while json would be "blink" or "fetch_temp", depending on usage). Without a binary stream I would do it just with json, so every message would have a "tag" and "message" property, but the image stream complicates things.
I had an idea to send a json text message before binary message, that would set the channel for the next message sent. Just no idea if it could work, if it wouldn't break if messages would come out of sync (is that possible?). Also, I need a solution as fast as possible (to stay at good framerate of the video, now clear binary stream is really neat!)
Thanks for any (good) ideas and solutions!

A: You're asking how to tell whether the data you send over a web socket is binary or JSON. Easy problem to solve. As you pointed out, just prefix the data with an indication of what's coming next. If you're worried about performance, don't send JSON as the prefix, send a single character - say, "B" to indicate the next message is binary or "J" to indicate that it's JSON.
And no, websocket messages cannot get out of sync unless your code makes a mistake. Websockets provide a reliable, ordered stream of bytes. Each byte is guaranteed to be received in order, exactly once, correctly, or you'll receive an error if the websocket isn't able to do this. "Correctly" is a bit of a stretch on an unencrypted connection - an unencrypted web socket will protect against simple network errors but it won't protect against intentional tampering by an attacker.


text:
Q: Create a shortcut to folder in Windows Anyone know the fix for creating a shortcut to a folder.  According to the article at the link below, all you need to do is change the first parameter to CoCreateInstance to CLSID_FolderShortcut and it will create a folder shortcut instead of a file shortcut.  This isn't the case, it does create the shortcut but it doesn't work.
When you view the properties of the shortcut, "Target type" is empty, it should be "File folder".  I am trying this on Windows 7.  Creating file shortcuts works fine using the sample code.
http://msdn.microsoft.com/en-us/library/bb776891(VS.85).aspx#Shellink_Creating_Shortcut


text:
Q: Algorithm to determine if a range contains a case-insensitive search phrase? Let's say you have thousands of files organized in the following way: First you sort them by their filename (case sensitive, so that upper case files come before lower case), then you grouped them into folders that contain the name of the first and the last file in that folder. E.g., the folders may look like:
Abel -> Cain
Camel -> Sloth
Stork -> basket
basking -> sleuth
tiger -> zebra

Now, given a case-insensitive search string s, determine which folders that can contain a file that matches s. You cannot and do not have to look inside a folder - the file does not actually have to exist.
Some examples:
("Abel", "Cain")    matches s = "blue",   since it contains "Blue"
("Stork", "basket") matches s = "arctic", since it contains "arctic"
("FA", "Fb")        matches s = "foo",    since it contains "FOo"
("Fa", "Fb") does NOT match s = "foo"

Formally: Given a closed range [a,b] and a lower case string s, determine if there's any string c in [a,b] such that lower(c) = s.
My first hunch was to do a case-insensitive search against the bounds of the range. But it can be easily seen from the last example that this is not correct.
A bruce-force solution is to generate all potential file names. For example, the input string "abc" would produce the candidates "ABC", "ABc", "AbC", "Abc", "aBC", "aBc", "abC", "abc". Then you just test each against the bounds. An example of this brute-force solution will follow below. This is O(2^n) though.
My question is if there's an algorithm for this that is both fast and correct?

Brute-force solution in Clojure:
(defn range-contains
  [first last string]
  (and (<= (compare first string) 0)
       (>= (compare last string) 0)))

(defn generate-cases
  "Generates all lowercase/uppercase combinations of a word"
  [string]
  (if (empty? string)
    [nil]
    (for [head [(java.lang.Character/toUpperCase (first string))
                (java.lang.Character/toLowerCase (first string))]
          tail (generate-cases (rest string))]
      (cons head tail))))

(defn range-contains-insensitive
  [first last string]
  (let [f (fn [acc candidate] (or acc (range-contains first last (apply str candidate))))]
    (reduce f false (generate-cases string))))

(fact "Range overlapping case insensitive"
  (range-contains-insensitive "A" "Z" "g") => true
  (range-contains-insensitive "FA" "Fa" "foo") => true
  (range-contains-insensitive "b" "z" "a") => false
  (range-contains-insensitive "B" "z" "a") => true)

A: I think that instead of creating all the upper-lower case combinations, this can be solved by checking upper, then lower for each character separately, which changes 2^N into 2N.
The idea is the following:

*

*keep "lowdone" and "highdone" flags, which indicate whether s can definitely come after the low limit while still potentially coming before the high limit, and vice versa

*go character by character through the string

*check if the uppercase version of the current letter can come after the corresponding low limit letter while at the same time coming before the high limit letter, then check the same for the lowercase version of the letter, if neither letter satisfies both conditions, return false (don't check low limit if "lowdone" is true, don't check high limit if "highdone" is true - when comparing ABC and ACA, once we are past the second letter, we don't care about the third letter)

*if a case satisfies both conditions, check if it comes strictly after the low limit letter or the low limit is too short to have a corresponding letter, if so, lowdone = true

*analogous for highdone = true

Does this sound good? Code in C# (could probably be written more concisely):
        public Bracket(string l, string u)
        {
            Low = l;
            High = u;
        }

        public bool IsMatch(string s)
        {
            string su = s.ToUpper();
            string sl = s.ToLower();

            bool lowdone = false;
            bool highdone = false;
            for (int i = 0; i < s.Length; i++)
            {
                char[] c = new char[]{su[i], sl[i]};

                bool possible = false;
                bool ld = lowdone;
                bool hd = highdone;
                for (int j = 0; j < 2; j++)
                {
                    if ((lowdone || i >= Low.Length || c[j] >= Low[i]) && (highdone || i >= High.Length || c[j] <= High[i]))
                    {
                        if (i >= Low.Length || c[j] > Low[i])
                            ld = true;

                        if (i >= High.Length || c[j] < High[i])
                            hd = true;

                        possible = true;
                    }
                }
                lowdone = ld;
                highdone = hd;

                if (!possible)
                    return false;
            }

            if (!lowdone && Low.Length > s.Length)
                return false;

            return true;
        }
    }

A: In the spirit of full disclosure, I guess I should also add the algorithm I came up with (Java, uses Guava):
public static boolean inRange(String search, String first, String last) {
    int len = search.length();
    if (len == 0) {
        return true;
    }

    char low = Strings.padEnd(first, len, (char) 0).charAt(0);
    char high = Strings.padEnd(last, len, (char) 0).charAt(0);

    char capital = Character.toLowerCase(search.charAt(0));
    char small = Character.toUpperCase(search.charAt(0));

    if (low == high) {
        if (capital == low || small == low) {
            // All letters equal - remove first letter and restart
            return inRange(search.substring(1), first.substring(1), last.substring(1));
        }
        return false;
    }

    if (containsAny(Ranges.open(low, high), capital, small)) {
        return true; // Definitely inside
    }

    if (!containsAny(Ranges.closed(low, high), capital, small)) {
        return false; // Definitely outside
    }

    // Edge case - we are on a bound and the bounds are different
    if (capital == low || small == low) {
        return Ranges.atLeast(first.substring(1)).contains(search.substring(1).toLowerCase());
    }
    else {
        return Ranges.lessThan(last.substring(1)).contains(search.substring(1).toUpperCase());
    }
}

private static <T extends Comparable<T>> boolean containsAny(Range<T> range, T value1, T value2) {
    return range.contains(value1) || range.contains(value2);
}


text: Q: Как указать пути до исходников в Qt Creator Есть динамическая библиотека собранная с отладочной информацией и исходники к ней. При отладке приложения которое использует эту библиотеку QtCreator показывает символы из этой библиотеки, но как их сопоставить с исходниками?


text:
Q: Why was StackOverflow throwing a 'Runtime Error'? For a couple of minutes, I got...
Server Error in '/' Application.
Runtime Error
Description: An exception occurred while processing your request. Additionally,
another exception occurred while executing the custom error page for the first
exception. The request has been terminated.

I'm curious what happened...  I couldn't even post a question to meta during the error condition...

A: We're looking into why you saw an error, but the event was caused by SQL coming online in New York.
We're using SQL 2012 Always On Availability groups as part of our high availability architecture.  How this works is the primary database server for that group (these are currently moved to Oregon due to Sandy) streams changes to the replicas.
Due to a lack of power in New York (status updates on our NY datacenter can be found here, here and here), we are keeping our equipment there off as much as we can.  However, the replicas for SQL being down mean the backlog of changes needed to sync to them builds up in Oregon, at the rate of about 40GB that needs sending every 6 hours.
To relieve these logs (which we could tolerate for up to ~4 days) we spin up the New York SQL boxes to receive changes and let the logs clear out on the primary.  On this latest spin up, the combination of no domain controller in New York online and the SQL boxes coming up simultaneously caused the windows clustering service to fail on NY-SQL01, and while the SQL cluster on top of this windows cluster assessed what was wrong, the databases were unavailable.
The app should have thrown a nice error page during this at least, we'll look into that.
We're by no means sitting around idle after our failover to Oregon.  There are many, many things still happening, but we'll try and keep the interruptions to a minimum.


text:
Q: Access UserDictionary Content Provider on android API level 23 I'm developing a android application which aims to show a list on the screen with the contents present in the user dictionary.
The problem is that when I compile and run the application in the Android API Level 23 Content Provider return a Cursor with no item, without any data.
It's strange because the API's preceding 23 (22, 21, 19, ...) the app runs and displays the data in the ListView normally.
Below is the code of my Activity:
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.provider.UserDictionary;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {

private ListView listView;
private SimpleCursorAdapter adapter;
private static final String[] COLUMNS = {
        UserDictionary.Words.WORD,
        UserDictionary.Words._ID,
        UserDictionary.Words.LOCALE
};

private static final int[] LIST_ITEM_VIEWS = {
        R.id.name,
        R.id.id_word,
        R.id.locale
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.list);

    adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.item_list, null, COLUMNS, LIST_ITEM_VIEWS, 0);

    listView.setAdapter(adapter);

    getLoaderManager().initLoader(0, null, this);

}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return new CursorLoader(getApplicationContext(), UserDictionary.Words.CONTENT_URI, COLUMNS,
            null, null, UserDictionary.Words.WORD);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    adapter.swapCursor(data);

}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    adapter.swapCursor(null);
}
}

A: This was reported here: Android Issue Traker
Official response: Working as intended. This feature has been remove effectively since API 23.

A: There is an issue on API level 23 where the user dictionary provider returns a cursor with no data, even when the dictionary is populated.
A current work around is to use a device or emulator running API level 22 or lower. You can quickly make an API level 22 emulator.

A: According to the Android official document of UserDictionary, only IME and SpellChecker can access the UserDictionary.
Check the NOTE on this page: https://developer.android.com/reference/android/provider/UserDictionary.html


text:
Q: CSS class not being styled when it is rendered after an  tag I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard
 tag and I have
 tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the
 tag as well. If I remove the
 tags, every item in the list is correctly styled. If I wrap each link in the list inside a
 tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
#pane {
    float: right;
    width: 800px;
}

#pane p {
    margin-left: 15px;
    font-family: verdana;
    font-size: 12px;
}

#pane p a.link { font-size: 16px; }

Here is a sample of the HTML generated:

    Google - For finding stuff

    Newegg - For buying stuff

Has anyone else encountered this behavior and found a way to fix it with adding
 tags everywhere?

A: Is it necessary to wrap it as a paragraph?  If not then you can lose that tag and then it works without that clutter. http://jsfiddle.net/bqhC9/

        Google - For finding stuff

        Newegg - For buying stuff

A: You can't put an
 inside of a
 tag. If you try to, the browser automatically corrects it by closing the
 tag for you.  The second link is no longer within a
 element and so your CSS rules no longer apply.
This is what the browser fixes your code to and why your CSS classes are no longer applied.

    Google - For finding stuff

    Newegg - For buying stuff

A: A collection of links is probably more suited to an unordered list (UL) perhaps inside a NAV.
Your issue is caused because HR inside of P doesn't validate (and for a good reason). To confirm, I used this sample:
<!doctype html>

    <title>Test</title>

    Google - For finding stuff

    Newegg - For buying stuff

A p element's end tag may be omitted if the p element is immediately
  followed by an ...HR...

Source: http://www.w3.org/TR/html-markup/p.html#p
As @Bill pointed out, this leads to the parser closing the P when you don't expect it.
An HR reprsents a thematic break, which is semantically invalid inside of a paragraph. Logically (at least in English) a paragraph is supposed to contain a collection of related thoughts on a single theme, so this makes sense.

A: hr can't in p tag. you can change p tag to div
    <!doctype html>

    Google - For finding stuff

    Newegg - For buying stuff

A: Good answer on the
,

You'd be better off not using the
.
Style the a.link into display:block which will display the a tag just like the enclosing
 tag.
Also auto-close your

Then correct your css selector: #pane > a.link if you need to actually be that selective.  Probably better to just style a.link by itself, so that you can overwrite it with another selector later if required and not have issues with specificity.

A: I think that you have problem with your HR tag,
in XHTML you have to close your tag.
So your HR should look like

    Google - For finding stuff

    Newegg - For buying stuff

Than it should work, no reason not to.


text:
Q: How strong is Spider-man's webbing? Everyone is familiar with the friendly neighborhood Spider-man's webbing: both organic as shown in Sam Raimi's Spider-man, or the Web-shooters version from every other Spider-man incarnation. My question might sound a bit of an overthinking but, exactly how strong are his webs?
According to Marvel Wikia (here), it says:

The web line's tensile strength has been estimated to be 120 pounds per square millimeter of cross section.

Well, that's one heck of a tensile strength. But in the movies and literally every version of the animated series, we see the super-villains and even super-heroes breaking off the webs so easily (In the Ultimate Spider-man animated series, even a non-super powered villain like Batroc the Leaper breaks through the webbing). But on the other hand, sometimes even the strongest guys find it difficult to break through the webbing. Why is it so? Does Spider-man carry cartridges with webbing of various (tensile) strengths?

A: There are many different strengths. Spider-Man's webbing does have an immense tensile strength but is weaker in other areas like shear strength; so, in theory, it depends how the webbing is applied and thus what kind of forces the "webbee"can apply to it. Spider-Man can also fire his webbing in different "modes" as continuous ropes (likely the strongest) but also as sprays or globs both of which are probably easier to break.
Spider-Man's webbing also contains an enzyme that slowly breaks it down over time (it normal dissolves after an hour or so). While this is just speculation on my part, it likely also has to "harden" before it can provide its full strength; it is stored as a liquid. This hardening might depend slightly upon environmental conditions thus accounting for any random one-off times where ordinary humans are able to break out of Spider-Man's webs.


text:
Q: Add javascript var to href I have dropdown with different links, before that i have 2 radio buttons where you could select "mode".

  <input type="radio" name="mode" checked="checked" value="mode1">MODE1

  <input type="radio" name="mode" value="mode2">MODE2

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site
  </button>

Site1

Site2

Site3

And i use this code snippet to detect what mode is selcted and add it to var mode:
$(document).ready(function() {
    var myRadio = $('input[name=mode]');
    myRadio.on('change', function () {
        var mode=myRadio.filter(':checked').val();
    });
});

What i want to do is to add javascript var $mode to href tags.
href="http://example.com/index.php?mode={$mode}
How could i accomplish this ?
I think only way would be to do this with some javascript function ?
Its not possible to just "print" var to href ?
JSFIDDLE: https://jsfiddle.net/DTcHh/18683/

A:
Use data-* attribute to keep static href value to be used later. .change() will trigger change event initially to set the value of href attributes.

$(document).ready(function() {
  var myRadio = $('input[name=mode]');
  myRadio.on('change', function() {
    var mode = myRadio.filter(':checked').val();
    $('ul.dropdown-menu a').prop('href', function() {
      return this.getAttribute('data-href') + mode;
    })
  }).change();
});
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />

    <input type="radio" name="mode" checked="checked" value="mode1">MODE1

    <input type="radio" name="mode" value="mode2">MODE2

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Choose site

  </button>

Site1

Site2

Site3

Fiddle here

A: Try this :-
$(document).ready(function() {
    var myRadio = $('input[name=mode]');
    myRadio.on('change', function () {
        var mode=myRadio.filter(':checked').val();
        $("ul.dropdown-menu li a").each(function(){
           $(this).attr('href',$(this).attr('href').split('?')[0] + "?mode=" + mode);
        });
    }).change(); //trigger on page load
});

DEMO

A: Check this fiddle I've modified for you: https://jsfiddle.net/so2fw1o4/1/
Add this to your myRadio.on('change', function
//here change the urls
    $('.dropdown-menu a').each(function(){
      $(this).attr('href', $(this).data('url') + mode)
    })

And you will need to add data attribute to each link to store initial link
Site1

A: Although you already have some answers here, I figured I would post another alternative (not necessarily any better).
You could add a class to each link, handle their click events, and set the new window's location yourself to achieve a similar effect.
The following is a code snippet modifying the jQuery in your fiddle:
$(document).ready(function() {
  var myRadio = $('input[name=mode]');
  var mode = myRadio.filter(':checked').val(); // Initial setting

  myRadio.on('change', function () {
    mode=myRadio.filter(':checked').val();
  });

  $('.mode-link').click(function(e) {
    e.preventDefault(); //stop the click action

    // Check if the mode has been set
    if (mode) {
      // Create the href value
      var newHref = $(this).attr('href') + mode;

      // Open the new tab/window with the correct href value
      window.open(
        newHref,
        '_blank'
      );
    }
  });
});

I simply added the mode-link class to each a element in the dropdown, stored the radio button value change in a new variable mode, added the click event handler, and finally handled the click event to create the new href value and open a new tab/window with that location.
If you didn't want the new tab/window you could simply set location.href = newHref but this wouldn't mimic the new tab/window opening, hence why I use window.open().
I have a modified sample here: JSFiddle


text:
Q: Software based compositing on windows 7 This has been bothering me for ages. I have an oldish computer that I use just for internet etc..but it has an Intel GMA 900, so no aero. But how come if I remote desktop to it, it can have aero (using the software wddm) etc (EVEN over network). But I cant enable this software compositing while using it through its graphics card.
All I am saying is that over LAN, the aero is extremely smooth even though it is software compositing on an ancient Pentium 4. I even tried installing windows 7 in a Virtaulbox without any guest additions and graphics acceleration, and it worked perfectly.

My only question is that is there a way to enable this software compositing on windows 7 without RDP?

A: RDP doesn't send bitmaps across the network the way VNC, for example, does; instead it sends GDI commands, and leaves it up to the client how they will be rendered. If the machine hosting the RDP client can support Aero compositing, then you'll get compositing; if not, you won't. Either way, the RDP server host's graphics hardware is not involved, so what looks to you like software rendering actually isn't. And that, I'm afraid, is why you won't be able to get Aero compositing to work on the console of the machine in question, but only when you're RDPed into it from something with more capable graphics hardware.


text:
Q: MySQL Cluster - SQL node fail to connect Management Nodes I am trying to deploy a 2 machines MySQL NDB Cluster with  the following architecture:
192.168.1.12 – management node
192.168.1.12 – SQL node
192.168.1.12 – data node
192.168.1.13 – SQL node
192.168.1.13 – data node

The base operating system is Ubuntu 14.04 and the MySQL Cluster software version is 5.7.25. .
I've been following the APT repository installation method:
$ sudo apt-get install mysql-cluster-community-management-server
$ sudo apt-get install mysql-cluster-community-client
$ sudo apt-get install mysql-cluster-community-data-node
$ sudo apt-get install mysql-cluster-community-server

I configure just the first machine 192.168.1.12
The management and the fisrt data node are working correctly.
ndb_mgm> show
Connected to Management Server at: 192.168.1.12:1186
Cluster Configuration
---------------------
[ndbd(NDB)] 2 node(s)
id=2    @192.168.1.12  (mysql-5.7.25 ndb-7.5.13, starting, Nodegroup: 0)
id=3 (not connected, accepting connect from 192.168.1.13)

[ndb_mgmd(MGM)] 1 node(s)
id=1    @192.168.1.12  (mysql-5.7.25 ndb-7.5.13)

[mysqld(API)]   2 node(s)
id=4 (not connected, accepting connect from 192.168.1.12)
id=5 (not connected, accepting connect from 192.168.1.13)

My /var/lib/mysql-cluster/config.ini file reads as follows:
[ndb_mgmd]
HostName=192.168.1.12
DataDir=/var/lib/mysql-cluster

[ndbd]
HostName=192.168.1.12
NodeId=2
DataDir=/usr/local/mysql/data

[ndbd]
HostName=192.168.1.13
NodeId=3
DataDir=/usr/local/mysql/data

[mysqld]
HostName=192.168.1.12

[mysqld]
HostName=192.168.1.13

On the MySQL node the /etc/mysql/mysql.conf.d/mysqld.cnf file reads as:
[mysqld]
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
datadir         = /var/lib/mysql
log-error       = /var/log/mysql/error.log
bind-address=192.168.1.12

ndbcluster
ndb-connectstring=192.168.1.12

[mysql_cluster]
ndb-connectstring =192.168.1.12

my.cnf(in 192.168.1.12) file reads as:
[mysql_cluster]
ndb-connectstring =192.168.1.12

And this my log file /var/log/mysql/error.log:
2019-02-26T21:18:07.772650Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 720710ms. The settings might not be optimal. (flushed=0 and $
2019-02-26T21:18:33.499413Z 0 [Warning] NDB: server id set to zero - changes logged to bin log with server id zero will be logged with another se$
2019-02-26T21:18:33.499926Z 0 [Note] NDB Binlog: Starting...
2019-02-26T21:18:33.500418Z 1 [Note] NDB Binlog: Started
2019-02-26T21:18:33.500438Z 1 [Note] NDB Binlog: Setting up
2019-02-26T21:18:33.500569Z 1 [Note] NDB Binlog: Created schema Ndb object, reference: 0x0, name: 'Ndb Binlog schema change monitoring'
2019-02-26T21:18:33.500684Z 1 [Note] NDB Binlog: Created injector Ndb object, reference: 0x0, name: 'Ndb Binlog data change monitoring'
2019-02-26T21:18:33.500708Z 1 [Note] NDB Binlog: Setup completed
2019-02-26T21:18:33.500720Z 1 [Note] NDB Binlog: Wait for server start completed
2019-02-26T21:18:33.500836Z 0 [Note] NDB Util: Starting...
2019-02-26T21:18:33.500936Z 2 [Note] NDB Util: Wait for server start completed
2019-02-26T21:18:33.501068Z 0 [Note] NDB Index Stat: Starting...
2019-02-26T21:18:33.501097Z 0 [Note] NDB Index Stat: Wait for server start completed
2019-02-26T21:18:33.603096Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data$
2019-02-26T21:18:33.607559Z 0 [Warning] CA certificate ca.pem is self signed.
2019-02-26T21:18:33.609426Z 0 [Note] Server hostname (bind-address): '192.168.1.12'; port: 33$
2019-02-26T21:18:33.609456Z 0 [Note]   - '192.168.1.12' resolves to '192.168.1.12';
2019-02-26T21:18:33.609491Z 0 [Note] Server socket created on IP: '192.168.1.12'.
2019-02-26T21:18:33.702507Z 0 [Note] Event Scheduler: Loaded 0 events
2019-02-26T21:18:33.702850Z 0 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.7.25-ndb-7.5.13'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Cluste$
2019-02-26T21:18:33.702987Z 2 [Note] NDB Util: Wait for cluster to start
2019-02-26T21:18:33.703018Z 0 [Note] NDB Index Stat: Wait for cluster to start
2019-02-26T21:18:33.703086Z 1 [Note] NDB Binlog: Check for incidents
2019-02-26T21:18:33.703101Z 1 [Note] NDB Binlog: Checking for any pending binlog purges
2019-02-26T21:18:33.703132Z 1 [Note] NDB Binlog: Wait for cluster to start
2019-02-26T21:19:03.754192Z 0 [Warning] NDB : Tables not available after 30 seconds.  Conside$

I start the nodes by using those commands
#Management node
sudo ndb_mgmd -f /var/lib/mysql-cluster/config.ini --bind-address=192.168.1.12

#Data node
sudo ndbd --bind-address=192.168.1.12

#SQL node
sudo service mysql start

NOTE: I tested only the machine with IP adress 192.168.1.12

A: You are trying to start a cluster with 2 nodes, but only start 1 node.
This is possible, but requires using a special option when starting
ndbd/ndbmtd, if I remember correctly this parameter is called
-no-wait-nodes. Check more in documentation. So the way you start above
the cluster will wait indefinitely for another node to start.
The MySQL Server will not start since the cluster isn't started.


text:
Q: oracle apex not work the Error: The Network Adapter could not establish the connectio [
I install orcle database and oracle apex locally but
I am getting this error, when try to open the workspace

also the same schema when try to connect through the sql developer not connect and error show
How can I fix that?

A: To connect to the database, you make a request to a "listener" which then hands off your connection to the database.  The listener listens (hence the name) on a port. If your listener is not running, or you are sending your request on the wrong port, then you see errors like this, because we can't find the listener.
Try this on a command line:
lsnrctl status
If you get errors, then your listener probably is not running. Go into Services, and you look for OracleTNS.... and start that. If your output suggests the listener is up and running already, then look for the information about the port and IP address (or hostname) that it is listening on.  You then use those for your connection details in SQLDev and ORDS and the like.


text:
Q: Jersey and Guice and nice JSON I have a project which uses Jersey 1.7, Guice 3.0 and has some JAXB annotated classes which are serialized through resources to XML and JSON. I'd like to configure the JSON output using a ContextResolver as suggested in several questions here on SO, as well as in the Jersey User Guide. This involves creating a JSONJAXBContext like this:
public class JaxbResolver implements ContextResolver<JAXBContext> {

    private final JAXBContext context;

    public JaxbResolver() throws Exception {
        this.ctx = new JSONJAXBContext(
            JSONConfiguration.
                natural().
                humanReadableFormatting(true).
                build(),
            Resource1.class, Resource2.class);
    }

    /* ... */
}

My problem is, that some of my resource classes have dependencies which are to be injected by Guice, like this:
public class DisplayConfigResource {
    private final ConfigRunner cr;

    @com.google.inject.Inject
    public DisplayConfigResource(ConfigRunner cr) {
        this.cr = cr;
    }

    /* ... */
}

If I remove my JaxbResolver from the game, everything works fine except that I have no control over the generated JSON (and the default is really weird, like removing the []s from single-element collections, ...). So it seems it's common sense to plug a ContextResolver like mine into Jersey so I can tune the JSON to something I like. But

*

*the JSONJAXBContext class really likes to have no-arg constructors on the resources while

*my resources really like to have their dependecies injected in their constructors.

So my question is how to resolve this situation and have Jersey, Guice and JSON play nicely together?

A: You can also use Jackson instead of JAXB for JSON marshal/unmarshal. It uses the same @XmlRootElement, @XmlType, etc annotations and it produces a more standard output (and does not need those fancy ContextResolver natural configuration stuff).
First configure your web.xml:
<servlet>
  <servlet-name>jersey</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
  </init-param>
</servlet>

Then add the jersey-json dependency in your pom.xml:
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-json</artifactId>
  <version>1.7</version>
</dependency>

A: I had similar problem and I resolved it by creating custom JAXBContextResolver and manually specifying which classes are going to play nicely with json serialization:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

    private JAXBContext context;
    private Class<?>[] types = {DtoIdNazov.class, DtoLokalitaPoloha.class, DtoListRestauracie.class, DtoDetailRestauracia.class};

    public JAXBContextResolver() throws Exception {
        JSONConfiguration jsonConfiguration = JSONConfiguration.natural().build();
        this.context = new JSONJAXBContext(jsonConfiguration, types);
    }

    public JAXBContext getContext(Class<?> objectType) {
        for (Class<?> type : types) {
            if (type == objectType) {
                return context;
            }
        }
        return null;
    }
}