text:
Q: PHP CURL is not sending xml in post method I am trying to connect with a telecom operator using their API Documentation.
I need to send XML request (in POST) to them along with some credentials in GET method.
I build my script and post XML, but they said they are not receiving any xml.
<?php
$url = "http://<IP>:<PORT>/C2SReceiver?LOGIN=abc&PASSWORD=123";
$xml = '<?xml version="1.0"?>
        <COMMAND>
            <TYPE>k59</TYPE>
            <DATE>19/03/2015 23:20:20</DATE>
            <PIN>11000009</PIN>
            <LOGINID>abc</LOGINID>
            <PASSWORD>123</PASSWORD>
            <EXTCODE>0100</EXTCODE>
            <EXTREFNUM>1230567890</EXTREFNUM>
        </COMMAND>';

    $headers = array(
        "Content-type: text/xml",
        "Content-length: " . strlen($xml),
        "Connection: close",
    );
    // configure
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    // requesting
    $data = curl_exec($ch);
    // displaying response in XML
    echo $data;
    if(curl_errno($ch))
        print curl_error($ch);
    else
        curl_close($ch);
?>

When I send the request, their system says: "Invalid Message format from HashMap"
They said, they are only getting the parameters via get method. They didn't receive any XML.
Please note:: if I change the xml format, their system response "Invalid XML".
If they are not getting my XML, how could they say its invalid.
I've waste a full day to solve that. no idea whats going wrong. Please take a look and suggest me what can I do from my end.
Thanks.

A: Try changing the header content-type from text/xml -> application/xml. On my CURLOPT_HTTPHEADER when doing doing a HTTP request:
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));

A: Your Code do not have any bug.I tested it to my end and i got the xml format data in C2SReceiver.php file.i just use this code for getting xml format data.
<?php $x = new SimpleXmlElement(file_get_contents('php://input')); print_r($x);die(); ?>

or
<?php $x = new SimpleXmlElement(file_get_contents('php://input')); print_r($x);die(); ?>

for getting xml data in C2SReceiver.php passed by curl


text:
Q: Spring boot Stomp WebSocket multiple session for same user I have a spring boot application where I am using Stomp over websockets and using RabbitMQ as external message broker. Our application is using spring security as well. Same authenticated user can get logged inn using different browsers. User can subscribe at some destination to fetch live data feeds using Js client of SockJS. At backend we use simpleMessageTemplate.convertAndSentToUser method to push live feeds to particular authenticated user.
Issue we are facing is that when user login using browser A and subscribe to a destination, A Unique queue like data-feeds-user123 is created at RabbitMq with auto-delete policy, and same user login from different browser B but does not subscribe to destination. Now when backend publishes live data feed using convertAndSendToUser method, A strange behaviour happens A new queue is created data-feeds-321 and messages are published at both queues. Although queue data-feed-321 does not have any consumer and it does not gets deleted when user gets disconnected/close session. Such queues seems useless in such scenario and does not get purged automatically.
Can anyone help me out on this, I don't want to broadcast the messages unless user subscribed from JS client.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to view data of a specific row in a database when a specific row is clicked in a table Here is my coding. I want to view data when i click any row on my table. But it view only the first data on row. What do you think is the problem?
My code on retrieving data from database is working. But when i click it, it always view the data of the first retrieved data row.
<?php

$sql = "SELECT * FROM courses";
if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        echo "
";
            echo "
";
                echo "COURSE CODE	";
                echo "COURSE NAME	";
                echo "ACTION	";
            echo "
";
        while($row = mysqli_fetch_array($result)){
            echo "
";
                echo "" . $row['course_code'] . "	";
                echo "" . $row['course_desc'] . "	";
                echo "";
                    echo "";
                        echo "Enroll";
                    echo "";
                echo "	";
            echo "
";

            echo "
";
                echo "
";
                    echo "
";
                        echo "
";
                            echo "<button type='button' class='close' data-dismiss='modal'>×</button>";
                            echo "
Confirm course to enroll.

";
                            echo "
Course Name:&nbsp&nbsp " . $row['course_desc'] . "
";
                            echo "
Course Code:&nbsp&nbsp " . $row['course_code'] . "
";
                            echo "
Price:&nbsp&nbsp " . $row['course_price'] . "
";
                                echo "
";
                                    echo "";
                                        echo "Confirm Enrollment";
                                    echo "";
                                echo "
";
                        echo "
";
                    echo "
";
                echo "
";
            echo "
";

        }
        echo "
";

        mysqli_free_result($result);
    } else{
        echo "No courses found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);

}

mysqli_close($link);
?>

Can anyone help me on this?

A: Your problem is that all your modals has the same DOM ID. You need them to be something unique, and the target to the modal must reflect that, so that each row opens the correct modal.
Assuming that course_code is unique in the database, you can use that. Then we update the line to open the modal,
echo "";

And the modal ID itself,
echo "
";

Notice how I appended -".$row['course_code']." to the data-target attribute and the modal ID.


text:
Q: $\int_{-2}^2\frac{x^2}{x^4+1} \sin(2x)dx$ Please, without using that the function is odd on [-2,2] then the integral is 0, is there an other method to calculate the integral $\int_{-2}^2\frac{x^2}{x^4+1} \sin(2x)dx$ ?
Thank you

A: How about:
$$I(t)=\int_{-2}^2\frac{x^2}{x^4+1}\sin(tx)dx$$
$$I'(t)=\int_{-2}^2\frac{x^3\cos(tx)}{x^4+1}dx=\left[\frac 14\ln|x^4+1|\cos(tx)\right]_{x=-2}^2+\frac 14\int_{-2}^2\ln(x^4+1)t\sin(tx)dx$$
$$I'(t)=\frac{\ln 17}{2}\cos(2t)+\frac 14\int_{-2}^2\ln(x^4+1)\sin(tx)tdx$$
$$I(T)-\int_{-2}^2\frac{x^2}{x^4+1}dx=\frac{\ln 17}{2}\int_0^T\cos(2t)dt+\frac 14\int_0^T\int_{-2}^2\ln(x^4+1)\sin(tx)tdxdt$$
Now try changing the order of integration in the final integral or using $u,v$ substitution to obtain a result. Once you get a formula for $I(t)$ notice that your original integral is just $I(2)$


text:
Q: How to bind to a list that nested deep in the DataContext object in WPF I need to bind to a list of objects that is hidden deep inside the DataContext object and it doesn't seem to be working for me. Here is my DataContext object:
public class UserDataContext
{
    public ObservableCollection<UserViewModel> Users { get; set; }
    public UsersSettingsViewModel UserSettings { get; set; }
}

public class UsersSettingsViewModel
{
    public int Id { get; set; }
    public ObservableCollection<Subscriptions> Subscriptions { get; set; }
}

I have a list of users, bound to Users property and when a user is selected, I want to display settings defined for the user. Settings are kept in UsersSettingsViewModel class and at the moment it is just a list of user's subscriptions.  I set DataContext to an instance of UserDataContext at the beginning. Then I dynamically load UserSettingsViewModel object for the selected user in the SelectionChanged event handler:
private void OnUserSelectionChanged(object sender, SelectionChangedEventArgs e)
{
   if (lwUsers.SelectedItem == null)
       return;

   var selectedUser = (UserViewModel)lwUsers.SelectedItem;
   var settings = _usersSettingsDal.Load(selectedUser.Login) ?? _usersSettingsDal.Create(selectedUser.Login);
   UserDataContext.UserSettings = _usersSettingsDal.ToViewModel(settings);
}

Although I don't have any problems in binding to Users property from XAML, for some reason I can't get the Subscriptions property to be displayed at all. It just doesn't do anything:
<GroupBox Header="Subscriptions" Name="gbSubscriptions">
                            <StackPanel Margin="10,10,10,10">
                                <ListView ItemsSource="{Binding UserDataContext.Subscriptions}">
                                    <ListBox.ItemTemplate>
                                        <DataTemplate>
                                            <StackPanel>
                                                <TextBlock Text="{Binding Path=Name, diag:PresentationTraceSources.TraceLevel=High}"   />
                                                <CheckBox IsChecked="{Binding Path=Enabled, diag:PresentationTraceSources.TraceLevel=High}" />
                                            </StackPanel>
                                        </DataTemplate>
                                    </ListBox.ItemTemplate>
                                </ListView>
                            </StackPanel>
                        </GroupBox>

Do I need to refresh DataContext somehow? Or maybe UserDataContext.Subscriptions is not a legitimate path for Binding? Any thoughts?

A: Referencing nested properties using Binding Paths is very similar to referencing the same properties in code. Take these examples:
int age = SomeParent.SomeChild.Age;

"{Binding Path=SomeParent.SomeChild.Age}"

SomeObject object = SomeCollection[0].SomeChild.SomeObject;

"{Binding Path=SomeCollection[0].SomeChild.SomeObject}"

double value = SomeClass.SomeObjectProperty.SomeCollection[0].SomeProperty;

"{Binding Path=SomeClass.SomeObjectProperty.SomeCollection[0].SomeProperty}"

For a more substantial list of Binding Path syntax, please view the Binding.Path Property page on MSDN.

A: Could you try to use this binding instead of yours:
<ListView ItemsSource="{Binding Path=UserDataContext.UserSettings.Subscriptions}">

A: Basically when you do:
UserDataContext.UserSettings = _usersSettingsDal.ToViewModel(settings);

you should raise a propertychange event as @toadflakz says, something like:
RaiseProperyChanged(()=>UserDataContext.UserSettings);

And the binding is also incorrect. The correct is as @Greenonion says:
<ListView ItemsSource="{Binding Path=UserDataContext.UserSettings.Subscriptions}">


text:
Q: Subir archivos a carpeta especifica Quiero subir un archivo a una carpeta especifica, pero la ruta la estoy sacando de una consulta de base de datos, pero cuando le doy subir me lo guarda en la ruta raíz.
$query = mysql_query("SELECT * FROM registros WHERE id_prod = '$id'") or die("consulta".mysql_error());
$result = mysql_fetch_array($query);

$dir = $result['dir_archivo'];

$archivo = (isset($_FILES['archivo'])) ? $_FILES['archivo'] : null;
if ($archivo) {
   $extension = pathinfo($archivo['name'], PATHINFO_EXTENSION);
   $extension = strtolower($extension);

   $extension_correcta = ($extension == 'PDF' or $extension == 'pdf' or $extension == 'AI' or $extension == 'ai');

   if ($extension_correcta) {

      // $ruta = $dir.$archivo['name'];
      // $ruta_destino_archivo = $ruta;
      // $ruta_destino_archivo = "archivos/{$archivo['name']}";
      $archivo_ok = move_uploaded_file($archivo['tmp_name'], $dir.$archivo['name']);

A: En base a lo que yo utilizo te puedo facilitar el siguiente script
$nombre_archivo = $_FILES['archivo']['name']; //Obteniendo el nombre del archivo
$ruta_destino = "miruta/cualquiera/";

//$_SERVER['DOCUMENT_ROOT'] = la carpeta raiz donde esta el proyecto
$carpeta_destino=$_SERVER['DOCUMENT_ROOT'] . $ruta_destino;

//Movemos el archivo al directorio temp al directorio deseado.

move_uploaded_file($_FILES['foto_perfil']['tmp_name'], $carpeta_destino . $nombre_archivo);

El codigo $_SERVER['DOCUMENT_ROOT'] puede ser reemplazado por algun lugar que elijas en el disco duro del servidor; por ejemplo una carpeta destinada a fotos de perfil de usuaris.


text:
Q: Mysql Left Join with WHEN clause, WHERE and CONCATE I am trying to solve one mysql query. I have TWO Databases e.g. A and B.
Database A has table ABC and Database B has table XYZ.
Joining condition phoneno from ABC = phoneno or cellphone from XYZ.
ABC Table

XYZ Table

Required Output

A: SELECT
a.mId AS mId,
CASE WHEN (a.pId = 0 OR a.pId IS NULL)
     THEN x.id
     ELSE a.pId
     END AS pId,
CASE WHEN (x.firstname IS NOT NULL)
     THEN CONCAT(x.firstname, ' ', x.lastname)
     ELSE a.pName
     END as pName,
a.phoneno as phoneno
FROM ABC a
LEFT JOIN XYZ x ON a.phoneno = COALESCE(x.phoneno, x.cellphone);

A: I am only interested in rows from table B.XYZ supplying missing values for rows in table A.ABC for which column pid = 0. So:
select t1.mid,
       t1.pid,
       if(t2.id is null, t1.pName, concat_ws(' ', t2.firstname, t2.lastname)) as pName,
       t1.phoneno
from A.ABC t1 left join B.XYZ t2 on t1.pid = 0 and t1.phoneno in (t2.phoneno, t2.cellphone)
;


text:
Q: Получение доступа к службе кластера Доброе утро:)!
кое как удалось получить и разобраться как достучаться до служб удаленного компьютера, но возник еще один вопрос:
-имеется некий удаленные сервер состоящий из несколько компов объединенных в кластер, необходимо получить доступ к службам этого кластера, к сожалению пока ничего не нашел, а при доступе через WMI и класс WIN32 получаю доступ только к службам самих компов.
попробовал по совету с другого форума через Failover Cluster Provider Reference
вот получившийся код:
ObjectQuery query = new ObjectQuery("select * from MSCluster_Service");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject queryObj in queryCollection)
{
    Console.WriteLine("Status: {0}", queryObj["Status"]);
    Console.WriteLine("Name: {0}", queryObj["Name"]);
}

просто все примеры которые нашел по ссылкам, они на C++, а я до него пока не дошел и немного не догоняю те примеры...
но в данном моем случае что тут не так, соединение проходит, запрос вроде правильный и я так понимаю по нему должно нам предоставить массив служб, которые и выводим foreach, но почему-то  выдает ошибку :

*

*когда в пошаговой обработке отрабатываешь и наводишь на значение queryCollection, то уже пишет System.Management.ManagementExeption

*а при начале цикла форич, даже в тело не входит и выдает ошибку сразу на условии выдает: Invalid class
Подскажите, пожалуйста!


text:
Q: `console.log([])` and `console.log([].toString())` provide different outputs I've noticed that, in NodeJS, console.log([]) and console.log([].toString()) produce [] and a blank string, respectively. I'm wondering why this is so and how I can get the output of console.log([]) as a string?
I understand for arrays, I can simply wrap the .toString() with brackets [], but for other constructed objects, say a Buffer:
var b = new Buffer('hi');

console.log(b); // <Buffer 68 69>
console.log(b.toString()); // hi
console.log('' + b); // hi

Is is possible to get the bare console.log(b) output as a string so I can perhaps concatenate it with another string?
Thanks.

A: I guess you use node.js.
Read the documentation. console.log uses util.format.
So the answer is:
var util = require('util');
var b = new Buffer('hi');
var str = util.format(b);


text:
Q: Good idea / Bad idea (/other ideas ?) I have recently been asked to make an Eclipse Rcp view that would be "pretty".
In that purpose I had fist looked at Java2D (after my boss advised me so) before the client's query turned to be more like
"It would be smooth if you could do some flash or something ..."
From there JavaFx seemed appealing to me however I never had a chance to use it before. I then were wondering if before to dive "head first" anyone (who would have preferably used it seriously) had any advice, warning or any constructive comment to do about using this product in an RCP view (so based on SWT).
I really long to know if JavaFx meets it's promises.
Thanks in advance and have a good day !
[EDIT]I dont want an Eclipse Fancy skinning or to make views appear with light effects or in a CompizFusion way,
What I want is to display fancy animations and pretty visual effects within a specific view that will be called sometimes. (Sorry I wasn't clear in the first place :s)[/EDIT]
*I'll pass on the "What's pretty and what's not ?" and other "Tastes are a personnal thing" debates, here "pretty" simply means to qualify a view containing convoluted transparancies and subtle animations ...

A: Eclipse RCP can also be customized in the way it looks, e.g. when you dont want to have the Eclipsi-L&F. Its called Presentation API, I saw a quite amazing UI once in a presentation but I cannot find it right now. Anyway, I just want to point you the direction, since I personally havent used this API (yet).
There are also some "skins" available for download.

*

*Nebula

*MP3 Manager
EDIT: Just found the slides. It goes quite into detail, but when you have a look at the last slide...it doesnt look like the Eclipse you know :-)

A: JavaFX uses Swing as default layout engine, so you'll gain nothing using it rather than Java2D.
On the other hand, using either your home-grown toolkit or Swing is generally a bad idea when working with Eclipse, as it already embeds the SWT toolkit. The main advantage of SWT over Swing is that it use the OS native widgets. Using another toolkit will lead to the following issues:

*

*Poor integration with Eclipse look&feel.

*Poor integration with Eclipse views and editors management.

A: The answer is simple. No, you can't use JavaFX yet. The problem is that JFX script can't be embedded into Swing nor Eclipse SWT. We already know about such an issues. (The is some kind of hack how to embed JFX into Swing APP only.)


text:
Q: Update Item Cart change to delete and add i want change update item in woocomerce. I use plugin (sumo measures) to calculate metadata (size, pack) and when I try to update quantity of cart product metadata dont change.
My idea to solution problem is remove item from cart and add.
My code:
add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
function on_action_cart_updated( $cart_updated ){

    WC()->cart->empty_cart();

    foreach( WC()->cart->get_cart() as $cart_updated ){
             $product_id = $cart_updated['product_id'];
         WC()->cart->add_to_cart( $product_id, $cart_updated['quantity'] );
    }

}

But code dont work.

A: I find using this action hook : woocommerce_update_cart_action_cart_updated
Using this you can get the cart data: $cart = WC()->cart->cart_contents;
You can get the cart itemmeta and quantity and then update the Sumo measures cart item data.
Because to remove and re-add the product with updated quantity will be the length process and also there will be much other factors need to take care.
Please let me know if you find any issues.
Thanks.


text:
Q: Caliburn.Micro ListBox with ContextMenu No Target Found I have a MasterView that have a TabControl binding with a ListView. I split the List into a secondary View becouse i want to separare the two views. The ListView have to do some operation that have nothing in common with the MasterView.
Here the code of the MasterView.xaml
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cal="http://www.caliburnproject.org"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:view="clr-namespace:App"
    mc:Ignorable="d" x:Class="App.MasterView"
    Title="Setup Cylinder"
    WindowStartupLocation="CenterScreen"
    Height="732" Width="986"  >
<Grid Margin="0,0,0,0" Background="#FF837F80" >
    <TabControl SelectedIndex="{Binding CycleIndex}" Grid.Column="0" ItemsSource="{Binding Items}" Margin="0,5,0,10">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <ContentControl cal:View.Model="{Binding}" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" IsTabStop="False" />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

Inside a MasterViewModel.cs there's a function called void public MenuItem_Open(). I want add a menu inside the ListView, that call the MenuItem_Open() of the MasterViewModel.cs.
Here is the code of the ListView.xaml
<UserControl x:Class="App.ListView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:cal="http://www.caliburnproject.org"
         xmlns:sys="clr-namespace:System;assembly=mscorlib"
         xmlns:local="clr-namespace:App"
         mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="517.5">
<Grid Margin="0,0,0,0" x:Name="LayoutRoot">
    <ScrollViewer   Margin="0,0,0,10" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">
        <ListBox  SelectedIndex="{Binding SelectedStepIndex}" x:Name="Steps" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  HorizontalContentAlignment="Left" VerticalContentAlignment="Center" AlternationCount="2">
            <ListBox.ContextMenu>
                <ContextMenu >
                    <MenuItem Header="New"  cal:Message.Attach="[Event Click] = [Action MenuItem_New()]"/>
                    <MenuItem Header="Copy"  />
                    <MenuItem Header="Paste" />
                </ContextMenu>
            </ListBox.ContextMenu>
        </ListBox>
    </ScrollViewer>
  </Grid>

The problem is always get the error "No Target found for MenuItem_New()".
I think the problem is related to the Visual Tree Broken, and i try more solution, but everytime i failed and i get the same error.
Any hint to solve this problem?
EDIT 1: Binding Error
<UserControl x:Class="App.ListView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:cal="http://www.caliburnproject.org"
         xmlns:sys="clr-namespace:System;assembly=mscorlib"
         xmlns:local="clr-namespace:App"
         mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="517.5">
<Grid Margin="0,0,0,0" x:Name="LayoutRoot">
    <ScrollViewer   Margin="0,0,0,10" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">
        <ListBox  SelectedIndex="{Binding SelectedStepIndex}" x:Name="Steps" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  HorizontalContentAlignment="Left" VerticalContentAlignment="Center" AlternationCount="2">
            <ListBox.ContextMenu>
                <ContextMenu >
                    <MenuItem Header="New"  cal:Message.Attach="[Event Click] = [Action MenuItem_New()]"/>
                    <MenuItem Header="Copy"  />
                    <MenuItem Header="Paste" />
<Button Command="{Binding ElementName=LayoutRoot, Path=DataContext.MenuItem_New}"/>
                </ContextMenu>
            </ListBox.ContextMenu>
        </ListBox>
    </ScrollViewer>
  </Grid>

A: The problem is (probably), that the Data Context of MenuItems is not the MasterViewModel, but it is DataContext of ListBox.
If I am accessing properties/methods of viewModel from nested items, I just use this : <Button Command="{Binding ElementName=LayoutRoot, Path=DataContext.ShowSessionDetail}" CommandParameter="{Binding SessionId}">
The LayoutRoot is name of element, which is located in root, hence its Data Context is the Data Context of ViewModel (you have also Grid with same name). Then in Path you say, you want to access Data Context of that element and then you can access methods/properties of it. This should work for you too.


text:
Q: Different versions in transitive dependencies in Gradle In my project I am forced to use these packages:

*

*com.sparkjava:spark-core:2.3, which ends up using jetty-server:9.3.2.v20150730

*org.apache.spark:spark-core_2.10:1.2.0, which ends up using jetty-server:8.1.14.v20131031
Note that com.sparkjava and org.apache.spark have nothing to do with each other. They are called both spark funnily.
The issue here is that both jetty versions are incompatible, so if I force jetty 8.X the system crashes, if I force jetty 9.X the system crashes again, I get java.lang.NoClassDefFoundError: org/eclipse/jetty/server/ServerConnector in one case and java.lang.NoClassDefFoundError: org/eclipse/jetty/server/bio/SocketConnector in the other.
What I am expected to do in such a situation ?
Note: I've tried to shadow jetty, but the dependency manager resolves just one (9.X by default, or 8.X if I force it) and then it shadows it, so it's really not helping.

A: It would be exceedingly difficult to resolve this situation.
Jetty 8.1 is about 4 major version behind Jetty 9.3, which represents many hundreds of releases of difference.

Note: Jetty versioning is [servlet_support].[major_ver].[minor_ver].
Jetty 8.x is Servlet 3.0, while Jetty 9.x is Servlet 3.1

The architecture of the connectors has evolved tremendously in that time frame, from being old school blocking Sockets in Jetty 8 to no blocking connectors at all in Jetty 9, with Jetty 9 needing to evolve the connectors to support features in TLS/1.2, and ALPN in order to properly support HTTP/2, and the internal I/O handling to support the new Servlet 3.1 Async I/O feature set.
Solution #1:
You won't be able to have both versions running in the same VM without some sort of classloader isolation, and careful configuration to ensure they don't claim the same resources (listening ports, temp files, etc)
Solution #2:
Upgrade (or downgrade) one or the other spark dependency till you hit a common jetty version.  (Spark_2.11 / 2.0.0 seems to support Jetty 9.2.x)
Solution #3:
Apache Spark is open source, go submit a patch that upgrades its use of Jetty to 9.3  (this might be difficult as Apache Spark isn't ready to use Java 8 yet, which is a requirement for Jetty 9.3)


text: Q: Проблема сегментации изображения. image thresholding problem, image segmentation Проблема заключается в том, что при проведение thresholding сегментации изображения, никак не получается разделить небо и фон, к небу постоянно добавляется ствол дерева, от которого отсвечивает солнечный свет. Пробовал несколько методов, например разделение по RGB каналам, но это не помогло. Если у кого, пожалуйста, опыт или совет, как можно провести сегментация данных типов изображений более точно?


text:
Q: Can I make powershell tab complete show me all options, rather than picking a specific one? In Powershell, if I type:
install-<tab>

Powershell tab completion will complete with a single command that starts with install-
Install-Package

And I can hit Tab again to see different completions.
Is it possible to have Powershell show all options that start with what I typed, like Linux or Unix shell? Eg, if I type:
install-<tab>

I get:
Install-Package
Install-PackageProvider
Install-Script

A: PSReadLine has a feature like this called MenuComplete. Instead of Tab, press Ctrl+space:

You can bind the MenuComplete function to tab with Set-PSReadLineKeyHandler:
Set-PSReadlineKeyHandler -Chord Tab -Function MenuComplete


text:
Q: How to run another code in PHP, if the code is successful? I am learning how to make login panel with session from here. I understood it fully, but I wanna open another file, in that code, when someone enter the right password + email, it only echo You have entered valid use name and password.
How to make it, clear everything on the page, and open a code (which I type)...
May be like, after I login, everything on the screen will get clear, and a image will open.

A: You can do this to the login function
add a variable to check if this user is logged in or not
<?php
        $msg = '';
        $logedin = false;
        if (isset($_POST['login']) && !empty($_POST['username'])
           && !empty($_POST['password'])) {

           if ($_POST['username'] == 'tutorialspoint' &&
              $_POST['password'] == '1234') {
              $_SESSION['valid'] = true;
              $_SESSION['timeout'] = time();
              $_SESSION['username'] = 'tutorialspoint';

              //echo 'You have entered valid use name and password';
              $logedin = true;
           }else {
                $logedin = false;
              $msg = 'Wrong username or password';
           }
        }
     ?>

then check if the user is logged in or not to see what you will show

  //if the user is NOT logged in
    <? if($loggedin){ ?>
     <form class = "form-signin" role = "form"
        action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);
        ?>" method = "post">

<?php echo $msg; ?>

        <input type = "text" class = "form-control"
           name = "username" placeholder = "username = tutorialspoint"
           required autofocus>

        <input type = "password" class = "form-control"
           name = "password" placeholder = "password = 1234" required>
        <button class = "btn btn-lg btn-primary btn-block" type = "submit"
           name = "login">Login</button>
     </form>

     Click here to clean Session.
     <? }else{ ?>
      // if user logged in yout code goes here
     <? } ?>

A: ya cool so simple, after echo line ie.'echo 'You have entered valid use name and password';', please use this or just replace the line
header('Location: http://www.example.com/');

you can use any link or local file at the place of this example link


text:
Q: What is the difference b/w @RequestParam and @QueryParam Anotation What is main difference between @RequestParam and @QueryParam in Spring MVC controller?

A: @QueryParam is a JAX-RS framework annotation and @RequestParam is from Spring.

A: Apart from these mentioned differences in framework, one major difference is @RequestParam will always expect a value to bind. Hence, if value is not passed, it will give error. This is not the case in @QueryParam
To explicitly give the option, use required = false while using @RequestParam

A: In addition to above another difference I observed is QueryParam do not translate parameters values to List type however RequestParam does.
What I mean is "@RequestParam("para") List param" is able to convert comma separated param values to List, @QueryParam fails to translate this.

A: I'll try to shed some more detailed light on this question.
Let's start with semantics of Query Parameter vs. Request Parameter, respectively @QueryParam vs. @RequestParam
Query Parameter, according to the HTTP Specification and also according to this annotation's (@QueryParam) implementation JAX-RS, represents the parameter found in query string. i.e. the string which follows the question-mark in the full request URL.
Request Parameter, according to the HTTP Specification and also according to this annotation's (@RequestParam) implementation Spring MVC (org.springframework.web.bind.annotation), represents the parameter of HTTP request, and to be clear here, it doesn't specify which type of parameter it is - query, header, body or etc.

Now let's talk about implementations per se.

@QueryParam
@QueryParam annotation belongs to JAX-RS specification, which states, that:

@QueryParam Binds the value(s) of a HTTP query parameter to a resource
  method parameter, resource class field, or resource class bean
  property

Pay attention here, it's query parameter which is bound to resource method's parameter (i.e. parameter in query string)

@RequestParam
@RequestParam on the other hand, belongs to Spring Framework, which states, that:

@RequestParam annotation indicates that a method parameter should be bound to a web request parameter.
  • In Spring MVC, "request parameters" map to query parameters, form data, and parts in multipart requests. This is because the Servlet API combines query parameters and form data into a single map called "parameters", and that includes automatic parsing of the request body.

Therefore, I think the names may be indeed a little bit misleading, but after digging in a little bit more, they are quite self-explanatory. Just try to stick with one when you want only query parameter and with another when you want any request parameter.


text:
Q: Package php7.2-mbstring unmet dependencies in Ubuntu 18.04 Try to install php-mbstring for mediawiki setup.
already added after first attempt universe repository: Package php7.2-mbstring missing in Ubuntu 18.04
But gives me hard time
Here details:
usertilo@myserver4:~$ sudo apt-get install php-mbstring
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php-mbstring : Depends: php7.2-mbstring but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

usertilo@myserver4:~$ sudo apt-get install php7.2-mbstring
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 php7.2-mbstring : Depends: php7.2-common (= 7.2.3-1ubuntu1) but 7.2.7-0ubuntu0.18.04.2 is to be installed
E: Unable to correct problems, you have held broken packages.

usertilo@myserver4:~$ uname -a
Linux myserver4 4.15.0-29-generic #31-Ubuntu SMP Tue Jul 17 15:39:52 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

usertilo@myserver4:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:        18.04
Codename:       bionic

usertilo@myserver4:~$ sudo apt-get install -f
Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

usertilo@server4:~$ sudo apt-get install php7.2-common
Reading package lists... Done
Building dependency tree
Reading state information... Done
php7.2-common is already the newest version (7.2.7-0ubuntu0.18.04.2).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

*

*update add info requested from comments

usertilo@myserver4:~$ sudo apt-cache policy php7.2-common php7.2-mbstring
php7.2-common:
  Installed: 7.2.7-0ubuntu0.18.04.2
  Candidate: 7.2.7-0ubuntu0.18.04.2
  Version table:
 *** 7.2.7-0ubuntu0.18.04.2 500
        500 http://archive.ubuntu.com/ubuntu bionic-security/main amd64 Packages
        500 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages
        100 /var/lib/dpkg/status
     7.2.3-1ubuntu1 500
        500 http://archive.ubuntu.com/ubuntu bionic/main amd64 Packages
php7.2-mbstring:
  Installed: (none)
  Candidate: 7.2.3-1ubuntu1
  Version table:
     7.2.3-1ubuntu1 500
        500 http://archive.ubuntu.com/ubuntu bionic/universe amd64 Packages

usertilo@myserver4:~$ cat /etc/apt/sources.list
deb http://archive.ubuntu.com/ubuntu bionic main universe
deb http://archive.ubuntu.com/ubuntu bionic-security main
# deb-src http://archive.ubuntu.com/ubuntu bionic universe
deb http://archive.ubuntu.com/ubuntu bionic-updates main

usertilo@myserver4:~$ cat /etc/apt/sources.list.d/*
cat: '/etc/apt/sources.list.d/*': No such file or directory

A: You are missing some necessary channels from sources.list. Do sudo gedit /etc/apt/sources.list and make it look like this:
deb http://archive.ubuntu.com/ubuntu bionic main multiverse restricted universe
deb http://archive.ubuntu.com/ubuntu bionic-security main multiverse restricted universe
deb http://archive.ubuntu.com/ubuntu bionic-updates main multiverse restricted universe

Save and exit.
Then update your repository:
sudo apt update

Then install php-mbstring:
sudo apt install php7.2-mbstring

A: Your package information that apt knows about is out of date.
Using the rmadison tool, we can see all the versions of php7.2-mbstring in the repos:
 php7.2-mbstring | 7.2.3-1ubuntu1         | bionic/universe          | amd64, arm64, armhf, i386, ppc64el, s390x
 php7.2-mbstring | 7.2.7-0ubuntu0.18.04.2 | bionic-security/universe | amd64, arm64, armhf, i386, ppc64el, s390x
 php7.2-mbstring | 7.2.7-0ubuntu0.18.04.2 | bionic-updates/universe  | amd64, arm64, armhf, i386, ppc64el, s390x

though I am only showing the Bionic items here.
Because your system doesn't know about the newer php7.2-mbstring in the security or updates repos, you're getting a version mismatch.
Run this:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install php7.2-mbstring

This should assist in getting your versions back to where they need to be.  (Note you may wish to use dist-upgrade instead of upgrade so that packages such as updated kernel packages get installed and upgraded too)


text:
Q: tonic_build add/use external crates like serde I'm trying to use or add an external create like serde, to the build.rs file that tonic_build will use to generate the .rs file from the .proto file.
// build.rs file
    let proto_file = "src/hello/hello.proto";

    tonic_build::configure()
        .build_server(true)
        .out_dir("./src/hello")
        .type_attribute("HelloRequest", "#[derive(Deserialize, Serialize)]") // adding attributes
        .compile(&[proto_file], &["."])
        .unwrap_or_else(|e| panic!("protobuf compile error: {}", e));

I can see the attributes are added to the rust file, see below :
#[derive(Deserialize, Serialize)]
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct HelloRequest {
    #[prost(string, tag="1")]
    pub id: ::prost::alloc::string::String,
    #[prost(string, tag="2")]
    pub message: ::prost::alloc::string::String,
}

but the file doesn't add: use serde::{Serialize, Deserialize}; causing the build to fail. I tried using server_mod_attribute but failed. how can I add use serde::{Serialize, Deserialize} to the auto-generated .rs file using tonic_build?

A: you can use the full path to the library
.type_attribute("HelloRequest", "#[derive(serde::Deserialize, serde::Serialize)]")


text:
Q: How to test window.open is being called from a react component I have a react component that renders a series of other components, each with their own checkbox.
There is a state hook called rulesToDownload which begins as an empty array and has ids added to / removed from it as checkboxes are checked / unchecked.
When the 'download' button is clicked, the rulesToDownload array is passed to a data function DownloadFundDataById that forEach's over the array and calls window.open for each value with an api call with the id appended. The data function is imported into the component, not passed in as a prop.
This causes multiple tabs to flash up before closing when the data downloads. It's not perfect but it works.
I want to complete my test coverage and need to test that the function gets called on button click, and that it does what it should.
Any help appreciated.
Code below:
Summary.test.js:
 it(`should create correct download array when some rules are selected`, async () => {
        global.open = sandbox.spy();

        fetch.mockResponseOnce(JSON.stringify(selectedRules));

        wrapper = mount();
        await act(async () => {} );
        wrapper.update();

        wrapper.find('ReportProgressSummary').first().find('input').last().simulate('change', {target: {checked: true}});

        wrapper.find('button').first().simulate('click');
        expect(global.open).to.have.been.called();

    });

I can confirm that all the 'find' statements are correct, and correctly update the checked value.
Summary.js:
const Summary = () => {
    const [expand, setExpand] = useState(false);
    const [buttonText, setButtonText] = useState("expand other rules");
    const [rulesToDownload, setRulesToDownload] = useState([]);
    const [data, setData] = useState([]);
    const [dataLoadComplete, setDataLoadComplete] = useState(false);
    const [dataLoadFailed, setDataLoadFailed] = useState(false);

    useEffect(() => {
            loadData();
    }, []);

    const loadData = async () => {
        try {
            let importedData = await ExecuteRules();
            setData(importedData);
            setDataLoadComplete(true);
        } catch (_) {
            setDataLoadFailed(true);
        }
    };

    const onButtonClick = () => {
        setExpand(!expand);
        if(!expand) setButtonText("hide other rules");
        else setButtonText("expand other rules");
    };

    const modifyDownloadArray = (id, checked) => {
        let tempArray;
        if(checked) tempArray = [...rulesToDownload, id];
        else tempArray = [...rulesToDownload.filter(ruleId => ruleId !== id)];
        setRulesToDownload([...tempArray]);
    };

    const dataFilter = (inputData, isFavouriteValue) => {
        return inputData.filter(rule => rule.isFavourite === isFavouriteValue)
                 .sort((a, b) => a.percentage - b.percentage)
                 .map((rule, i) => {
                    return <ReportProgressSummary
                                result={rule.percentage}
                                id={rule.id}
                                title={rule.name} key={i}
                                modifyDownloadArray={modifyDownloadArray}
                            />
                    })
    };

    return (

            {
                dataLoadFailed &&

Rule load failed

            }
            {
                !dataLoadComplete &&
                    <LoadingSpinnerTitle holdingTitle="Loading rule data..."/>
            }
            {
                dataLoadComplete &&
                <Fragment>
                    <PageTitle title="System Overview"/>
                    <LineAndButtonContainerStyled>
                        <ContainerStyled>
                            {
                                dataFilter(data, true)
                            }
                        </ContainerStyled>
                        <ContainerStyled>
                            <ButtonStyled
                                    disabled={!rulesToDownload.length}
                                    onClick={() => DownloadFundDataById(rulesToDownload)}>
                                download
                            </ButtonStyled>
                        </ContainerStyled>
                    </LineAndButtonContainerStyled>

                    <LineBreakStyled/>

                    <ButtonStyled onClick={() => onButtonClick()}>{buttonText}</ButtonStyled>
                    {
                        expand &&
                        <ContainerStyled>
                            {
                                dataFilter(data, false)
                            }
                        </ContainerStyled>
                    }
                </Fragment>
            }

    )
};

export default Summary;

DataMethod.js:
export function DownloadFundDataById(downloadArray) {
    downloadArray.forEach(id => window.open(baseApiUrl + '/xxxx/xxxx/' + id));
}

I can confirm the url is fine, just replaced for now
TestSetup:
const doc = jsdom.jsdom('<!doctype html>')

global.document = doc;

global.window = doc.defaultView;

configure({ adapter: new Adapter() });

global.expect = expect;
global.sandbox = sinon.createSandbox();
global.React = React;
global.mount = mount;
global.shallow = shallow;
global.render = render;
global.fetch = jestFetchMock;
global.act = act;

chai.use(chaiAsPromised);
chai.use(sinonChai);
chai.use(chaiEnzyme());
chai.use(chaiJestDiff());

console.error = () => {};
console.warn = () => {};

Current test output says that global.open is not being called. I know this makes sense as it isn't actually assigned as a prop to the onClick of the button or anything. This I think is one of my issues - I can't assign a stub to the button directly, but I'm trying not to re-write my code to fit my tests...

A: Managed to get this working with a couple of updates to my test file:
it(`should create correct download array when some rules are selected`, async () => {
        global.open = sandbox.stub(window, "open");

        fetch.mockResponseOnce(JSON.stringify(selectedRules));

        wrapper = mount();
        await act(async () => {} );
        wrapper.update();

        wrapper.find('ReportProgressSummary').first().find('input').last().simulate('change', {target: {checked: true}});

        wrapper.find('button').first().simulate('click');
        expect(global.open).to.have.been.called;

    });

the sandbox.spy() was updated to a sandbox.stub() with (window, "open")
thanks to this article for the help!
https://github.com/mrdulin/mocha-chai-sinon-codelab/blob/master/src/stackoverflow/53524524/index.spec.js
Also the expect statement using to.be.called() is actually not a function and so was updated to to.be.called


text:
Q: Solving two-dimensional recurrence relation $a_{i,\ j}\ =\ a_{i,\ j-1}\ +\ a_{i-1,\ j-1}$ How to approach the following two dimensional recurrence relation ?

For $i,j\ge2$,
  $$a_{i,\ j}\ =\ a_{i,\ j-1}\ +\ a_{i-1,\ j-1}$$
  where $a_{p,\ 1}=1$ (for $p\ge1$) and $a_{1,\ q} = 1$ (for $q\ge1)$.

A: One way to go about this, and generally about solving recurrence relations, is to use generating functions. In this case this will lead to bivariate generating function.
Let's suppose we have $f(x,y)=\sum_{i,j=0}^{\infty}a_{i,j} x^i y^j$ formal powers series which encodes coefficients of our sequence. To simplify further computation, I have shifted the sequence so that $a_{0,q}=a_{p,0}=1$, but don't worry about that, it is shifted back at the end. Let's play with coefficients a little to see if we can get better form of $f(x,y)$:
\begin{align}
f(x,y)&=\sum_{i,j\geq0}a_{i,j} x^i y^j \\
&=a_{0,0}+\sum_{i\geq 1}a_{i,0} x^i+\sum_{j\geq 1}a_{0,j} y^j + \sum_{i,j\geq1}a_{i,j} x^i y^j \\
\end{align}
We have shifted the indices so that we can later apply recurrence relation. But before proceeding, notice $a_{0,0}=1$ and also
$$
\sum_{i\geq1}a_{i,0} x^i = x+x^2+x^3+\dots = \frac{x}{1-x}
$$
and similarly for the second sum. So overall we have
$$
f(x,y) = 1+\frac{x}{1-x}+\frac{y}{1-y}+\sum_{i,j\geq1}a_{i,j} x^i y^j
$$
For the rightmost sum, we can apply recurrence relation, lets write
\begin{align}
\sum_{i,j\geq1}a_{i,j} x^i y^j &= \sum_{i,j\geq1}(a_{i,j-1}+a_{i-1,j-1}) x^i y^j \\
&= \sum_{i,j\geq1}a_{i,j-1} x^i y^j+\sum_{i,j\geq1}a_{i-1,j-1} x^i y^j \\
&= y\sum_{i,j\geq1}a_{i,j-1} x^i y^{j-1}+xy\sum_{i,j\geq1}a_{i-1,j-1} x^{i-1} y^{j-1}\\
\end{align}
We have moved the $x$,$y$ out of the sum, so that indices match. Let's just re-index the sum
\begin{align}
\sum_{i,j\geq1}a_{i,j} x^i y^j &= y\sum_{i,j\geq1}a_{i,j-1} x^i y^{j-1}+xy\sum_{i,j\geq1}a_{i-1,j-1} x^{i-1} y^{j-1}\\
&= y\sum_{i\geq1,j\geq0}a_{i,j} x^i y^{j}+xy\sum_{i,j\geq0}a_{i,j} x^{i} y^{j}\\
&= y\left(\sum_{i\geq0,j\geq0}a_{i,j} x^i y^{j}-\sum_{j\geq0}a_{0,j}y^j\right)+xy\sum_{i,j\geq0}a_{i,j} x^{i} y^{j}\\
&= y\left(f(x,y)-\sum_{j\geq0}a_{0,j}y^j\right)+xyf(x,y)\\
&= y\left(f(x,y)-\frac{1}{1-y}\right)+xyf(x,y)\\
\end{align}
Here we have just substituted back the definition of $f(x,y)$ itself. Putting back together we have
\begin{align}
f(x,y)=1+\frac{x}{1-x}+\frac{y}{1-y}+ y\left(f(x,y)-\frac{1}{1-y}\right)+xyf(x,y)\\
\end{align}
and after some simple algebraic manipulations we finally get:
\begin{align}
f(x,y) = \frac{1}{(1-x)(1-y-xy)}\\
\end{align}
The $f(x,y)$ encodes all of the coefficients in a compact way. We can try to write it in a way that will allow us to see the coefficients more clearly.
For this notice that $\frac{1}{1-x}=1+x+x^2+x^3+\dots$. Also second expression is well known generating function
$$\frac{1}{1-y-yx}=\frac{1}{1-y(x+1)}=\sum_{i,j\geq0}\binom{j}{i} x^i y^j.$$
So we can view our function in this form as a product
$$
f(x,y) = (1+x+x^2+x^3+\dots) \left(\sum_{i,j\geq0}\binom{j}{i} x^i y^j\right)
$$
Now to ask what is the value of $a_{i,j}$ is same as to ask what coefficient of $x^i y^j$ is in this product. It is not hard to see that it will be $\binom{j}{i}+\binom{j}{i-1}+\dots+\binom{j}{0}$. So overall, also with correcting the original offset from $i$ to $i-1$ and $j$ to $j-1$, we get the following,
$$a_{i,j} = \sum_{k=0}^{i-1}\binom{j-1}{k}.$$


text:
Q: Dexie DB liveQuery multiple collections I'm currently using DexieDB to store data in 10 different collections.
When a user is navigating to a single page, I collect data from these 10 different collections as the data source.
The main collection has an identifier that is being used to get the corresponding data from the other collections.
With the new liveQuery update I managed to get this working for a single collection, but I was wondering if I were to use it for multiple collection what the best approach would be.
Would it be better to create multiple subscriptions for the collections that need to be watched (not all of them), or would it be possible to create 1 subscription over multiple collections?
I looked in the docs, but all the examples include only one collection, and there isn't any documentation on how this would work with multiple collections.
Thank you in advance!

A: Both ways are possible. If you are in a Component based GUI framework (React, Angular, Svelte etc), one subscription per query is normally what to prefer becuase by splitting it so, a mutation affecting the query on the related collection will only trigger a re-render of its component instead of re-rendering also its parent.
That said, you can also perfectly well perform multiple queries within your callback to liveQuery and return an array or object containing the data. That way you will implicitly subscribe to all the visited queries.


text:
Q: Flex container doesn't shrink on wrap I need the flex container to shrink to fit content when the items in the container wraps. The items need to be of a fixed width.
How does one do it?
Here is an example:

      .wrapper {
        display: flex;
        border: 1px solid red;
        flex-wrap: wrap;
      }

      .item {
        height: 40px;
        background-color: green;
        margin: 10px;
        width: 300px;
      }


text:
Q: Finding each row's percentage of total SELECT I.[Order Number], SUM(CAST([Ext Price] AS FLOAT)) AS Rev
        FROM stg.Invoices I
        where i.[order number] = '64100097'
        GROUP BY I.[Order Number]

Gives me:
Order Number    Rev
64100097    124079.33

When I try to get the % of revenue per line using:
SELECT StgID,
CAST((CAST([Ext Price] AS FLOAT)) / (NULLIF(Rev,0)) AS FLOAT)
FROM stg.Invoices I
JOIN (
        SELECT I.[Order Number],
        SUM(CAST([Ext Price] AS FLOAT)) AS Rev
        FROM stg.Invoices I
        where i.[order number] = '64100097'
        GROUP BY I.[Order Number]
) as TotRev on I.[Order Number] = TotRev.[Order Number]

I get this:
StgID   RevPct
7006418 0.202934687026437
7006427 0.000460995397057673
7006417 0.0274442971282969
7006426 0.000415379418957211
7006422 0.0312703171430729
7006425 0.000609287622684616
7006424 0.0161187201768417
7006420 0.197365669205338
7006419 0.226870986489047
7006428 0.000134752500678397
7006421 0.10299056256993
7006423 0.193384345321658

Which totals up to: .08333333333
Shouldn't this all add up to 1?
I'm not understanding why I can't get each line to add up to a total percentage of 100%.
Here is proof that all of them should add up to the total:
select stgid, [ext price]
from stg.Invoices
where [order number] = '64100097'

stgid   ext price
7006420 24489
7006418 25180
7006427 57.2
7006417 3405.27
7006426 51.54
7006421 12779
7006423 23995
7006422 3880
7006425 75.6
7006424 2000
7006419 28150
7006428 16.72

A: Use window functions:
SELECT I.[Order Number], SUM(CAST([Ext Price] AS FLOAT)) AS Rev ,
       SUM(CAST([Ext Price] AS FLOAT)) / NULLIF(SUM(SUM(CAST([Ext Price] AS FLOAT))) OVER (), 0) as p_rev
FROM stg.Invoices I
WHERE i.[order number] = '64100097'
GROUP BY I.[Order Number];


text:
Q: Load only one ID element from another website I know I can do something like this
<!doctype html>

    <meta charset="utf-8">
    <title>Load remote content into object element</title>

And to load another web site in my page,but the problem is that on that url i have one element, and I want to get only specific ID content from that website like ID #sidebar-wrapper is that possible?

A: It is typically not possible to load content from another website and read it using JavaScript due to browser security restrictions. You will probably need a server-side script to download the data first on the server and then serve it to your client.


text:
Q: Bug?: The Playlist List API doesn't return the right thumbnails I'm using a WordPress plugin called WP YouTube Lyte, which internally uses the YouTube Data API v3. I've however noticed that the for playlists, the featured thumbnail simply doesn't match the one that is set on YouTube itself.
I've dug down a bit deeper and made direct API calls myself, to notice, that it wasn't a bug in the plugin, but rather in YouTube's API.
Here I've used the API explorer with the following playlist:
https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlists.list?part=snippet%252Cid&id=PL7EpZck9oTXT3z3DslPZQkXeKbEvqV840&_h=3&
In the thumbnails object, I am expecting the current featured playlist thumbnail, but instead in most cases, the API returns the thumbnails of the second video in the playlist.

A: As far as I know, the API's own documentation w.r.t. playlist's thumbnails (https://developers.google.com/youtube/v3/docs/playlists#snippet.thumbnails) does not define/specify such concept as featured thumbnail.
Indeed Youtube's site itself is using internally the same API, but please bear in mind that Google's systems are distributed and highly asynchronous -- therefore I find it acceptable to observe such differences as yourself noticed, as long as the API documentation is not specifying tighter guarantees.


text:
Q: Filtering the dates range based on the days I have a table with columns as
    Id (1)
    Date holding values as (2013-12-12 00:00:00)
    Start time (00:00:00)
    end time (01:00:00)
    value

The user will give the date range and will specify day like sunday ,monday etc .
How can I use a sql query to filter the dates and find the proper days between that for the specified days as well.

A: One way would be to use BETWEEN ... AND ... and DAYOFWEEK():
SELECT *
FROM   my_table
WHERE  Date BETWEEN ? AND ?
   AND DAYOFWEEK(Date) = ? -- 1=Sunday ... 7=Saturday


text:
Q: Removing duplicate code in rspec tests with fixtures I use Rspec and fixtures to test Rails models.
A few test cases have very similar code which looks like this
it 'creates request' do
  u = users(:user_one)
  o = documents(:document_one)
  requests = Request.where(status: Request::PENDING, user: u, document: o)
  expect { o.request_access(u) }.to change { requests.count }.by(1)
end

it 'does not create a request if user already has access' do
  u = users(:user_one)
  o = documents(:document_one)
  Request.create status: Request::ACCEPTED, user: u, document: 0
  requests = Request.where(status: Request::PENDING, user: u, document: o)
  expect { o.request_access(u) }.not_to change { requests.count }
end

How could I eliminate code duplication here? Is there a way to use let to solve the problem? What if I have more test cases where other fixtures are used and hence Request.where(status: Request::PENDING, user: u, document: o) refers to other objects?

A: This should be DRY enough. let all the things!
let(:user) { users(:user_one) }
let(:document) { documents(:document_one) }
let(:requests) { Request.where(status: Request::PENDING, user: user, document: document) }
let(:action) { document.request_access(user) }

context 'user does not have access' do
  it 'creates request' do
    expect { action }.to change { requests.count }.by(1)
  end
end

context 'user has approved access' do
  before do
    Request.create status: Request::ACCEPTED, user: user, document: document
  end

  it 'does not create a request' do
    expect { action }.not_to change { requests.count }
  end
end

A: You could use let or before(:each):
before(:each) do
  @u = users(:user_one)
  @o = documents(:document_one)
end

it 'creates request' do
  requests = Request.where(status: Request::PENDING, user: @u, document: @o)
  expect { @o.request_access(@u) }.to change { requests.count }.by(1)
end

it 'does not create a request if user already has access' do
  Request.create status: Request::ACCEPTED, user: @u, document: @o
  requests = Request.where(status: Request::PENDING, user: @u, document: @o)
  expect { @o.request_access(@u) }.not_to change { requests.count }
end

let(:u) { users(:user_one) }
let(:o) { documents(:document_one) }

it 'creates request' do
  requests = Request.where(status: Request::PENDING, user: u, document: o)
  expect { o.request_access(u) }.to change { requests.count }.by(1)
end

it 'does not create a request if user already has access' do
  Request.create status: Request::ACCEPTED, user: u, document: o
  requests = Request.where(status: Request::PENDING, user: u, document: o)
  expect { o.request_access(u) }.not_to change { requests.count }
end

EDIT: You can't add the requests query to a before filter because you have a Request.create before your query in the second test. Anyway, to DRY it you could create a method that returns the query:
let(:u) { users(:user_one) }
let(:o) { documents(:document_one) }

it 'creates request' do
  requests
  expect { o.request_access(u) }.to change { requests.count }.by(1)
end

it 'does not create a request if user already has access' do
  Request.create status: Request::ACCEPTED, user: u, document: o
  requests
  expect { o.request_access(u) }.not_to change { requests.count }
end

def requests
  Request.where(status: Request::PENDING, user: u, document: o)
end


text:
Q: Quickbook PHP API - Http Response Body are null or Empty I need customer list from Quickbooks Account. Quickbooks API call is as below
$dataService = DataService::Configure(array(
            'auth_mode' => 'oauth1',
            'consumerKey' => '',
            'consumerSecret' => '',
            'accessTokenKey' => '',
            'accessTokenSecret' => '',
            'QBORealmID' => '',
            'baseUrl' => 'https://quickbooks.api.intuit.com/'
        ));

$dataService->setLogLocation("./logs/");
$dataService->Query("SELECT * FROM Customer");

It gives error as below.

Fatal error: Uncaught QuickBooksOnline\API\Exception\SdkException:
  [0]: Http Status Code:[0] Http Response Body are null or Empty. thrown
  in
  Core/HttpClients/IntuitResponse.php
  on line 26

Please suggest me that what I have done wrong?


text:
Q: Remove google analytics from drupal site After exclude google analytics from drupal code the module still there,
How to remove google analytics module from drupal site completely ?

A: @leymannx is correct in his comment on your question. The correct order is to disable the module, uninstall it, and then delete it from your file system. However, from your question I gather that the module has already been removed from your file system. From this point, you want to delete references to it from your database.
Please note: this is a dangerous way to proceed and if you can simply restore your file system and follow the process @leymannx laid out, you should do so.
The process is outlined in this community doc. But the basic idea is to run one of these commands on your database:
Drupal 7: DELETE from system where type = 'module' AND name = 'google_analytics';
Drupal 8: DELETE FROM key_value WHERE collection='system.schema' AND name='google_analytics';
Then dump your cache and the module should be completely gone.


text:
Q: Convert a whole column of urls to clickable urls in a datatable of a shiny app How can I convert a whole column of urls in a dataframe displayed via DT::datatable() into clickable urls that will lead you to the relative webpages?
## app.R ##
library(shiny)
library(shinydashboard)
library(DT)

df<-structure(list(sub_indicator = c("peak concentrations", "Toxics Release Inventory",
                                     "American Housing Survey"), `Data Sources 1` = c("https://www.epa.gov/outdoor-air-quality-data/air-quality-index-report",
                                                                                "https://www.epa.gov/toxics-release-inventory-tri-program/tri-data-and-tools#triadvanced",
                                                                                "https://www.census.gov/programs-surveys/ahs/data/interactive/ahstablecreator.html?s_areas=00000&s_year=2021&s_tablename=TABLE1&s_bygroup1=1&s_bygroup2=1&s_filtergroup1=1&s_filtergroup2=1"
                                     )), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
                                     ))

ui <- dashboardPage(
  dashboardHeader(title = "Dataset Inventory"),
  dashboardSidebar(

  ),
  dashboardBody(
    dataTableOutput("table")
  )
)

server <- function(input, output) {

  output$table<-renderDataTable({
    datatable(
    df
    )
  })
}

shinyApp(ui, server)

A: You can make the links clickable by adding in html () and using almost your identical code except adding escape = false:
library(shiny)
library(shinydashboard)
library(DT)

df <- structure(list(sub_indicator = c("peak concentrations", "Toxics Release Inventory",
                                     "American Housing Survey"), `Data Sources 1` = c("https://www.epa.gov/outdoor-air-quality-data/air-quality-index-report",
                                                                                "https://www.epa.gov/toxics-release-inventory-tri-program/tri-data-and-tools#triadvanced",
                                                                                "https://www.census.gov/programs-surveys/ahs/data/interactive/ahstablecreator.html?s_areas=00000&s_year=2021&s_tablename=TABLE1&s_bygroup1=1&s_bygroup2=1&s_filtergroup1=1&s_filtergroup2=1"
                                     )), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
                                     ))

## Function to add HTML language to the links
make_link <- function(x){
  paste0("",x,"")
}
df$`Data Sources 1` <- make_link(df$`Data Sources 1`)

### Shiny app
ui <- dashboardPage(
  dashboardHeader(title = "Dataset Inventory"),
  dashboardSidebar(
  ),
  dashboardBody(
    dataTableOutput("table")
  )
)

server <- function(input, output) {
  output$table <- renderDataTable({
  df
  }, escape = FALSE) # added in escape = FALSE here
}

shinyApp(ui, server)

A: We could do
library(purrr)
library(dplyr)
server <- function(input, output) {

  output$table<-renderDataTable({
    datatable(
      df %>%
         mutate(`Data Sources 1` = map(`Data Sources 1`, ~ glue::glue('click')))
    )
  })
}

-output


text:
Q: Where is catalina_base and catalina_home located for tomcat6? I recently installed tomcat6 with apt-get and have got it up and running. Ubuntu doesnt set the $CATALINA_BASE and $CATALINA_HOME environment variables during the install. How can I locate these directories, so I can manually set them?

A: Both are stored and can be set in /etc/default/tomcat6. By default, CATALINA_HOME is /usr/share/tomcat6, and CATALINA_BASE is /var/lib/tomcat6.

A: In either Tomcat6 or Tomcat7 installed with Apt-Get, find the declarations of
CATALINA_HOME and CATALINA_BASE, in /etc/init.d/tomcat6 or tomcat7, and EXPORT them to the OS variables. They are then visible on a ENV command. and for use by other software.

A: I have ubuntu v10.
And I have tomcat v6 installed at which is at /usr/lib/tomcat6/...
Answer:
In my system, both variables are stored in /etc/init.d/tomcat6


text:
Q: Header setting under \usepackage{fancyhdr} \pagestyle{fancy}

In both the odd and even pages..."headrules"...means the horizontal line is not covering the full width of written texts as it is clearly visible from the uploaded images. The code of the chapter document which i have used is as follows:
\documentclass[12pt,twoside,a4paper]{book}
\usepackage[a4paper]{geometry}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead {}
\fancyhead [ER]{\footnotesize \sc Chernoff Distance for Conditionally Specified Models}
\fancyhead [OL] {\footnotesize\sc\rightmark}
\fancyhead [RO,LE] {\thepage}
\fancyfoot {}
\renewcommand{\headrulewidth}{0.4pt}
\usepackage{amsfonts}
\usepackage{latexsym,amsmath}
\usepackage{amssymb,array}
\usepackage{amssymb}
\parindent 0.0 cm
\makeatletter \oddsidemargin 0in \evensidemargin 0in \textwidth
16cm \RequirePackage[dvips]{graphicx} \textheight 20cm
\setlength\textheight{8.8in} \setlength\textwidth{6.25in}
\setlength\topmargin{0.0in}
\newtheorem{t1}{Theorem}[section]
\newtheorem{p1}{Proposition}[section]
\newtheorem{l1}{Lemma}[section]
\newtheorem{c1}{Corollary}[section]
\newtheorem{d1}{Definition}[section]
\newtheorem{r1}{Remark}[section]
\newtheorem{co}{Counterexample}[section]
\newtheorem{ex}{Example}[section]
\renewcommand{\baselinestretch}{1.2}
\numberwithin{equation}{section}
%\newcounter{equation}[section]
\renewcommand{\theequation}{\thesection.\arabic{equation}}

I need help to solve the issue. Kindly help in your spare time...if the answer is known.

A: use it this way:
\documentclass[12pt,twoside]{book}
\usepackage[a4paper,rmargin=0in, lmargin=0in,
   textwidth=16cm,textheight=20cm]{geometry}
\usepackage{graphicx}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead {}
\fancyhead [ER]{\footnotesize \sc Chernoff Distance for Conditionally Specified Models}
\fancyhead [OL] {\footnotesize\sc\rightmark}
\fancyhead [RO,LE] {\thepage}
\fancyfoot {}
\renewcommand{\headrulewidth}{0.4pt}
\usepackage{amsfonts}
\usepackage{latexsym,amsmath}
\usepackage{amssymb,array}
\parindent=0cm
\newtheorem{t1}{Theorem}[section]
[...]

then fancyhdr knows the exact page margins. Look into the documentation of geometry how pages can be defined. Margins of 0mm doesn't really make sense.


text:
Q: Consider the set of integers $\mathbb{ℤ}$ with the digital line topology. Find a proper subset of the integers that is dense in $\mathbb{ℤ}$ The digital line topology: For each odd integer we have a basis element $B(n)=\{n\}$. We regard each even integer $n$ as representing the boundary between $n − 1$ and $n + 1$. Associated to each even $n$ we have a basis element $b(n)=\{n-1,n,n+1\}$. Thus, in the digital line, every odd integer is an open set, and every even integer is a closed set.
A subset $A$ of a topological space $X$ is called dense if Cl(A) = X, and $y\in Cl(A)$ if and only if every open set containing $y$ intersects $A$.
I propose that the the subset of odd integers is dense in $\mathbb{Z}$.

A: Sure. Any non-empty open set contains a $B(n)$ or a $b(n)$, hence in the first case the odd number $n$ and in the second case the odd number $n+1$.


text:
Q: Cargo Collective traditional pagination The Cargo Collective developers (those who have contributed developer themes) seem to be enamored of autopagination. As such, I cannot seem able to find a code snippet that will show how to do traditional pagination. Ie. when I set my max number of articles to be "3", it shows only 3 at a time.
I don't mind that I will likely need to provide styles; I just need to know the combination of markup and handlebars required to get the raw pagination in place.
The documentation hints at some "automated" views, but doesn't provide much description of how to use them unless I'm missing something: views and models documentation.
As such, attempts were guesswork. My first such attempt was:

It seemed like you need a data-set to match, but it doesn't seem to indicate which of the data sets populates the Pagination view with useful data.
I tried a few things (no point listing them all as they were trying to catch lightning in a jar attempts) such as the following:

  {{Navigation}}

I don't think the above makes any particular sense and I didn't have any expectation it would work. Just wanted to illustrate that I tried a few things since I can't find any samples or appropriate documentation.
A point in the right direction for either of those two things would be greatly appreciated!

A: It looks like what you are asking for is a slideshow element.
There is an article on how to do this:
{slideshow}{image 1}{image 2}{image 3}{image 4}{/slideshow}

And there are also good support pages where you can explore further.
Update
All developer templates seems to be bound to Autopagination. See this discussion, as an example:

For a design that uses conventional page navigation inside the thumbnail index and text nav, you'll need to use a Non-Developer Design, like Biblio or Manhattan.

It also gives you tip, which (non-developer) templates to use if you need traditional navigation.


text:
Q: How to get admin order items from admin order quote I'm trying to get the items which are present in quote of admin order.
\Magento\Backend\Model\Session\Quote $adminQuote
\Magento\Sales\Model\AdminOrder\Create $adminCreate

to get the details but whenever i call call getItems, getAllvisibleItems, getAllItems its returning null value.
I need to get the item details which are under quote when you are placing an order from admin.
Can any one let me know how to do that.

A: You should use the \Magento\Backend\Model\Session\Quote to get the item details which are under quote when you are placing an order from admin.
    use \Magento\Backend\Model\Session\Quote;

    public function __construct(
            ...
            \Magento\Backend\Model\Session\Quote $backendQuoteSession
            ...
        ) {
            ...
            $this->backendQuoteSession = $backendQuoteSession;
            ...

        }

    public function yourFunction() {
       $items = $this->backendQuoteSession->getQuote()->getAllVisibleItems();

        foreach ($items as $item) {
        {
            echo 'ID: '.$item->getProductId().'
';
            echo 'Name: '.$item->getName().'
';
            echo 'Sku: '.$item->getSku().'
';
            echo 'Quantity: '.$item->getQty().'
';
            echo 'Price: '.$item->getPrice().'
';
            echo "
";
        }
    }

A: You can use the \Magento\Sales\Model\AdminOrder\Create . I have used this class to get the added product in cart.
In my case i need to restrict the place order based on the product items in  cart.To achieve this i have created a custom Block and checking the items in cart.
Step 1 :Added My custom Block in sales_order_create_index.xml
     <referenceContainer name="content">
          <block class="[Package]\[Namespace]\Block\Adminhtml\Cart\CustomBlock"  template="Package_NameSpace::[template_Name]"/>
     </referenceContainer>

Step 2 : Created a Block name as "CustomBlock.php"
     namespace [Package]\[Namespace]\Block\Adminhtml\Cart;

     use Magento\Backend\Block\Template\Context;
     use Magento\Sales\Model\AdminOrder\Create  as OrderCreate;

 class CustomBlock extends \Magento\Backend\Block\Template
 {
       /** @var  OrderCreate */
       protected $_orderCreate;

       /**
        * CustomBlock constructor.
        * @param Context     $context
        * @param OrderCreate $orderCreate
        * @param array       $data
        */
       public function __construct(
        Context $context,
        OrderCreate $orderCreate,
        array $data = []
      )
     {
        $this->_orderCreate = $orderCreate;
        parent::__construct($context, $data);
     }

   /**
    * Get Items Details
    */
   public function getItemsDetails()
   {
      $quoteData =  $this->_orderCreate->getQuote();
      foreach ($quoteData->getAllItems() as $item) {
         echo "Product Sku".$item->getSku();
         // Insert Your code here
      }

  }
}


text:
Q: Edge channels in Quantum Hall effect Why is the value of Hall conductance directly proportional to the number of edge channels in the sample?

A: In fact, the value of Hall conductance is NOT proportional to the number of edge channels in the sample. For example,
$\sigma_{xy}=\frac13 \frac{e^2}{h}$ FQH state has one edge channel, and
$\sigma_{xy}=\frac25 \frac{e^2}{h}$ FQH state has two edge channels.


text:
Q: Javascript slider, How to assign a max value for scrolling so it doesn't overflow? I'm wanting to set a min and max value for scrolling that way it isn't possible to scroll beyond the content inside of the slider. Right now, the code allows for infinite scrolling. I'm fairly new to Javascript but I've been coding for several years at a University.
JSFiddle
JavaScript
$('#vcards').width(function(){
var width = 0;
$('.vcard').each(function(){
    width += $(this).outerWidth(true);
});
return width;
}());
$('#next').on('click',function(){
$('#vcards').animate({left : "-=170"});
});
$('#prev').on('click',function(){
$('#vcards').animate({left : "+=170"});
});

CSS
#slider{
width:500px;
overflow:hidden;
position:relative;
border:1px solid black;
height:225px;
padding:10px;
}

.vcard{
width:150px;
margin: 0 10px;
height:200px;
float:left;
border:1px;
text-align:center;
font-weight:bold;
background-color:green;
}

#vcards{
position:absolute;
top:0;
left:-170px;
}

HTML

1

2

3

4

5

Next

Prev

A: You could try this:
$('#next').on('click',function(){
    var v_offset = $('#vcards').offset();
    var v_width = $('#vcards').width();
    var left = v_offset.left;
    var total = v_width - Math.abs(left);
    var cont_w = $('#slider').width();
    if(total>=cont_w)
    $('#vcards').animate({left : "-=170"});
    });

$('#prev').on('click',function(){
    var v_offset = $('#vcards').offset();
    var left = v_offset.left;
    if(left<=0)
    $('#vcards').animate({left : "+=170"});
    });


text:
Q: Can it be a wrong given CIDR? Am given some homework about creating 4 sub-nets out of a network address of 198.77.48.0/23. Clearly this is a class C address but can it even be possible to have a CIDR /23?
We took it otherwise and thought our tutor might have errored. That in order to create 4 sub-nets, we actually need a /26. In that way, we get the following sub-nets
Network addresses
198.77.48.0 -> 198.77.48.64 -> 198.77.48.128 -> 198.77.48.192
Hosts addresses : From
198.77.48.1 -> 198.77.48.65 -> 198.77.48.129 -> 198.77.48.193
Hosts addresses To
198.77.48.62 -> 198.77.48.126 -> 198.77.48.190 -> 198.77.48.254
Broadcast addresses
198.77.48.63 -> 198.77.48.127 -> 198.77.48.191 -> 198.77.48.255

A: I think i finally got the answer. This is like sub-netting an already sub-netted network.


text:
Q: Multiple table inheritance Rails and activerecord I'm trying to implement Multiple Table Inheritance with ActiveRecord. Looks like all the available gems are pretty old. Am I missing something? Is there any "native" way to implement this with activerecord?
I'm using Rails 3.2.3 and activerecord 3.2.1

A: Rails 6.1+ delegated type
Rails 6.1 added a "native" way to implement Multiple Table Inheritance via delegated type.
See the corresponding PR for details.

With this approach, the "superclass" is a concrete class that is represented by its own table, where all the superclass attributes that are shared amongst all the "subclasses" are stored. And then each of the subclasses have their own individual tables for additional attributes that are particular to their implementation. This is similar to what's called multi-table inheritance in Django, but instead of actual inheritance, this approach uses delegation to form the hierarchy and share responsibilities.

A: Single Table Inheritance (where each Car and Truck share one database)
class Vehicle < ActiveRecord
end

class Car < Vehicle
end

class Truck < Vehicle
end

In your case you are not sharing the database but rather the functions. You should then write a module and include it in each model
class Car < ActiveRecord
  extend VehicleFinders
end

class Truck < ActiveRecord
  extend VehicleFinders
end

module VehicleFinders
  def find_purchased
    #...
  end
end

So in extend module's method are class method on that calling class.include module's methods are instance method for object of calling class
This might be a good read for you http://raysrashmi.com/2012/05/05/enhance-rails-models


text:
Q: How to divide large csv file into multiple csv files using chunk size How to write spring batch configuration class for single csv into multiple csv files ,it should divide based on chunk size and it should divide into multiple csv file based on chunk capacity
How to write spring batch configuration class for single csv into multiple csv files ,it should divide based on chunk size and it should divide into multiple csv file based on chunk capacity
package com.codenotfound.batch;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.builder.FlatFileItemWriterBuilder;
import org.springframework.batch.item.file.transform.PassThroughLineAggregator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import com.codenotfound.model.Person;

@Configuration
public class HelloWorldJobConfig {

  @Bean
  public Job helloWorlJob(JobBuilderFactory jobBuilders,
      StepBuilderFactory stepBuilders) {
    return jobBuilders.get("helloWorldJob")
        .start(helloWorldStep(stepBuilders)).build();
  }

  @Bean
  public Step helloWorldStep(StepBuilderFactory stepBuilders) {
    return stepBuilders.get("helloWorldStep")
        .<Person, String>chunk(10).reader(reader())
        .processor(processor()).writer(writer()).build();
  }

  @Bean
  public FlatFileItemReader<Person> reader() {
    return new FlatFileItemReaderBuilder<Person>()
        .name("personItemReader")
        .resource(new ClassPathResource("csv/persons.csv"))
        .delimited().names(new String[] {"firstName", "lastName"})
        .targetType(Person.class).build();
  }

  @Bean
  public PersonItemProcessor processor() {
    return new PersonItemProcessor();
  }

  @Bean
  public FlatFileItemWriter<String> writer() {
    return new FlatFileItemWriterBuilder<String>()
        .name("greetingItemWriter")
        .resource(new FileSystemResource(
            "target/test-outputs/greetings.txt"))
        .lineAggregator(new PassThroughLineAggregator<>()).build();
  }
}

t


text:
Q: Automatically connect to wifi network in android? I am develping an app in which whenever wifi turned on then in background app should be to connect to a network if the network it connected to previously ?Can i use broad cast reciver for this purpose?

A: For receiving the Broadcast for connectivity change, you can listen like this:
Register your receiver in the AndroidManifest.xml
    <receiver
            android:name=".NetworkCheckReceiver"
            >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
   </receiver>

Then in the BroadcastReceiver class
public class NetworkCheckReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                Log.d("NetworkCheckReceiver", "NetworkCheckReceiver invoked...");

                boolean noConnectivity = intent.getBooleanExtra(
                        ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

                if (!noConnectivity) {
                    Log.d("NetworkCheckReceiver", "connected");
                    WifiConfiguration wifiConfig = new WifiConfiguration();
                    wifiConfig.SSID = String.format("\"%s\"", networkSSID);
                    wifiConfig.preSharedKey = String.format("\"%s\"", networkKey);
                    WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);

                    int netId = wifiManager.addNetwork(wifiConfig);
                    wifiManager.disconnect();
                    wifiManager.enableNetwork(netId, true);
                    wifiManager.reconnect();
                }
                else{
                    Log.d("NetworkCheckReceiver", "disconnected");
                }
            }
        }
 }

And of course, don't forget to add the required permissions
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>


text:
Q: Accidentally told Chrome to ignore Protocol Handler? I clicked a magnet link and Chrome gave me the popup saying "This site is trying to open an external app." I clicked the checkbox for it to never ask me again but I accidentally clicked the "Do Nothing" button. Now I can't seem to revert that decision.
As per this question, if I go to Settings > Content Settings (under Privacy) > "Manage Handlers..." nothing is listed. Right clicking a magnet link does not provide an "Open Link With..." option either. The question seems to be outdated.

A: After a little Googling, I found the answer.
Ensure Chrome is completely closed. No lingering extensions or icon in the system tray. Navigate to %LOCALAPPDATA%\Google\Chrome\User Data and there is a file named local state. Inside the file, look for protocol_handler and under that you'll find magnet: true, change it to false and save the file.
Following these instructions fixed my magnet problem.

A: For Google Chrome version 108.x on Windows 10

*

*Close Google Chrome

*Go to %LOCALAPPDATA%\Google\Chrome\User Data\Default\

*Open file Preferences with a text editor

*Look for protocol_handler and you will find <protocol>: true. Set it to false and save the file

A: The answer above did not work for me. But this one worked: (dont upvote my answer but his)

1) Goto URL chrome://settings/clearBrowserData
2) Select duration "Past week".
3) Select only "Cookies and other site data"
4) Click "Clear Browsing Data" and browse site again.


text:
Q: enable ephemeral containers AWS EKS I'm trying to debug a distroless POD by trying kubectl debug which uses ephemeral containers that are disabled by default in aws eks. I'm using aws eks 1.21
✗  kubectl debug -it opentelemetry-collector-agent-6hqvf --image=busybox --target=some-app

error: ephemeral containers are disabled for this cluster (error from server: "the server could not find the requested resource")

So how to enable them for EKS?

A: The Kubernetes v1.23 release (not yet available on EKS) moved the ephemeral containers feature from alpha to beta.
When EKS adds support for Kubernetes v1.23, it's possible that this will include the ephemeral container API. It's not possible to say with confidence which way AWS will go here.
If EKS does add support for this API, make sure that you're applying appropriate restrictions. The ability to run an ephemeral container changes the attack surface for your workload and for the cluster it runs on.

A: AWS EKS 1.23 now includes the feature
✗  k exec -ti ebs-csi-node-gn5g6 -- bash
Defaulted container "ebs-plugin" out of: ebs-plugin, node-driver-registrar, liveness-probe, debugger-sbn42 (ephem)
OCI runtime exec failed: exec failed: unable to start container process: exec: "bash": executable file not found in $PATH: unknown
command terminated with exit code 126

and via ephemeral containers:
✗  k debug -ti ebs-csi-node-gn5g6 --image=busybox --target=ebs-plugin
Targeting container "ebs-plugin". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-fzpnj.
If you don't see a command prompt, try pressing enter.
/ # ls
bin   dev   etc   home  proc  root  sys   tmp   usr   var
/ #


text:
Q: How to retain . dot in java regular expressions My program is as below,
    /**
     * @param args
     */
    public static void main(String[] args) {
        RegularExpressions r = new RegularExpressions();
        // TODO Auto-generated method stub
        String []input = {" Dear [name],\n",
                "\n",
                "Thanks for buying the [num] [item].\n",
                "We appreciate your patronage\n",
                "\n",
                "Best, [sales_person]\n"};
        HashMap<String, String> dic = new HashMap<String, String>();
        dic.put("name", "Anna Bell Smith");
        dic.put("num", "eight");
        dic.put("item", "Boxes of Soap.");
        dic.put("sales_person", "Karmine Smithe");
        String []afterChange = r.replace(input, dic);
        r.display(afterChange);

    }
    String [] replace(String []strings, Map<String, String> dict){
        String patternStr = ".(";
        for(String key:dict.keySet()){
            patternStr = patternStr + key + "|";
        }
        patternStr = patternStr.substring(0, patternStr.length()-1);
        patternStr = patternStr+").";
        Pattern pattern = Pattern.compile(patternStr);
        for(int i=0;i<strings.length;i++){
            StringBuffer sb = new StringBuffer();
            Matcher matcher = pattern.matcher(strings[i]);
            boolean isMatcherFind = false;
            while(matcher.find()){

            matcher.appendReplacement(sb, dict.get(matcher.group(1)));
                isMatcherFind = true;
            }

            if(isMatcherFind){
                strings[i] = sb.toString();
            }else{
                strings[i] = strings[i];
            }
        }
        return strings;

    }
    void display(String []str){
        for(String s:str){
            System.out.println(s);
        }
    }
}

The above program is giving an output like
Dear Anna Bell Smith
Thanks for buying the eight Boxes of SoapWe appreciate your patronage
Best, Karmine Smithe

While I am expecting output as
Dear Anna Bell Smith

Thanks for buying the eight Boxes of Soap.
We appreciate your patronage

Best, Karmine Smithe.

Meaning,  dot(.) and "\n" should be retained instead it is replacing with empty spaces. I am java 8 version, let me know how can i retain dot(.) and "\n"

A: You have a loop that repeatedly calls matcher.find() to find the next match in the string; then it calls appendReplacement().  The javadoc for appendReplacement says it does this:

*

*It reads characters from the input sequence, starting at the append position, and appends them to the given string buffer. It stops after reading the last character preceding the previous match, that is, the character at index start() - 1.

*It appends the given replacement string to the string buffer.

*It sets the append position of this matcher to the index of the last character matched, plus one, that is, to end().
So for each match, it appends the characters up to the match, then it appends the replacement string (instead of the string that got matched).  So far, so good.
But what happens when there's no more matches?  There are still characters left in the input, to the right of the last match, that didn't get appended to the output.
Fortunately, there's a method that takes care of exactly that for you: appendTail.

A: You'd have to use appendReplacement and appendTail explicitly. Unfortunately you have to use StringBuffer to do this. Here's a snippet:
    String content="aaaaaaaaaa";
Pattern pattern = Pattern.compile("a");
Matcher m = pattern.matcher(content);

StringBuffer sb = new StringBuffer();
final int N = 3;
for (int i = 0; i < N; i++) {
  if (m.find()) {
     m.appendReplacement(sb, "b");
  } else {
     break;
  }
}
m.appendTail(sb);
System.out.println(sb); // bbbaaaaaaa

according to matcher-replace-method


text:
Q: C : send different structures for one function argument I have a function that draws a circle using OpenGL, I would like to pass it a structure containing the x and y coordinates and the radius. The problem is this same function has to be used with 3 different structures all containing the coordinates, radius and some other things that the draw function doesn't use.
Is there some way to only have one argument for 3 different structures (only one is sent at a time).
I hope I've been enough precise.
PS : the functions have to be "abstract".

A: Yes you can use a prototype like this:
void foo(char type, void *data);

Use the type to tell the function which struct to use the data as, and you're good.
struct c *prepareStructC(void);
//...
struct c *toto = prepareStructC();
foo('c', toto);
//...
void foo(char type, void *data)
{
  int x, y;
  switch (type)
  {
    case 'c':
      x = ((struct c*)data)->x;
      y = ((struct c*)data)->y;
      break;
    //...
  }
  //...
}

Second option, if you want to avoid a switch/case, and be able to add more struct types afterwards, without evolving foo, you can make sure all your structs begin with the necessary data, always in the same order, with the same type. This way you can make something like an "interface" from C++, and use abstract versions of the type:
struct abstract
{
  int x;
  int y;
  int radius;
}

struct a
{
  struct abstract abs;
  //... other data ...
}
struct b
{
  struct abstract abs;
  //... other data ...
}
struct c
{
  struct abstract abs;
  //... other data ...
}

//Two choices : either you have:
void foo(void *data)
{
  int x,y,r;
  x = ((struct abstract*)data)->x;
  y = ((struct abstract*)data)->y;
  r = ((struct abstract*)data)->radius;
  //...
}

//OR Smarter way:
void foo2(struct abstract *data)
{
  int x,y,r;
  x = data->x;
  y = data->y;
  r = data->radius;
}
//Calling foo2 with:
struct a *sa = prepareStructA();
struct b *sb = prepareStructB();
struct c *sc = prepareStructC();
foo2(sa->abs);
foo2(sb->abs);
foo2(sc->abs);

The second part of the second method allows you more flexibility, breaking down specific information in a subtype, enables you to put the abs part anywhere inside the struct a/b/c, and is better in the principle of a single purpose for a struct (Having coordinates and radius and other things inside a struct is not always the best.)

A: Only if the function accepts a void* as the argument, and then you cast the void* to the correct pointer type in the function before dereferencing it to access the data within.
typedef enum
{
    type1, type2, type3
} datatype;

void foo(void* data, datatype type)
{
    switch(type)
    {
        case type1:
        // do something with data by casting it to the proper type
        break;

        // ... other cases here
    }
}

However, by doing so you will a) need to pass another argument that indicates the original type being casted to void* before being passed, and b) you are abandoning the type system which is hardly ever a good idea and should always be avoided.
If you take this approach, highly recommend creating three "wrapper" functions that take the correct types before calling the function (that takes the void*) internally. Make it a strict convention to never call the void* function directly; only call the wrapper. In this fashion, you still have the type system to help out with compilation errors.
void bar1(someStruct* data)
{
    foo((void*) data, type1);
}
void bar2(someOtherStruct* data)
{
    foo((void*) data, type2);
}
void bar3(yetAnotherStruct* data)
{
    foo((void*) data, type3);
}


text:
Q: linkedin-j authorization failed i work with the linkedin-j lib and try to authorize, but there always an exception is thrown:
I try to authorize first. But if i fetch the
request

and the
authURL

an exception is thrown(see below).
This is my code:
private static String consumerKeyValue="[mykey]";
private static String consumerSecretValue="[mySecret]";
private static String accessTokenValue="[myTokenValue]";
private static String tokenSecretValue="[mytokenSecretValue]";

static LinkedInApiClientFactory factory;
static LinkedInApiClient client;

static LinkedInOAuthService oAuthService;
static LinkedInRequestToken request;
static String authURL;

private static LinkedInAccessToken accessToken;

public static void main(String[]args) throws IOException{

    authorize(consumerKeyValue, tokenSecretValue);
    createClient(consumerKeyValue, consumerSecretValue, accessTokenValue, tokenSecretValue);

}

public static void createClient(String key, String secret, String token, String secretToken){
factory=LinkedInApiClientFactory.newInstance(key,secret);
client=factory.createLinkedInApiClient(accessToken);
}

public static void authorize(String key, String secret) throws IOException{
    oAuthService=LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(key, secret);
    request=oAuthService.getOAuthRequestToken();
    authURL=request.getAuthorizationUrl();
    System.out.println("Paste this URL to your browser:");
    System.out.println(authURL);
    System.out.println("and now paste the given PIN here and press enter");
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String input=br.readLine();
    accessToken =oAuthService.getOAuthAccessToken(request, input);
}

}

and now following exception is thrown:
Exception in thread "main" com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceImpl.getOAuthRequestToken(LinkedInOAuthServiceImpl.java:159)
at Connection.authorize(Connection.java:46)
at Connection.main(Connection.java:32)
Caused by: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
at com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceImpl.getOAuthRequestToken(LinkedInOAuthServiceImpl.java:148)
... 2 more
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getContent(HttpURLConnectionResponseAdapter.java:18)
at oauth.signpost.AbstractOAuthProvider.handleUnexpectedResponse(AbstractOAuthProvider.java:228)
at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:189)
... 4 more
Caused by: java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/requestToken
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at oauth.signpost.basic.HttpURLConnectionResponseAdapter.getStatusCode(HttpURLConnectionResponseAdapter.java:22)
at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:178)
... 4 more


text:
Q: Eclipse m2eclipse not picking up "provided" transitive dependencies Trying to get Roboguice working in Eclipse which contains 2 Maven projects, Astroboy and Roboguice (let's call them A and B where A depends on B). My problem is that unit tests in A which work fine in Maven give compile errors in Eclipse because it can't find Junit. Junit is declared in A's pom as a provided dependency, as below. I did tell Eclipse that project A depends on B by adding B to A's build path/projects.
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>provided</scope>
    </dependency>

I got it to work temporarily by changing the scope to test (then doing a mvn install and maven/update project on A), but what must I do to have it find Junit by itself?


text:
Q: Chrome Device mode- cannot see the Viewport controls Running Chrome 66.0.3359.170 (Official Build) (64-bit) on Windows 8.1
I can see the Device Mode toggle button in the dev tools window and can toggle it on and off but I cannot see the Viewport controls or anything resembling a Device mode menu bar.
Can someone tell me where it should be so I can first verify whether it is missing or I am just a little slow. Or whether I have to enable a particular menu bar or something.
Referring to the menu shown in the first image on this page-
Test Responsive and Device-specific Viewports

A: Face the same issue following steps help me

*

*Inspect the window / open DevTools

*Select 'Customize & control DevTools' option from the right top (indicated by 3 vertical dots).

*select 'setting'

*click on 'Restore Default and reload'