text:
Q: Is it possible to export a VirtualBox drive to a "real" hard drive? I have a Windows 7 VM on my Mac OS X VirtualBox Host. The virtual drive is a dynamically-expanding with a limit of 20GB.
Is it possible to export the .vdi virtual hard drive to a real, physical hard drive, to put into a real, physical computer?
I have an external case to mount an IDE drive to USB, and can pass that through to VB, but just copying all the files on the virtual drive won't copy things like boot sectors.
Also, if I can do this, would I have to re-activate Windows, or do anything special?

A: There's a risk Windows won't survive the hardware change.
Still if you connect your physical disk to the vm and boot from the ISO image of a ghosting utility you may be able to do this.

A: Yes it is possible all you need is Acronis true image home 2013 and sysprerp
Create your virtual machine with either windows 7 or vista (xp slighlty difrent)
update with all windows updates and programs.
go to c:\windows\system32\sysrep\sysprerp.exe double click it once you are happy with your setup the computer will strip out the hardware default but keep windows and all updates and programs.
Make sure the "GENERALIZE" is ticked and "SHUT DOWN" is selected
then install Acronis true image home on the host computer
go to tools and create an Rescue Acronis boot iso save this on desktop or somewhere handy.
Open up virtual box and right click your virtual machine and go to settings and then storage and click the cd icon and then folder "Choose Virtual folder" then select your Acronis ISO. Click ok at bottom
Power on your virtual machine and be ready on your keyboard  use your arrow keys to go up to  Acronis true image home from the menu!! (don't let windows boot or you start over)
Once on the backup and restore screen , Click the Devices on the top left of your screen and  then usb and look for  your external drive click it and Acronis will suddenly see a new partion to scan. then go back to devices and click usb mouse. so you can you your mouse in Acronis.
Click backup disk drives it asks what you want to backup make sure both The system and windows partitions are ticked. You should have something like DISK 2, SYSTEM RESERVED, UNNAMED.
Then choose browse for location then find a drive to dump your image onto external hard drive works well.
name your image file something useful like Windows7homepreium32BIT then click ok and proceed. Tick the box in Acronis for shutdown. Go have a cuppa this can take 10 mins depending on machine Spec.
Your virtual box will be powered down with virtual box you host machine will take control of your external hard  drive and you can see your image.
Restore image
This will give you a Backup you can use on any drive and any computer.
pop back to Acronis on your host desktop and burn a bootable rescue media but this time to cd. put the disk in any computer along with your external hard drive. And  repeat steps about except this time from Acronis  menu choose restore and select your image from hard drive and choose your destination hard drive and click proceed a prefect copy of windows every time
8 mins to restore it from scratch Bonus! Windows loaded in under 15 min including service packs and programs.
This a rough guide hope it helps

A: More than likely anyway that you export a virtual machine to a physical machine, you're going to end having to reactivate it. One, the system will notice that the hardware is different (motherboard, harddrive, RAM, processor, videocard). Two, you going to find that Windows will need to find drivers for any specific hardware that is installed on the machine (video, NIC, sound, etc).  Last, if you reactivate windows on the new hardware, your licenese for the OS will not allow you to keep the virtual up and running also. It's a grey area, but typicaly you can only have one instance of the OS running at a time (though I doubt that the EULA police will raid your home for this). Just remember that.
Good luck on your project and hope this helps some.

A: You might be able to do this with an imaging program such as Norton Ghost or Acronis True Image. And possibly using the dd command in OS-X. Microsoft also has a tool available for deploying Windows 7 images. See this for more info.


text:
Q: How do I call a JS callbacks from C++ with node-addon-api? I need a way to invoke JS callbacks from a C library that uses contexts.
Here's an example:
const ctx1 = mylib_init();
mylib_set_event_callback(ctx1, () => {
  console.log("EVENT");
});

Napi::FunctionReference cb;
bool done = false; // Used to prevent crash on multithreading.
// TSFN would obviously be used; this is just to shorten it.

extern "C" void onEvent(mylib_t* handle, void* userdata) {
  if (cb != nullptr && !done) {
    done = true;
    cb.Call({});
  }
}

Napi::Value MyWrapper::SetEventCallback(const Napi::CallbackInfo &info) {
  Napi::Env env = info.Env();
  Napi::Object global = env.Global();

  // info[0] = mylib_t* previously converted to a BigInt.
  // info[1] = JS callback
  mylib_t* handle = convertJSBigIntToHandle(info[0]);

  r_cb = Napi::Persistent(info[1].As<Napi::Function>());
  const auto ret = mylib_set_callback(handle, onEvent, nullptr);
  return env.Null();
}

This works (the JS callback is run), but the problem is that the callback is global.
If I have ctx2 and call mylib_set_event_callback again, it will overwrite the callback from ctx1.
How can I convert this so that callbacks for ctx1 and ctx2 will both be called?

A: Your callback is global because it is in a global variable.
You should place the Napi::FunctionReference in the mylib_t structure.
If you cannot modify that structure, I see that you can pass a a context pointer in userdata - you are passing nullptr. Create dynamically a Napi::FunctionReference with new and pass this pointer so that you can have it in onEvent.
You should also properly the reference when the structure is destroyed or the function is replaced.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get UWP Store associations using PowerShell or MSBuild I'm using AppVeyor CI to build my UWP app and want to create an APPX package during every build. However my .gitignore is ignoring the Package.StoreAssociation.xml and MyAppName_StoreKey.pfx which I want to include in the APPX package as they are identifying my app in Windows Store.
Is there any way to get these files using PowerShell or MSBuild or something like that? In other words, is there any command line equivalent to the Project > Store > Associate App with the Store... wizard?
I know I can upload these files to the repo as Secure files but I'd prefer getting the latest files from the Dev Center with every build.

A: I would say probably not, as the Associate App with the Store Wizard, is an authenticated Wizard which requires a users Microsoft Account to be registered with Visual Studio, Load Credentials from storage or asking for OAuth, and then Visual Studio goes to Microsoft's server to Sign the Certificate and Sign the app with it.
AppVeyor documentation says the currently UWP is not officially supported for UWP, as a Microsoft License is required.
Edit: Does this help?

A:
Is there any way to get these files using PowerShell or MSBuild or something like that? In other words, is there any command line equivalent to the Project > Store > Associate App with the Store... wizard?

No, as @William's explanation. The associating operation needs user's interaction in Visual Studio, this doesn't depend on a public command/API.
In my experience, we need to store(maintain) the latest store association information in somewhere, overwrite the related files and replace the reserved keywords in the app's manifest template file before packaging.


text:
Q: Proof that ideal inclusion as sets is preserved under localisation of a commutative ring I apologise if this seems too trivial which is why I am a bit suspicious.
I essentially need to prove that given ideals $I, J$ in a commutative ring $A$, $I \subset J$ iff $I_m \subset J_m$ in $A_m$, for all maximal ideals $m$ in $A$.
I proceeded as thus : Supposing $I \subset J $, take $\frac{x}{s} \in I_m$, where $x \in I$, $\implies x \in J$, $\implies \frac{x}{s} \in J_m$.
Conversely if $I_m \subset J_m$ in $A_m$, then take $x \in I$, $\implies \frac{x}{s} \in I_m, \implies \frac{x}{s} \in J_m$ and consequently $x \in J$.
Is this all there is to it??Or are there any loopholes that I havent been able to perceive??

A: The mistake in the OP's argument was discussed in the comments.
Let give a proof (which differs from the one proposed in the comments which I think needs some finiteness-assumptions on the ideals; I was assuming $A$ is noetherian, I guess).
Given ideals $I,J\subset A$ such that $I_m \subset J_m\subset A_m$ for each maximal ideal $m\subset A$ we claim that $I\subset J$.
Let $f\in A$ be an arbitrary element and consider the ideal $(J:f) = \{a\in A\mid af\in J\}$.
If $S\subset A$ is a multiplicative subset, then $f\in S^{-1}J$ holds if and only if $S\cap(J:f)\neq\emptyset$.
In particular, if $m\subset A$ is a maximal ideal, then $f\in J_m$ if and only if $(J:f)$ is not(!) contained in $m$.
Consequently, if $f\in J_m$ for each maximal ideal, then $(J:f)$ is not contained in any maximal ideal which is possible only if $(J:f) = A$; equivalently, if $f\in J$. Applied to each element of $I$ separately this implies that if $I_m\subset J_m$ for each maximal ideal $m\subset A$, then $I\subset J$.


text:
Q: Concurrent table creation Have a situation when table can be created from different places.
So, I have ~10 working applications, that can simultaneously try to create a same table.
Question. How can I synchronize them ? So I don't have any exceptions or errors ?
All instances of the application are trying to create a new table when the day ends, so when there is something like 00:00:00 they all will try to create it.
Sorry, for possible 'stupid question', have been googling for a while, no results.
Thank you.

A: You can use sp_getapplock to take arbitrary locks. You could make your app take such a lock before creating the table. Like that:
exec sp_getapplock
if tabledoesnotexist
 create table ...

A: As alluded to in the comments, your first step is to perform an existence check. Then, on the off chance that there are two simultaneous creations you can use TRY...CATCH.
IF Object_ID('test', 'U') IS NULL
  BEGIN
    BEGIN TRY
      CREATE TABLE test ( a int )
    END TRY
      BEGIN CATCH
        SELECT Error_Message()
      END CATCH
  END

UPDATE
You do not want to create a table every day. Seriously. This is very poor database design.
Instead you want to add a datetime column to your table that indicates when each record was created.

A: Can you please go through the following code ... Concurrent execution is handled using ISOLATION LEVEL SERIALIZABLE.
     CREATE PROCEDURE [dbo].[GetNextID](
            @IDName nvarchar(255)
        )
        AS
        BEGIN
            /*
                Description:    Increments and returns the LastID value from tblIDs
                for a given IDName
                Author:         Max Vernon
                Date:           2012-07-19
            */

            DECLARE @Retry int;
            DECLARE @EN int, @ES int, @ET int;
            SET @Retry = 5;
            DECLARE @NewID int;
            SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
            SET NOCOUNT ON;
            WHILE @Retry > 0
            BEGIN
                BEGIN TRY
                    BEGIN TRANSACTION;
                    SET @NewID = COALESCE((SELECT LastID FROM tblIDs WHERE IDName = @IDName),0)+1;
                    IF (SELECT COUNT(IDName) FROM tblIDs WHERE IDName = @IDName) = 0
                        INSERT INTO tblIDs (IDName, LastID) VALUES (@IDName, @NewID)
                    ELSE
                        UPDATE tblIDs SET LastID = @NewID WHERE IDName = @IDName;
                    COMMIT TRANSACTION;
                    SET @Retry = -2; /* no need to retry since the operation completed */
                END TRY
                BEGIN CATCH
                    IF (ERROR_NUMBER() = 1205) /* DEADLOCK */
                        SET @Retry = @Retry - 1;
                    ELSE
                        BEGIN
                        SET @Retry = -1;
                        SET @EN = ERROR_NUMBER();
                        SET @ES = ERROR_SEVERITY();
                        SET @ET = ERROR_STATE()
                        RAISERROR (@EN,@ES,@ET);
                        END
                    ROLLBACK TRANSACTION;
                END CATCH
            END
            IF @Retry = 0 /* must have deadlock'd 5 times. */
            BEGIN
                SET @EN = 1205;
                SET @ES = 13;
                SET @ET = 1
                RAISERROR (@EN,@ES,@ET);
            END
            ELSE
                SELECT @NewID AS NewID;
        END
        GO


text:
Q: MySQL select inner join and union I have this two tables. I have current player id_player, I want to select all games from this player (id_player) and his opponents info. Current player and opponent player are connected with same id_game.  or

table game:`id_game` (...)
table game_player:`id_game_player, id_player, id_game`(...)

"give me all separate game info from current player and his opponent
  and join info for their game (grouped by game)"

result as:
      +---player game info
game1 |
      +---opponent game info

      +---player game info
game2 |
      +---opponent1 game info

      +---player game info
game2 |
      +---opponent2 game info

Can anyone provide me MySQL solution?
Thanks

EDIT:
I try with this code but I'm not sure this is fastest way (WHERE IN) and is there any way to group results like above?
SELECT * FROM game_player
    JOIN `game` ON game.id_game = game_player.id_game
    WHERE game_player.id_game
    IN (
    SELECT game_player.id_game
    FROM `game_player`
    WHERE game_player.id_player =2)

A: give this a try
SET @player_ID = 0;                  -- <<== the playerID
SELECT  a.*, b.*, 'player' Status         -- this is the first part of the union
FROM    game a                            -- which gets all the game of
        INNER JOIN game_player b          -- the selected player and its info
            ON a.id_game = b.id_game
WHERE   id_player = @player_ID
UNION ALL
SELECT  d.*, c.*, 'opponent' status
FROM    game_player c
        INNER JOIN
        (
            SELECT  a.*
            FROM    game aa
                    INNER JOIN game_player bb
                        ON aa.id_game = bb.id_game
            WHERE   bb.id_player = @player_ID
        ) d ON c.id_game = d.id_game AND c.id_player <> @player_ID
ORDER   BY id_game, status


text:
Q: Find the force of attraction exerted by a homogenous cone of altitude h and vertex angle $\alpha$ on a point located at vertex. Find the force of attraction exerted by a homogenous cone of altitude h and vertex angle $\alpha$ (in axial cross section) on a material point containing unit mass and located at its vertex.
I am picturing a cone with the base on the $z=0$ plane and the point of attraction on the top of the cone. The law of gravitation states
$$F = -\frac{Gm_1 m_2}{r^2}$$
In this case, the $m_1 = 1$ (some unit mass), and $m_2 = dm$ of some mass inside the cone. So the problem can be shown as (in cylindrical coordinates) :
$$\int\int\int_V-\frac{G}{L^2} \ r \ dz \ d\theta \ dr$$
Where $L$ is the length from the $dm$ mass to the vertex point of the cone. Now, for $L$ in terms of $r, \theta, z$ .  A generic point written in cylindrical coordinates $(x,y,z) = (r\cos(\theta), r\sin(\theta), z)$. The distance between this point and $(0,0,h)$ ie: the vertex is:
$$L = |(0,0,h) - (r\cos(\theta), r\sin(\theta), z)| = |(-r\cos(\theta), -r\sin(\theta), h-z)| = \sqrt{r^2 + (h-z)^2}$$
Now, for the bounds (a is the radius of the base):
$$\int_{0}^{a(1-\frac{z}{h})}\int_{0}^{2\pi}\int_{0}^{h} -\frac{G}{L^2} \ r \ dz \ d\theta \ dr$$
Since $z = (h - \frac{h}{a}r)$ rearranging gets $r = a(1-\frac{z}{h})$ becoming the bound for $r$.
Problem here is that I am suppose to get a vector quantity at the end (something along $-2\pi G(1-\cos(\alpha))z \cdot \vec{u_z}$ ...) How can I setup this problem properly?

A: You need to only consider force in z-direction and
$dF_z = dF \ cos \phi = dF \cdot \cfrac{h-z}{L}$ where $\phi$ is angle between z-axis and segment between vertex and the point in the cone. So your integral should have $(h-z) r $ in the numerator and $L^3$ in the denominator.
Alternatively, for ease of working, I will suggest to use spherical coordinates which is easier here and also place the point unit mass at the origin with the axis of symmetry being z-axis.
The force of attraction between the point mass at $(0, 0, 0)$ and a small mass element $dm$ in the cone will have two components - one along z-axis and one perpendicular to it (along the cross section of the cone). As z-axis is the axis of symmetry and the point mass is on z-axis, the force perpendicular to z-axis will cancel each other out when we consider the whole cross section of the cone.
Using spherical coordinates,
$x = \rho \cos\theta \sin\phi, y = \rho \sin\theta \sin\phi, z = \rho \cos\phi$
$\sqrt{x^2+y^2+z^2} = \rho$
Now at $z = h$, $z = \rho \cos\phi = h \implies \rho = h \sec\phi$
Also, $dF_z = dF \cos\phi = \cfrac{G \ dM \cos\phi}{\rho^2} $
$dM = \sigma \ dV = \sigma \ \rho^2 \sin\phi \ d\rho \  d\phi \ d\theta$
Where $\sigma$ is the mass density of the cone and if $M$ is the mass of the cone,
$\sigma = \cfrac{3 M}{\pi h^3 \tan^2\alpha}$
The integral is,
$\displaystyle |F| = G \cdot \sigma \int_0^{2\pi} \int_0^{\alpha} \int_0^{h \sec\phi} \sin \phi \cos \phi \ d\rho \ d\phi \ d\theta$
$ \displaystyle = 2 G \ \sigma \ \pi \ h (1 - \cos\alpha)$
And note that $\vec F = |F| \ \hat z$


text:
Q: In Bokeh, how can I display different information for points and patches? I want to display different information for different layers (points and patches) using bokeh.
I downloaded the shapefile and the population information of Haitian cities respectively from here and from here and I merged them.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd

import osmnx as ox

from bokeh.layouts import row, column
from bokeh.models import Select
from bokeh.palettes import Spectral5
from bokeh.plotting import curdoc, figure, save
from bokeh.sampledata.autompg import autompg_clean as df

from bokeh.io import show
from bokeh.models import LogColorMapper
from bokeh.palettes import Viridis6 as palette
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource

from bokeh.sampledata.us_counties import data as counties
from bokeh.sampledata.unemployment import data as unemployment

import pandas as pd
import geopandas as gpd
import shapely

color_mapper = LogColorMapper(palette=palette)

Some functions
 def getPolyCoords(row, geom, coord_type):
        """Returns the coordinates ('x' or 'y') of edges of a Polygon exterior"""

        # Parse the exterior of the coordinate
        exterior = row[geom].exterior

        if coord_type == 'x':
            # Get the x coordinates of the exterior
            return list( exterior.coords.xy[0] )
        elif coord_type == 'y':
            # Get the y coordinates of the exterior
            return list( exterior.coords.xy[1] )
def getPointCoords(row, geom, coord_type):
    """Calculates coordinates ('x' or 'y') of a Point geometry"""
    if coord_type == 'x':
        return row[geom].x
    elif coord_type == 'y':
        return row[geom].y

Cities data
haiti = gpd.read_file(hti_admbnda_adm2_cnigs_20181129.shp')
haiti = haiti.to_crs({'init': 'epsg:32618'})
haiti = haiti[haiti.index != 98].reset_index(drop=True) ## i=98 is corrupted

pop = pd.read_csv('hti_admnbnda_adm2_cnigs2013c.csv')
level = 2
left = 'adm%dcode'%level
right = 'ADM%d_PCODE'%level
h_geom = pd.merge(pop, haiti, left_on=left, right_on=right)

Then I created a data for bokeh
grid = pd.DataFrame()
grid['x'] = h_geom.apply(getPolyCoords, geom='geometry', coord_type='x', axis=1)
grid['y'] = h_geom.apply(getPolyCoords, geom='geometry', coord_type='y', axis=1)
grid['Name'] = h_geom['adm2_en']
grid['Population'] = h_geom['TOTAL']
data=dict(
    x=list(grid['x'].values),
    y=list(grid['y'].values),
    name=list(grid['Name'].values),
    rate=list(grid['Population'].values),
)

From osmnx I get points of schools
selected_amenities = ['school']
place = 'Haiti'
schoolOSM = ox.pois_from_place(place=place, amenities=selected_amenities)
schools = gpd.GeoDataFrame(schoolOSM)
idxok = []
for i in schools.index:
    if type(schools['geometry'][i]) == shapely.geometry.point.Point:
        idxok.append(i)
schools = schools[schools.index.isin(idxok)]
schools['x'] = schools.apply(getPointCoords, geom='geometry', coord_type='x', axis=1)
schools['y'] = schools.apply(getPointCoords, geom='geometry', coord_type='y', axis=1)

data1=dict(
    x=list(schools['x'].values),
    y=list(schools['y'].values),
)

Then I want to show the information: I would like to show Name, Population and coordinates for cities while only coordinates for schools.
TOOLS = "pan,wheel_zoom,reset,hover,save"

p = figure(title="Schools Point in Haiti", tools=TOOLS,
    x_axis_location=None, y_axis_location=None,
    tooltips=[("Name", "@name"), ("Population", "@rate"), ("(Long, Lat)", "($x, $y)")])

p.hover.point_policy = "follow_mouse"
p.patches('x', 'y', source=data,
         fill_color={'field': 'rate', 'transform': color_mapper},
         fill_alpha=1.0, line_color="black", line_width=1)
# Add points on top (as black points)
p.circle('x', 'y', size=3, source=data1, color="black")

show(p)

In doing so I get the information of Name, Population, Long, Lat for both Schools and Cities. But Schools do not have the info Name and Population, so I get something like

A: You need to create two separate data sources and two separate HoverTools.
from bokeh.models import HoverTool

data_cities = dict(x = list(cities['x'].values),  y = list(cities['y'].values))
data_schools = dict(x = list(schools['x'].values),  y = list(schools['y'].values))

cities = p.circle('x', 'y', size = 3, source = data_cities, color = "green")
schools = p.circle('x', 'y', size = 3, source = data_schools, color = "blue")

hover_cities = HoverTool(renderers = [cities], tooltips = [("Name", "@name"), ("Population", "@rate"), ("(Long, Lat)", "($x, $y)")]))
hover_schools = HoverTool(renderers = [schools], tooltips = [("(Long, Lat)", "($x, $y)")]))

p.add_tools(hover_cities)
p.add_tools(hover_schools)


text:
Q: Count the rows of a table where the value is obtained from another table and display in a loop I want to take the post_id from table 'posts' and use this value to count the rows in table 'comment_post' where the same column post_id is equal to the value from the table posts
These are my 2 tables:
posts
 id | post_id | title
----+---------+-------
 1  | 1       | title1
 2  | 2       | title2
 3  | 3       | title3

comment_post
 id | post_id | comment_id
---+----------+-----------
 1 | 1        | 26
 2 | 1        | 27
 3 | 2        | 28
 4 | 1        | 29
 5 | 3        | 30

User comments are stored in a separate table 'comments' and posts are published in the table posts.
I made a relationship between the two tables and called the table 'comment_post'.
I have a loop set up to return the posts in the browser

            <?php
            $i = 0;
            foreach ($posts as $post):{
            if(++$i > 11) break;
            }
            ?>

<a href="single_post.php?post-slug=<?php echo $post['slug']; ?>"><img loading="lazy" src="<?php echo BASE_URL . '/static/images/' . $post['image']; ?>" alt="pcr test" class="img-fluid">

<?php echo date("F j, Y ", strtotime($post["created_at"])); ?>

                        <?php if (isset($post['topic']['name'])): ?>

                        <a href="<?php echo BASE_URL . 'filtered_posts.php?topic=' . $post['topic']['id'] ?>"><?php echo $post['topic']['name'] ?>

                        <?php endif ?>

                    <a href="single_post.php?post-slug=<?php echo $post['slug']; ?>">

<?php echo $post['title'] ?>

<?php echo $post['lead'] ?>

Jamie Aldus

<?php echo date("j-m-y ", strtotime($post["created_at"])); ?>

                  <?php endforeach ?>

and in the line

I want to display the number of comments for each post.
I have tried all sorts of SELECT and COUNT(*) queries, but none seem to work.
A little help would be nice, thank you.
Code for $posts
function getPublishedPosts() {
    // use global $conn object in function
    global $conn;
    $sql = "SELECT * FROM posts WHERE published=true ORDER BY created_at DESC";
    $result = mysqli_query($conn, $sql);

    // fetch all posts as an associative array called $posts
    $posts = mysqli_fetch_all($result, MYSQLI_ASSOC);
    $final_posts = array();
    foreach ($posts as $post) {
        $post['topic'] = getPostTopic($post['id']);
        array_push($final_posts, $post);
    }
    return $final_posts;
}

A: You can get the comment post counts inside of your function by updating your SQL query with a left join and some grouping:
function getPublishedPosts($mysqli, $limit = 10) {
    $sql = "
        SELECT
            posts.*, COUNT(1) as commentCount
        FROM
            posts
        LEFT JOIN
            comment_posts ON posts.id = comment_posts.post_id
        WHERE
            posts.published = true
        GROUP BY
            comment_posts.post_id, posts.id
        ORDER BY
            posts.created_at DESC
        LIMIT ?
    ";
    $query = $mysqli->prepare($sql);
    $query->bind_param('i', $limit);
    $query->execute();
    $posts = $query->get_result();

    $final_posts = array();

    while($post = $posts->fetch_assoc()) {
        $post['topic']            = getPostTopic($post['id']);
        $final_posts[$post['id']] = $post;
    }

    return $final_posts;
}

Notes

*

*It's best practice to not use global $conn; pass the $conn in when you invoke the function instead (much like passing the DB link to mysqli_*). You now use the function like:
$posts = getPublishedPosts($conn);

*I've changed the procedural style function calls to object style instead. Maybe it isn't your preference but it's easier to read and follow so I suggest learning it (others would suggest ditching mysqli it altogether and using PDO instead)

*You can now access the number of comments per post at the field commentCount.

*I've put a $limit parameter in the function call (with a default of 10); because you have a limit in your for each loop (which you can now remove)
$posts = getPublishedPosts($conn, 20); // Adding the second parameter changes the number of results returned, in this case 20 will be returned

*I've changed your $final_posts to be indexed on the post_id. Maybe it isn't strictly necessary in this case but can make things easier down the road

*I've changed the for loop in the function to a while: it basically does the same thing

*As mentioned in the comments, I fully expect you can update the SQL Query to accommodate the getPostTopic as well (another JOIN most likely)


text:
Q: matplotlib update installation im new to the python world , i been trying to plot using matplotlib . I get it to work but it still gives me errors about updating it , how can i update it? here's the code :
import cv2
import numpy as np
import matplotlib.pyplot as plt
#                      0
img = cv2.imread('bryan.jpg' ,cv2.IMREAD_GRAYSCALE)
#IMREAD_COLOR = 1
#IMREAD_UNCHANGED = -1
cv2.imshow('image' , img)
cv2.waitKey(0)
cv2.destroyAllWindows()
plt.imshow(img, cmap='gray', interpolation= 'bicubic' )
plt.plot([50,100],[80,10], 'c' ,linewidth=5)

plt.show()

plus the error:You probably need to get an updated matplotlibrc file from
http://matplotlib.sf.net/_static/matplotlibrc or from the matplotlib source
distribution


text:
Q: Updating existing metadata of my S3 object I am trying to update the existing metadata of my S3 object but in spite of updating it is creating the new one. As per the documentation, it is showing the same way but don't know why it is not able to update it.
 k = s3.head_object(Bucket='test-bucket', Key='test.json')
            s3.copy_object(Bucket='test-bucket', Key='test.json', CopySource='test-bucket' + '/' + 'test.json', Metadata={'Content-Type': 'text/plain'}, MetadataDirective='REPLACE')

A: I was able to update using the copy_from method
s3 = boto3.resource('s3')
object = s3.Object(bucketName, uploadedKey)
object.copy_from(
    CopySource={'Bucket': bucketName,'Key': uploadedKey},
    MetadataDirective="REPLACE",
    ContentType=value
)

A: S3 metadata is read-only, so updating only metadata of an S3 object is not possible. The only way to update the metadata is to recreate/copy the object. Check the 1st paragraph of the official docs

You can set object metadata at the time you upload it. After you upload the object, you cannot modify object metadata. The only way to modify object metadata is to make a copy of the object and set the metadata.


text:
Q: writing string text pyramid pattern in java I am new to android and trying to write this pyramid in java but it is not printing exactly.
i want to print like this

my code to write this is
  String searchQuery = "rooms in mumbai";

    int n = searchQuery.length();

    for (int i = 0; i<=n; i++)
    {
        for (int j = 0; j<=i-1; j++)
        {
            System.out.print(searchQuery.charAt(j));
        }
        System.out.println();
    }

but this printing this
r
ro
roo
room
rooms
rooms
rooms i
rooms in
rooms in
rooms in m
rooms in mu
rooms in mum
rooms in mumb
rooms in mumba
rooms in mumbai

As we can see it is priting some lines two times and I want the print to start from "roo" but it is printing from "r". Guide me how can i do that

A: BE SIMPLE!!!
String str = "rooms in mumbai";

for (int i = 3; i <= str.length(); i++)
    if (str.charAt(i) != ' ')
        System.out.println(str.substring(0, i));

Output:
roo
room
rooms
rooms i
rooms in
rooms in m
rooms in mu
rooms in mum
rooms in mumb
rooms in mumba
rooms in mumbai

A: To start printing from roo instead of r, change the outer loop
for (int i = 0; i<=n; i++)

into
for (int i = 3; i<=n; i++)

If you want to avoid/skip  , just add this line after System.out.println()
if (j + 1 < n && searchQuery.charAt(j+1).equals(" ")){
    i++;
}

This will effectively skip printing new lines that simply have an extra space compared to the previous line

A: To make it start from roo just simply make int i = 3


text:
Q: Tomcat maxThreads & acceptCount tuning for Fail-Fast I would like to tune Tomcat to fail-fast in case of any issues when all threads are occupied ( for example, waiting for a database connection if suddenly database starts to perform badly ).
I checked few articles, specifically:
https://netflixtechblog.com/tuning-tomcat-for-a-high-throughput-fail-fast-system-e4d7b2fc163f
https://tomcat.apache.org/tomcat-8.5-doc/config/http.html
I have few questions and would be grateful if you help me:

*

*Why Netflix maintains the concurrent requests in memory and then in-their-own-code reply 503 if it reaches the threshold? What is the rationale behind it doing themselves?
As far as I understand from tomcat documentation ( see link above ), if maxThreads and acceptCount is reached, tomcat will reply with Connection Refused by himself. So specifying correctly small acceptCount should the trick.

From Tomcat docs:

Each incoming request requires a thread for the duration of that request. If more simultaneous requests are received than can be handled by the currently available request processing threads, additional threads will be created up to the configured maximum (the value of the maxThreads attribute). If still more simultaneous requests are received, they are stacked up inside the server socket created by the Connector, up to the configured maximum (the value of the acceptCount attribute). Any further simultaneous requests will receive "connection refused" errors, until resources are available to process them.

From article:

Track the number of active concurrent requests in memory and use it for fast failing. If the number of concurrent requests is near the estimated active threads (8 in our example) then return an http status code of 503. This will prevent too many worker threads becoming busy because once the peak throughput is hit, any extra threads which become active will be doing a very light weight job of returning 503 and then be available for further processing.

*I assume that even in Tomcat NIO the worker threads are not re-used "simultaneously" like it can be in NodeJS, for example.
For one http request there is an allocated 1 worker thread which won't handle any other http requests unless finishes with this one. Even if this http request is waiting for a blocking i/o like database read.

*Given all things mentioned above, I believe that this could be the proper configuration:
# not using the executor, but a 'default' internal thread pool of the connector

maxConnections = -1 # For NIO/NIO2 only, setting the value to -1, will disable the maxConnections feature and connections will not be counted.
# or we can leave default, i.e. 10k. The thing is that only 1 thread ( hence little resources used ) will keep these connections alive, so we can use keepAlive
# and avoid establishing connections again and again which can be costly and resource consuming.

server.tomcat.max-threads = 96 # we assume that 8 cores can handle up to this amount of threads, given that each thread spends significant time in database and/or other network calls
# in the article above it was stated that they increased maxThreads 3 times than the amount of cores

server.tomcat.accept-count = ?? # from one point of view, it can be something really-really small like 16 or 32
# from another point of view, maybe something like 512
# imagine that due to a temporary network glitch an upstream service won't be reachable and we need few seconds to reach the timeouts and open circuit breaker. would be nice to queue other requests and successfully ( the ones what are independent ) process them seconds after rather than reject them right away

P.S I am using Tomcat 8.5 and NIO connector.
Any help / advice would be highly appreciated.


text:
Q: Getting Parent name from same table I have a table Which is as below:
quotes_glass_types
 id | name                    | parent_id
 1  | Annealed glass           |  Null
 2  |  Clear Float Glasss     |   1
 3  |  Tinted glass           |   1
 4  |  Toughened glass        |   Null
 5  |  Clear toughened Glass  |   4

Here, name having Null parent_id are the parent.
How do i display glass name  along with their parent in laravel? for example;
{
  id:2,
  name:Clear Float glass,
  category:Annealed glass
 }

what do i do after this?:
$glass=\DB::table('quotes_glass_types')->select('id','name','parent_id as category')->get();

A: If you want to get Name with Parent Name than you can use below query :
SELECT qgt.name,pqgt.name FROM quotes_glass_types as qgt LEFT JOIN quotes_glass_types as pqgt ON qgt.id = pqgt.parent_id

You have to use LEFT JOIN on the same table. I don't know how to write this query in Laravel but this query works in phpmyadmin.
Please check it.

A: You can do like this-
DB::table('quotes_glass_types')

->select('quotes_glass_types.*', 'qgt.name as parent_name')

->leftjoin('quotes_glass_types as qgt', 'qgt.id', '=', 'quotes_glass_types.parent_id')

->get();


text:
Q: Jquery tabs not working on different domain I have created a site for a client with jquery tabs, on my hosting they work fine
http://auto.nathanrobjohn.com
but on his hosting it just doesn't seem to want to work
http://www.modernandclassicautos.co.uk.php53-7.dfw1-1.websitetestlink.com/
I haven't changed anything at all.
Any help would be really appreciated.

A: Run the console on Chrome, saw the next errors on the new hosting while on your hosting not:

Uncaught SyntaxError: Unexpected token < jquery.min.js:1 Uncaught
SyntaxError: Unexpected token < jquery-ui.min.js:1 Uncaught
SyntaxError: Unexpected token < conditionizr.min.js:1 Uncaught
SyntaxError: Unexpected token < modernizr.min.js:1 Uncaught
ReferenceError: conditionizr is not defined
  www.modernandclassicautos.co.uk.php53-7.dfw1-1.websitetestlink.com/:43
Uncaught ReferenceError: Modernizr is not defined
  scripts.js?ver=1.0.0:6

When I clicked on the link to the jquery's file - I think I've found the problem.
The difference between the two versions is the URL of the scripts.
On the one that works:
http://ajax.googleapi...

While on the other one:
//ajax.googleapi...

UPDATE:
Consider following the next 2 suggestions:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js?ver=1.9.1"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

(1)Add http: before the //ajax in the `src.
(2) Why are you loading this file twice? remove the second line.
UPDATE 2
I've noticed you also have the following code:
And the first js file does not exist on your server , therefore you see HTML - the HTML of the 404 page.
<script type='text/javascript' src='/ajax/libs/jquery/1.10.1/jquery.min.js?ver=1.9.1'>
</script>
<script type='text/javascript' src='/ajax/libs/conditionizr.js/2.2.0/conditionizr.min.js?ver=2.2.0'></script>
<script type='text/javascript' src='/ajax/libs/modernizr/2.6.2/modernizr.min.js?ver=2.6.2'></script>

Remove the first line. You're calling the same jquery script 3 times - not a good idea at all.
Hope it helped , update me if not.

A: Check the contents of your jquery.min.js and jquery-ui.min.js files. They appear to contain HMTL pages.


text:
Q: Is it allowed to start multiple transactions in the same Sqlite database connection? I have a multi-threaded C++ application which uses Sqlite3 for the database. I am storing the SQLite database connection and threads which need access to the database, use the same connection creating the transactions of their own.
I use the below command to get the database connection.
const int errorCode =  sqlite3_open_v2(fileNameUtf8.c_str(), &Handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, Vfs->GetName().c_str());

But as multiple threads are accessing the database, I am facing the issue of starting multiple transactions in the same connection. When the second thread tries to begin transaction error message "cannot start a transaction within a transaction" is returned.
I thought SQLITE_OPEN_FULLMUTEX flag allows the case of multiple threads using the same connection. I assumed it might even allow multiple transactions in the same connection.
Is there any option in Sqlite3 to begin multiple transactions corresponding to different threads using the same SQLite database connection ?
Thanks in advance.

A: In SQLite, one connection corresponds to one transaction.
To get separate transactions, you need separate connections.
Accessing one connection from multiple threads makes sense only if the threads ensure that their transactions and SQL statements do not interfere with each other.
Also read the FAQ.

A: Multiple independant transation in same single connexion simply does not make sense: since you use the same connection, every other transaction is seen by the database as nested in the already existing one, so the error.
But if you need concurrency, you should wonder whether SQLite is the right tool. From the FAQ Appropriate Uses For SQLite :

SQLite does not compete with client/server databases. SQLite competes with fopen().

and later

Many concurrent writers? → choose client/server


text:
Q: Getting ORA-00001 and ORA-01438 errors when inserting data into a table I have a problem trying to run this script where I got the error:

ORA-00001: unique constraint (constraint_name) violated

So, the thing is can't insert date into the table, and other error is:

ORA-01438: value larger than specified precision allowed for this column

CREATE TABLE TEST
(    TEST_ID        INT NOT NULL,
    COMPONENTS     VARCHAR2(30) NOT NULL,
    MATTER        VARCHAR2(2) NOT NULL,
    LIC            NUMBER(9, 2),
    MIC            NUMBER(9, 2),
    UIP            NUMBER(9, 2),
    CONSTRAINT TEST_pk PRIMARY KEY (TEST_ID));

--SEQUENCE TEST_ID

CREATE SEQUENCE SEQ_TEST_ID
 START WITH     1
 INCREMENT BY   1
 MINVALUE 1
 MAXVALUE 9999;

 --INSERTING VALUE TO TABLE

INSERT ALL

INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Food waste','OG','50.50','39.00','13.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Paper'     ,'OG','05.50','19.00','32.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Cardboard' ,'OG','00.00','00.00','10.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Plastic'       ,'OG','03.00','04.00','00.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Textiles'      ,'OG','03.00','06.00','04.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Ruber'     ,'OG','03.00','00.00','01.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Leather'       ,'OG','03.00','02.50','01.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Yard waste' ,'OG','00.00','00.00','15.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Wood'           ,'OG','03.00','05.50','02.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Misc. Organic','OG','03.00','04.00','00.00')

INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Glass'      ,'IG','05.50','05.50','08.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Tin Cans'       ,'IG','00.50','00.50','05.00')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Aluminum'       ,'IG','03.00','03.00','00.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Other metals'   ,'IG','00.00','00.00','02.50')
INTO TEST (TEST_ID,COMPONENTS, MATTER, LIC, MIC, UIP) VALUES (SEQ_TEST_ID.NEXTVAL,'Drit,ash,etc'   ,'IG','20.50','15.50','05.00')
SELECT * FROM DUAL;

A: you can increaseur sequence cache size to 200,the default is 20.
alter sequence SEQ_TEST_ID cache 200;

try agian.

A: If you are creating table in oracle, then AUTO_INCREMENT is not supported.
Create the table using MSW_ID as number and create a sequence to use its value in your table as.
CREATE TABLE MSW

( MSW_ID number,
 COMPONENTS VARCHAR2(15) NOT NULL,
 MATTER VARCHAR2(2) NOT NULL,
 LIC NUMBER(4, 2),
 MIC NUMBER(4, 2),
 UIP NUMBER(4, 2),
 CONSTRAINT NSW_pk PRIMARY KEY (MSW_ID));

You can learn more on sequences here;
CREATE SEQUENCE SEQ_MSW_ID
 START WITH     1
 INCREMENT BY   1
 MINVALUE 1
 MAXVALUE 99999999999;

and then you insert query becomes
INSERT  INTO MSW ( MSW_ID, COMPONENTS, MATTER, LIC, MIC, UIP) VALUES
                (SEQ_MSW_ID.NEXTVAL, 'Food waste'   ,'OG','50.50','39.00','13.00'); --> semicolon
INSERT  INTO MSW ( MSW_ID, COMPONENTS, MATTER, LIC, MIC, UIP) VALUES
                 (SEQ_MSW_ID.NEXTVAL, 'Paper'        ,'OG','05.50','19.00','32.50');  --> semicolon
.
.
.
INSERT  INTO MSW ( MSW_ID, COMPONENTS, MATTER, LIC, MIC, UIP) VALUES
                 (SEQ_MSW_ID.NEXTVAL, 'Drit,ash,etc' ,'IG','20.50','15.50','05.00');  --> semicolon

Or use insert all as a single statement as
INSERT ALL
     INTO MSW ( MSW_ID, COMPONENTS, MATTER, LIC, MIC, UIP) VALUES
                (SEQ_MSW_ID.NEXTVAL, 'Food waste'   ,'OG','50.50','39.00','13.00')
     INTO MSW ( MSW_ID, COMPONENTS, MATTER, LIC, MIC, UIP) VALUES
                (SEQ_MSW_ID.NEXTVAL, 'Paper'        ,'OG','05.50','19.00','32.50')
     .
     .
     .
     INTO MSW ( MSW_ID, COMPONENTS, MATTER, LIC, MIC, UIP) VALUES
                (SEQ_MSW_ID.NEXTVAL, 'Drit,ash,etc' ,'IG','20.50','15.50','05.00')
SELECT * FROM DUAL;  --> semicolon

A: The error message is because of extra parentheses in int().
SQL> create table foo(f int());
create table foo(f int())
                      *
ERROR at line 1:
ORA-00907: missing right parenthesis

SQL> create table foo(f int);

Table created.

SQL>

Btw. the question has nothing to do with PL/SQL, it is a plain Oracle SQL issue.


text:
Q: How to bold first line of paragraph till comma in word using VBA if i have a paragraph for example
The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
What in need to do is to bold first line of paragraph till comma
The quick brown fox jumps over the lazy dog, The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
for all paragraphs in Word using VBA.

A: Sub Test()
Dim p As Paragraph
Dim idx As Integer
Dim i As Integer
For Each p In ActiveDocument.Paragraphs

With p.Range
    idx = InStr(1, .Text, ",", vbTextCompare)
    If idx > 0 Then
        For i = 1 To idx
            .Characters(i).Bold = True
        Next i
    End If
End With

Next p
End Sub

Loops over each paragraph, finds the first Comma, bolds all characters including the first comma.
Input:
Sample paragraph, some text.
Output:
Sample paragraph, some text.
It isn't the most optimal code, since it loops over the characters, but it's tested and works and should give the idea for what you're after. Skips paragraphs without comma's.


text:
Q: jQuery plugin placeholder without using placeholder attribute I'm looking for a jQuery plugin placeholder that doesn't use placeholder attribute.

A: Should be fairly simple to build yourself — here's a quick example:
$.fn.placeholder = function(){
    return $(this).each(function(){
        $(this)
            .data('original-value', $(this).val())
            .focus(function(){
                var $input = $(this);
                if ($input.val() == $input.data('original-value'))
                    $input.val("");
            })
            .blur(function(){
                var $input = $(this);
                if ($.trim($input.val()) == "")
                    $input.val($input.data('original-value'));
            });
    });
};

$('input').placeholder();

http://jsfiddle.net/BrHjH/1


text:
Q: KStream-KStream inner join throws java.lang.ClassCastException In the process method of @StreamListener, I am mapping school KStream to person KStream and via .through() method to populate a topic "person" from which I generate a KStream inside another process1 method of
@StreamListener.
MianApplication.java
@SpringBootApplication
public class KafkaStreamsTableJoin {

    public static void main(String[] args) {
        SpringApplication.run(KafkaStreamsTableJoin.class, args);
    }

    @EnableBinding(KStreamProcessorX.class)
    public static class KStreamToTableJoinApplication {

        @StreamListener
        public void process(@Input("school") KStream<SchoolKey, School> schools) {

            schools.map((schoolKey, school) -> {
                return KeyValue.pair(new PersonKey("Adam", "Smith", schoolKey.getId()), new Person(12));
            })
            .through("person", Produced.with(new PersonKeySerde(), new PersonSerde()));
        }

        @StreamListener
        public void process1(@Input("school_1") KStream<SchoolKey, School> schools, @Input("person") KStream<PersonKey, Person> persons) {

            schools.selectKey((schoolKey, school) -> schoolKey.getId())
                    .join(persons.selectKey((personKey, person) -> personKey.getId()),
                            (school, person) -> {
                                System.out.println("school_app2= " + school + ", person_app2= " + person);
                                return null;
                            },
                            JoinWindows.of(Duration.ofSeconds(1)),
                            Joined.with(Serdes.Integer(), new SchoolSerde(), new PersonSerde())
                    );
        }
    }

    interface KStreamProcessorX {

        @Input("person")
        KStream<?, ?> inputPersonKStream();

        @Input("school")
        KStream<?, ?> inputSchoolKStream();

        @Input("school_1")
        KStream<?, ?> inputSchool1KStream();

    }
}

Inside the method process1, this KStream need to join with another KStream but I am getting the following exception:
Exception in thread "stream-join-sample_2-654e8060-5b29-4694-9188-032a9779529c-StreamThread-1" java.lang.ClassCastException: class kafka.streams.join.School cannot be cast to class kafka.streams.join.Person (kafka.streams.join.School and kafka.streams.join.Person are in unnamed module of loader 'app')
    at org.apache.kafka.streams.kstream.internals.AbstractStream.lambda$reverseJoiner$0(AbstractStream.java:98)
    at org.apache.kafka.streams.kstream.internals.KStreamKStreamJoin$KStreamKStreamJoinProcessor.process(KStreamKStreamJoin.java:94)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:117)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:183)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:162)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:122)
    at org.apache.kafka.streams.kstream.internals.KStreamJoinWindow$KStreamJoinWindowProcessor.process(KStreamJoinWindow.java:55)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:117)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:183)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:162)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:122)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:366)
    at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:199)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:420)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:889)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:804)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:773)

I think this exception is related to incorrect serde's but I can't figure out which serde's are creating the problem and how to fix it. Or is it that during mapping in method process,
re-partitioning is triggered and this has something to do with incorrect serde's?
POJO's and Serde's:
Person.java
public class Person {

    private double age;

    public Person() {
    }

    public Person(double age) {
        this.age = age;
    }

    @JsonGetter("age")
    public double getAge() {
        return age;
    }

    @JsonSetter("age")
    public void setAge(double age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }
}

PersonSerde.java
public class PersonSerde extends Serdes.WrapperSerde<Person> {
    public PersonSerde () {
        super(new JsonSerializer<>(), new JsonDeserializer<>(Person.class));
    }
}

PersonKey.java
public class PersonKey {

    private String firstName;
    private String lastName;
    private int id;

    public PersonKey() {
    }

    public PersonKey(String firstName, String lastName, int id) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.id = id;
    }

    @JsonGetter("firstName")
    public String getFirstName() {
        return firstName;
    }

    @JsonSetter("firstName")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @JsonGetter("lastName")
    public String getLastName() {
        return lastName;
    }

    @JsonSetter("lastName")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @JsonGetter("id")
    public int getId() {
        return id;
    }

    @JsonSetter("id")
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "PersonKey{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", id=" + id +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PersonKey personKey = (PersonKey) o;
        return id == personKey.id &&
                Objects.equals(firstName, personKey.firstName) &&
                Objects.equals(lastName, personKey.lastName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(firstName, lastName, id);
    }
}

PersonKeySerde.java
public class PersonKeySerde extends Serdes.WrapperSerde<PersonKey> {
    public PersonKeySerde () {
        super(new JsonSerializer<>(), new JsonDeserializer<>(PersonKey.class));
    }
}

serde's and pojo's for School class is similar to Person class.
application.yml
spring.application.name: stream-join-sample

spring.cloud.stream.bindings.school:
  destination: school
  contentType: application/json
  consumer:
    useNativeDecoding: false
spring.cloud.stream.kafka.streams.bindings.school:
  consumer:
    keySerde: kafka.streams.serde.SchoolKeySerde
    valueSerde: kafka.streams.serde.SchoolSerde
    application-id: stream-join-sample_1

spring.cloud.stream.bindings.person:
  destination: person
  contentType: application/json
  consumer:
    useNativeDecoding: false
spring.cloud.stream.kafka.streams.bindings.person:
  consumer:
    keySerde: kafka.streams.serde.PersonKeySerde
    valueSerde: kafka.streams.serde.PersonSerde
    application-id: stream-join-sample_2

spring.cloud.stream.bindings.school_1:
  destination: school
  contentType: application/json
  consumer:
    useNativeDecoding: false
spring.cloud.stream.kafka.streams.bindings.school_1:
  consumer:
    keySerde: kafka.streams.serde.SchoolKeySerde
    valueSerde: kafka.streams.serde.SchoolSerde
    application-id: stream-join-sample_2

spring.cloud.stream.kafka.streams.binder:
  brokers: localhost
  configuration:
    default.key.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
    default.value.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
    commit.interval.ms: 100

Sample Application with reproducible steps:

A: I downloaded your code from GitHub to dig into this, and turns out it's actually a bug in the used JsonSerializer/JsonDeserializer. The type (School, Person, PersonKey, SchoolKey) is encoded in the record headers, but the headers are never cleaned up. Each time the type changes, just a new header is appended (header keys are not unique, and duplicates are allowed).
For some record, the same type is just encoded multiple times, and thus, this part of the code works. However, for some cases, different types are encoded and one type (the first header found) is picked "randomly" when reading data from a topic. The happens before the join, but when receiving data from a repartition topic. If the wrong type is picked, the code crashed with a ClassCastException later.
New Answer:
Following the discussion on this ticket, https://github.com/spring-cloud/spring-cloud-stream-binder-kafka/issues/685, you should disable that type information is written into the record headers via:
props.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);

Note, that all Serdes that are created manually, ie, via calling new must be configured manually:
Map<String, Object> config = new HashMap<>();
config.put(JsonSerializer.ADD_TYPE_INFO_HEADERS, false);

PersonKeySerde personKeySerde = new PersonKeySerde();
personKeySerde.configure(config, true);

PersonSerde personSerde = new PersonSerde();
personSerde.configure(config, false);

// ...
.through("person", Produced.with(personKeySerde, personSerde));

Original Answer:
As a workaround, you can replace map and selectKey() with a transform() and clear the headers within transform(). It's a hack though. You should file a ticket agains SpringBoot project so they can fix JsonSerializer/JsonDeserializer.
The following code removes the headers and ensure that the correct types are used, avoiding the ClassCastException:
@SpringBootApplication
public class KafkaStreamJoinApplication {

    public static void main(String[] args) {
        SpringApplication.run(KafkaStreamJoinApplication.class, args);
    }

    @EnableBinding(KStreamProcessorX.class)
    public static class KafkaKStreamJoinApplication {

        @StreamListener
        public void process(@Input("school") KStream<SchoolKey, School> schools) {
            // replace map() with transform()
            schools.transform(new TransformerSupplier<SchoolKey, School, KeyValue<PersonKey, Person>>() {
                @Override
                public Transformer<SchoolKey, School, KeyValue<PersonKey, Person>> get() {
                    return new Transformer<SchoolKey, School, KeyValue<PersonKey, Person>>() {
                        ProcessorContext context;

                        @Override
                        public void init(final ProcessorContext context) {
                            this.context = context;
                        }

                        @Override
                        public KeyValue<PersonKey, Person> transform(final SchoolKey key, final School value) {
                            // clear all headers; would be sufficient to only remove type header
                            for (Header h : context.headers().toArray()) {
                                context.headers().remove(h.key());
                            }
                            // same a "old" map code:
                            return KeyValue.pair(new PersonKey("Adam", "Smith", key.getId()), new Person(12));
                        }

                        @Override
                        public void close() {}
                    };
                }})
                .through("person", Produced.with(new PersonKeySerde(), new PersonSerde()));
        }

        @StreamListener
        public void process1(@Input("school_1") KStream<SchoolKey, School> schools, @Input("person") KStream<PersonKey, Person> persons) {

            // replace selectKey() with transform()
            schools.transform(new TransformerSupplier<SchoolKey, School, KeyValue<Integer, School>>() {
                @Override
                public Transformer<SchoolKey, School, KeyValue<Integer, School>> get() {
                    return new Transformer<SchoolKey, School, KeyValue<Integer, School>>() {
                        ProcessorContext context;

                        @Override
                        public void init(final ProcessorContext context) {
                            this.context = context;
                        }

                        @Override
                        public KeyValue<Integer, School> transform(final SchoolKey key, final School value) {
                            // clear all headers; would be sufficient to only remove type header
                            for (Header h : context.headers().toArray()) {
                                context.headers().remove(h.key());
                            }
                            // effectively the same as "old" selectKey code:
                            return KeyValue.pair(key.getId(), value);
                        }

                        @Override
                        public void close() {}
                    };
                }})
                // replace selectKey() with transform()
                .join(persons.transform(new TransformerSupplier<PersonKey, Person, KeyValue<Integer, Person>>() {
                    @Override
                    public Transformer<PersonKey, Person, KeyValue<Integer, Person>> get() {
                        return new Transformer<PersonKey, Person, KeyValue<Integer, Person>>() {
                            ProcessorContext context;

                            @Override
                            public void init(final ProcessorContext context) {
                                this.context = context;
                            }

                            @Override
                            public KeyValue<Integer, Person> transform(final PersonKey key, final Person value) {
                                // clear all headers; would be sufficient to only remove type header
                                for (Header h : context.headers().toArray()) {
                                    context.headers().remove(h.key());
                                }
                                // effectively same as "old" selectKey code:
                                return KeyValue.pair(key.getId(), value);
                            }

                            @Override
                            public void close() {}
                        };
                    }}),
                    (school, person) -> {
                        System.out.println("school_app2= " + school + ", person_app2= " + person);
                        return null;
                    },
                    JoinWindows.of(Duration.ofSeconds(1)),
                    Joined.with(Serdes.Integer(), new SchoolSerde(), new PersonSerde())
                );
        }
    }

    interface KStreamProcessorX {
        @Input("person")
        KStream<?, ?> inputPersonKStream();

        @Input("school")
        KStream<?, ?> inputSchoolKStream();

        @Input("school_1")
        KStream<?, ?> inputSchool1KStream();
    }
}

A: Could it be that there are some stale data somewhere in the topics or in the underlying changelog topics? Can you try to use new topics and different application-id's to see if it fixes your issues?
Here is a sample configuration to use:
spring.cloud.stream.bindings.school:
  destination: school-abc
spring.cloud.stream.kafka.streams.bindings.school:
  consumer:
    keySerde: kafka.streams.serde.SchoolKeySerde
    valueSerde: kafka.streams.serde.SchoolSerde
    application-id: stream-join-sample_diff_id_1

spring.cloud.stream.bindings.person:
  destination: person-abc
spring.cloud.stream.kafka.streams.bindings.person:
  consumer:
    keySerde: kafka.streams.serde.PersonKeySerde
    valueSerde: kafka.streams.serde.PersonSerde
    application-id: stream-join-sample_diff_id_2

spring.cloud.stream.bindings.school_1:
  destination: school-abc
spring.cloud.stream.kafka.streams.bindings.school_1:
  consumer:
    keySerde: kafka.streams.serde.SchoolKeySerde
    valueSerde: kafka.streams.serde.SchoolSerde
    application-id: stream-join-sample_diff_id_2

spring.cloud.stream.kafka.streams.binder:
  brokers: localhost
  configuration:
    default.key.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
    default.value.serde: org.apache.kafka.common.serialization.Serdes$StringSerde
    commit.interval.ms: 100

Note that I changed the topic names, application id etc. You might want to update any producers that populate the topics.
Also, notice that you don't need to specify the content type, setting useNativeDecoding to false etc. since those are the defaults in the current version of the kafka streams binder.


text:
Q: Show last post from multiple categories using wp_list_categories I have the following code that lists out the children categories on a separate page when you click on its parent category. The  code renders a list like so:
Home › Archive for IQ Issue 7

*

*Journal

*news

*world view
However I would like to retrieve the latest post from each of these categories and print underneath the category name. How could I achieve this within the loop below? I have tried several foreach loops but none seem to print the correct info. Thanks in advance.
category.php
<?php $this_category = get_queried_object();

// if parent is 0, category is top level
if( 0 == $this_category->parent ) :

    // top level category,
    // show child categories of this issue
    $args = array(
        'child_of' => $this_category->term_id,
        'title_li' => '',
        'hide_empty' => 0
    ); ?>

    <?php wp_list_categories($args); ?>

<?php else :

    // child category,
    // show articles in this subcategory, etc.
    echo 'child category';

endif; ?>

A: Get all children categories using get_terms(). Loop through each term and run a new query using tax_query.
Example:
<?php if ( get_queried_object()->parent == 0 ) :  // parent cat ?>

Showing all children

    <?php
        $args = array(
            'hide_empty' => false,
            'parent' => get_queried_object()->term_id
        );
        $terms = get_terms( 'category', $args );

        if ( $terms ) echo '
';
        foreach( $terms as $term ) {
            $the_post = new WP_Query(array(
                'posts_per_page' => 1,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'category',
                        'field' => 'id',
                        'terms' => $term->term_id
                    )
                )
            ));
        ?>
            <?php while ( $the_post->have_posts() ) : $the_post->the_post(); ?>

<a href="<?php echo get_term_link( $term, 'category'); ?>"><?php echo $term->name; ?> (Last article: <a href="<?php the_permalink(); ?>"><?php the_title(); ?>)

            <?php endwhile; wp_reset_query(); ?>
        <?php
        } //endforeach
        if ( $terms ) echo '
';
    ?>

<?php else: // child ?>
    <?php
    while ( have_posts() ) : the_post();
        get_template_part( 'content', get_post_format() );
    endwhile;
    ?>
<?php endif; ?>


text:
Q: UIManager Won't Set Button Background All, I am using java swing's UIManager to set this theme
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

This theme is terrible at differentiating disabled/enabled backgrounds for buttons, so I've been battling trying to get this to change the disabled background. Nothing is working for me. I don't understand what I'm doing wrong, below are all my approaches so far
//My color constant
Color disabledButton = new Color(255,124,124);

//Maybe its these?
UIManager.put("Button.background", disabledButton);
UIManager.put("Button.foreground", disabledButton);

//No maybe this...
UIManager.put("Button.disabled", disabledButton);

//Okay how about this
UIManager.put("Button.disabled", "DerivedColor(color=255,124,124 parent=control offsets=0.0,0.0,0.0,0 pColor=255,124,124");

//NO!!?!?! WELL FINE ILL SET THE BACKGROUND MYSELF
myButton.setBackground(disabledButton);

None of these work... where am I making an error?


text:
Q: jquery list hovering changing side img I need to have a list of icons who are changing the image and title in the siding div whenever an
element is being hovered, there is a default image when nothing is being hovered ("i.png") which comes back whenever the user cursor leave the
, here is the html:

$("#brain").hover(function() {
        $("#brain img").css("opacity", "1");
        $("#exp-img").attr("src", "a.png");
        $("#icon-image-header").text("lorem");
      });
      $("#brain").mouseleave(function() {
        $("#brain img").css("opacity", "0.5");
      });
      $("#body").hover(function() {
        $("#body img").css("opacity", "1");
        $("#exp-img").attr("src", "b.png");
        $("#icon-image-header").text("ipsum");
      });
      $("#body").mouseleave(function() {
        $("#body img").css("opacity", "0.5");
      });
      $("#planning").hover(function() {
        $("#planning img").css("opacity", "1");
        $("#exp-img").attr("src", "c.png");
        $("#icon-image-header").text("dolor");
      });
      $("#planning").mouseleave(function() {
        $("#planning img").css("opacity", "0.5");
      });
      $("#pen").hover(function() {
        $("#pen img").css("opacity", "1");
        $("#exp-img").attr("src", "d.png");
        $("#icon-image-header").text("sit");
      });
      $("#pen").mouseleave(function() {
        $("#pen img").css("opacity", "0.5");
      });
      $("#front").hover(function() {
        $("#front img").css("opacity", "1");
        $("#exp-img").attr("src", "e.png");
        $("#icon-image-header").text("amet");
      });
      $("#front").mouseleave(function() {
        $("#front img").css("opacity", "0.5");
      });
      $("#pie").hover(function() {
        $("#pie img").css("opacity", "1");
        $("#exp-img").attr("src", "f.png");
        $("#icon-image-header").text("lorem");
      });
      $("#pie").mouseleave(function() {
        $("#pie img").css("opacity", "0.5");
      });
      $("#bulb").hover(function() {
        $("#bulb img").css("opacity", "1");
        $("#exp-img").attr("src", "g.png");
        $("#icon-image-header").text("ipsum");
      });
      $("#bulb").mouseleave(function() {
        $("#bulb img").css("opacity", "0.5");
      });
      $("#db").hover(function() {
        $("#db img").css("opacity", "1");
        $("#exp-img").attr("src", "h.png");
        $("#icon-image-header").text("dolor");
      });
      $("#db").mouseleave(function() {
        $("#db img").css("opacity", "0.5");
      });
      $("#skills-icons").mouseleave(function() {
        $("#icon-image-header").text("Lorem");
        $("#exp-img").attr("src", "i.png");
      });

        Lorem

+Lorem

Lorem Ipsum Dolor

Now this is actually working fine but I was wondering if there was any cleaner way of doing this. I'm a beginner in jquery but it seems really long.

A: Here you go with a solution https://jsfiddle.net/9fczjsgu/

var dic = {
  "brain" : {
    img: "a.png",
    text: "lorem"
  },
  "body" : {
   img: "b.png",
    text: "ipsum"
  },
  "planning" : {
    img: "c.png",
    text: "dolor"
  },
  "pen" : {
    img: "d.png",
    text: "sit"
  },
  "front" : {
    img: "e.png",
    text: "amet"
  },
  "pie" : {
    img: "f.png",
    text: "lorem"
  },
  "bulb" : {
    img: "g.png",
    text: "ipsum"
  },
  "db" : {
    img: "h.png",
    text: "dolor"
  }
};

$("li").hover(function() {
  $(this).find("img").css("opacity", "1");
  $("#exp-img").attr("src", dic[$(this).attr('id').img]);
  $("#icon-image-header").text(dic[$(this).attr('id').img]);
}).mouseleave(function() {
  $(this).find("img").css("opacity", "0.5");
});

        Lorem

+Lorem

Lorem Ipsum Dolor

Create a dictionary (JSON), with ids as key & it will contain value again in a form of JSON with image & text.
Hope this will help you.


text:
Q: Possibility of passing MyObject to bean routing using Apache camel? I am consuming messages from Apache kafka using apache camel JAVA DSLs.
I am writing an object by converting it to byte[] on kafka. when I consume it I receive a message back with byte[]. I deserialize it and get an object.
I checks it if it is an object of MyObject then need to pass it to bean using java DSL .to(). My code is as below:
public class KafkaRouter extends RouteBuilder {

    private MessageBean msgBean;

    @Override
    public void configure() throws Exception {

        from("{{kafka.cons.uri}}").process(new Processor() {

            @Override
            public void process(Exchange exchange) throws Exception {
                Object obj = SerializationUtils.deserialize(exchange.getIn().getBody(byte[].class));                //TODO cast to specific class as returned after deserialization.

                if(obj !=null && obj instanceof MessageBean){

                    msgBean = (MessageBean)obj;

                }
                else {

                    throw new PTFException("Invalid Message read in Kafka Consumer");
                }

            }

        }).bean(PTFTransformerService.class,"callTransformerService(msgBean)"); ;
    }

Now issue is I just want MyObject in corresponding called method and I do not want to use TypeConvertors. I do not want to get Exchange/body in method I will process my stream in process and throw exception if read invalid messages and do not forward it to the bean.
My method on the other end will be:
private void callTransformerService(MessageBean msgObj){
    // Got my object here ;-)

    }

A: Add @Body before function argument MessageBean msgObj:
import org.apache.camel.Body;

private void callTransformerService(@Body MessageBean msgObj){

}

A: You may need to write a custom fallback type converter that can convert from kafka byte[] to your POJOs

*

*http://camel.apache.org/type-converter.html
Then you can just define the pojo type in the bean and Camel will use the fallback type converter to try to convert to the pojo type.

A: You can set the Exchange Body in the Processor as follows below:
msgBean = (MessageBean)obj;
exchange.getIn().setBody(msgBean, MessageBean.class);
void callTransformerService(@Body MessageBean msgObj) {}


text:
Q: Bash script to get nested http response from URL I have a scenario where I am deploying applications to a Tomcat instance using a bash script and need to test if the endpoint (a login screen in this case) is truly available by testing it before I declare the deployment activity as being successful.
There is a wrinkle in the situation, as it were. Tomcat is hiding behind a reverse proxy, so when I test the endpoint it needs to go through the Apache Webserver on HTTPS, get rerouted and then return the response from the actual endpoint desired.
I am currently trying the following:
response=$(curl --write-out %{http_code} --silent --output /dev/null https://url.to.test)

However this obviously does not follow the potential 301 presented by the reverse proxy, and simply hands the 301 back as the answer.
My Google-fu must be weak these days because I can't find anyone else who has suffered through the same or a similar enough issue.
Any thoughts?

A: If you want curl to follow 30x redirects, use -L aka --location.


text:
Q: How to use hard disk with raspberry pi? I have a raspberry pi Zero and I wnat to use a 128GB ssd hard disk with it. How can I connect it to my raspberry pi.

A: Use a USB HDD enclosure.
Google

A: Also be aware about this kickstarter project: https://www.kickstarter.com/projects/2073955313/pidrive-low-power-msata-ssd-for-the-raspberry-pi


text:
Q: Add Dynamic button in android I have a Linear Layout
and I want to add to this Linear Layout a button (from 3 Buttons) Dynamic in Run Time Depending on an integer value that returns from a function
I know how to add a view to a Layout using AddView , and how to remove views form layout using removeView  ...
but my question is how to check if the view Exists in the layout before call the method reomveView

A: I suggest you create your buttons beforehand and just set the visibility to View.GONE
when you trigger some event you can set other buttons visibility to true while the others are false..
this will work with no problems and you dont have to add them dynamically.. it will just "seem" dynamic :)
You can do that with this code:
button1.setVisibility(View.GONE);
button2.setVisibility(View.VISIBLE);

Given the buttons are "button1" and "button2"
View.GONE will "remove" the view from the screen, however it is still "there" it just doesn't appear for the user, and it doesn't take up any space
View.INVISIBLE will "remove" the view from the screen, how ever the space it took up is still used by it.
View.VISIBLE will show the view as it would usually.


text:
Q: Instagram navigation after Python Requests not working I have started building a web scraper for Instagram and am trying to NOT use Selenium (have build prior ones with Selenium, need something faster). I know the Instagram API won't be around for much longer so didn't want to deal with it.
The issue I am encountering is the 'following' website is not being recognized as signed in.  I can successfully sign into the login page and navigate to the user's profile page, but once I attempt a 'GET' request on the following page it signals that I need to login.  Here is the code in python using the requests library:
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'

def login():
    """Logs in to instagram."""
    session.headers.update(
        {'Referer': BASE_URL, 'user-agent': STORIES_UA})
    req = session.get(BASE_URL)

    session.headers.update({'X-CSRFToken': req.cookies['csrftoken']})

    login_data = {'username': USERNAME, 'password': PASSWORD}
    login = session.post(LOGIN_URL, data=login_data, allow_redirects=True)
    session.headers.update({'X-CSRFToken': login.cookies['csrftoken']})
    loginVerification = login.json()

    """
    Check that the user is actually authenticated in the JSON
    """
    if loginVerification['authenticated'] == True and login.status_code == 200:
        print("Successful login")
    else:
        print("Invalid login")
        if login.status_code != 200:
            print("Client error")

    print(login.url)

    """Get to user home page"""
    user_page = session.get(YOURPAGE_URL)
    if user_page.status_code == 200:
        print("Successful navigation to user page")
        print(user_page.url)
    else:
        print("Couldn't get to user page")

    """Next we need to get the user's followers"""
    session.headers.update({'Referer': FOLLOWERS_URL})
    follower_page = session.get(FOLLOWERS_URL)
    if follower_page.status_code == 200:
        print("Successful navigation to followers page")
        print(follower_page.url)
    else:
        print("Couldn't get to followers page")

When i print out the URL's of the different pages after making GET requests, they are correct for the user profile page but not once I try and reach the following page.
I should be directed to this: https://www.instagram.com/USERNAME/following/
But am sent to this instead: https://www.instagram.com/accounts/login/?next=/USERNAME/following/
Any help is appreciated!


text:
Q: Creating a sequence in spring boot I am using spring boot specifically spring data jpa for working with the database and the database manager is postgres. I need to create a sequence that will be used in the conformation of an attribute.
Specifically my attribute is called classifier (this attribute is not the primary key) and it is formed with a given string and a consecutive number (which would be the value given by the sequence) example FMFC-COMP-1234
currently I create the sequence with postgres using
CREATE SEQUENCE seq_name START WITH 1;

but I wish I could create it from spring boot. Any help will be welcome. Thanks in advance


text:
Q: How to do GROUP BY [empty] Is there a way for explicitly specifying an empty aggregation, such as the following:
SELECT NULL AS Product, SUM(Revenue) FROM Sales GROUP BY ()

Rather than the implicit version which doesn't have a GROUP BY clause:
SELECT NULL AS Product, SUM(Revenue) FROM Sales

Sample input/output:
WITH Sales (Product, Revenue) AS (VALUES ('a',10),('b',20))
select NULL Product, SUM(Revenue) from Sales;
┌─────────┬──────────────┐
│ product ┆ sum(revenue) │
╞═════════╪══════════════╡
│         ┆           30 │
└─────────┴──────────────┘

The query is correct as-is, I'm just wondering if there is a way to make the GROUP BY explicit. This is for a very basic downstream parser that checks if it is an aggregation query based on if the words GROUP BY are in the normalized query.

A: You can use expressions to group by. so grouping by an expression that is constant is equivalent removing it from the group by statement
i.e. the following are equivalent:
WITH Sales (Product, Revenue) AS (VALUES ('a',10),('b',20))
select NULL Product, SUM(Revenue) from Sales;

and
WITH Sales (Product, Revenue) AS (VALUES ('a',10),('b',20))
select NULL Product, SUM(Revenue) from Sales group by 1=1;


text:
Q: Overflow inside overflow hidden & position relative grandparent I have this dropdown menu that gets cut off due to #parent-wrapper's overflow hidden and position relative (required due to this jQuery carousel). Is there a way to make the dropdown's overflowing part display outside #parent-wrapper while keeping #parent-wrapper's overflow hidden and position relative?
Simple example:
http://jsfiddle.net/gNUJV/
Full example:
http://jsfiddle.net/nrQSG/

        Lorem

Ipsum

Dolor

and
a {
  color: white;
}
#parent-wrapper {
  width: 500px;
  overflow: hidden;
  position: relative;
}
#parent {
  height: 100px;
  overflow: hidden;
  background: blue;
}
.dropdown ul {
  width: 100px;
  display: none;
  padding: 50px;
  background: black;
  z-index: 2000;
  position: absolute;
}

and
$(".dropdown").hoverIntent({
  over: function() {
    $("ul", this).show();
  },
  out: function() {
    $("ul", this).hide();
  },
  timeout: 500
});

Requires: http://cherne.net/brian/resources/jquery.hoverIntent.minified.js

A: Add a height to the #parent-wrapper on hover and it will expand.
$(".dropdown").hoverIntent({
 over: function() {
   $("ul", this).show().closest('#parent-wrapper').css('height','100px');
}.......

A: #parent-wrapper {
  width: 500px;
  /*change this: overflow:hidden; for: */
  overflow: visible;
  position: relative;
}

A: Position: Relative is the problem child here.  If you can rework the code to use Position: Absolute I think it might work.  See the following for more details...
CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

A: I think you can achieve this without using jquery by giving the dropdown a position of fixed instead of absolute.
.dropdown ul {
  ...
  position: fixed;
}

Also if you have more than the two items in your dropdown, the dropdown menu will extend automatically.


text:
Q: Optimal operating system for self-hosted Windows agent? We are currently using multiple self-hosted build agents with Windows 10 as the operating system. In various pipelines in Azure Devops (whether Online or OnPremis), we have not had any bad experiences or questioned the OS we chose over the many years.
Now IT approached me and asked if there was anything wrong with using Windows Server 2019/2022 as the OS for a self-hosted build agent. I guess in the long run it would be a price advantage.
But are there any other advantages or disadvantages between Windows Server 2019/2022 and Windows 10/11?

A: There are no other advantages or disadvantages between Windows Server 2019/2022 and Windows 10/11. Only cost... and maybe system requirements of your build/external components.


text:
Q: how to get 100% test coverage for apex class? I tried to get up below class coverage from 62% to 100% but no luck..
what i am missing...?Please help me out...bold code in test class has not covered...
Apex class:
public with sharing class InvoiceGenerator {

public void generateInvoices() {
    Invoice_Generation_Frequency__c igf = Invoice_Generation_Frequency__c.getInstance('Default');
    system.debug('igf.Days__c:'+igf.Days__c);

    Integer currentYear = system.today().year();
    Integer currentDay = (system.today().addDays((integer)igf.Days__c)).day();
    system.debug('--day--'+currentDay);

    List<Account> accList = [Select Id,Group__c,Group_Signup_Start_Date__c,Group_Renewal_Date__c,Invoice_Amount__c From Account  where

    Group__c='yes' and CALENDAR_YEAR(Group_Renewal_Date__c) < = :currentYear and DAY_IN_MONTH(Group_Renewal_Date__c) = :currentDay];

    String currYear = system.today().year() + '%';
    //List<AggregateResult> arList = [select count(id) cnt from Invoice__c where Invoice_Number__c like :currYear];
    //nextInvNum = (integer)arList[0].get('cnt');

    List<Invoice__c> invnumberList = [select Invoice_Number__c from Invoice__c where Invoice_Number__c like:currYear order by Invoice_Number__c desc];
    List<Invoice__c> InvoiceList = new List<Invoice__c>();

    if(invnumberList.size() > 0){
        string invhighestnum = invnumberList[0].Invoice_Number__c;
        string convertedlast = invhighestnum.substring(5,9);
        integer InvNumhighest = integer.valueOf(convertedlast);
        system.debug('132654'+InvNumhighest);

        system.debug('--InvNumhighestnew--'+InvNumhighest);
        for(Account a : accList) {
            InvNumhighest++;
            Invoice__c Inv = new Invoice__c();
            Inv.Account__c = a.Id;
            Inv.Paid__c = false;
            Inv.Group_Start_Date__c = a.Group_Signup_Start_Date__c;
            Inv.Group_Renewal_Date__c = a.Group_Renewal_Date__c;
            Inv.Invoice_Amount__c = a.Invoice_Amount__c;
            Inv.Invoice_Number__c = (system.today().year() + '-' + InvNumhighest);
            InvoiceList.add(Inv);
            system.debug('--invList--'+InvoiceList);
        }
        insert InvoiceList;
    }
    else {
            **integer nextInvNum;
            nextInvNum = 0000;
            nextInvNum = nextInvNum + 2000;
            system.debug('--nextInvNum--'+nextInvNum);
            for(Account a : accList) {
                nextInvNum++;
                Invoice__c Inv = new Invoice__c();
                Inv.Account__c = a.Id;
                Inv.Paid__c = false;
                Inv.Start_Date__c = a.Group_Signup_Start_Date__c;
                Inv.Renewal_Date__c = a.Group_Renewal_Date__c;
                Inv.Invoice_Amount__c = a.Invoice_Amount__c;
                Inv.Invoice_Number__c = (system.today().year() + '-' + nextInvNum);
                InvoiceList.add(Inv);
            }
            insert InvoiceList;**
        }
  }
}

Test class:
 @isTest(SeeAllData=true)
 class TestInvoiceUpdate{

public static String CRON_EXP = '0 00 01 * * ?';

static testmethod void test() {

Test.startTest();

Account a = new Account();
a.Name = 'test';
a.Group__c = 'Yes';
Date myDate = date.newinstance((system.today().addYears(-1)).year(), (system.today().addDays(45)).month(), (system.today().addDays(45)).day());
a.Group_Renewal_Date__c = myDate;
insert a;
system.debug('Myinsert'+a);

Invoice__c i = new Invoice__c();
i.Paid__c = false;
i.Account__c = a.id;
i.Invoice_Number__c = '1111';
insert i;

String InvId = System.schedule('testBasicScheduledApex',CRON_EXP,new InvoiceUpdate());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :InvId];
// Verify the expressions are the same
System.assertEquals(CRON_EXP, ct.CronExpression);
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
Test.stopTest();

}

static testmethod void test1() {

Test.startTest();

Account a = new Account();
a.Name = 'test1';
a.Group__c = 'Yes';
Date myDate1 = date.newinstance((system.today().addYears(-1)).year(), (system.today().addDays(45)).month(), (system.today().addDays(45)).day());
a.Group_Renewal_Date__c = myDate1;
insert a;
system.debug('Myinsert'+a);

Invoice__c i = new Invoice__c();
i.Paid__c = false;
i.Account__c = a.id;
i.Invoice_Number__c = '2222';
insert i;

String InvId = System.schedule('testBasicScheduledApex',CRON_EXP,new InvoiceUpdate());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :InvId];
// Verify the expressions are the same
System.assertEquals(CRON_EXP, ct.CronExpression);
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
Test.stopTest();
   }
}

A: Your test code calls the InvoiceUpdate class, but you have only shown us the InvoiceGenerator class. Therefore, we cannot know why the class is not covered in your test code.
From the code you have shared, you should have ZERO percent coverage.


text:
Q: What is Tuple? And tuple vs. List vs. Vector? Can you give me a brief description of Tuple? And when to use it over List and Vector?

A: When ever you will do more insertion/deletion operations in a data structure you should use a List. When ever in a data structure accessing of variables is very frequent use a vector.
Tuples are objects that pack elements of different types together in a single object, just like pair objects do for pairs of elements, but generalized for any number of elements.
Conceptually, they are similar to plain old data structures (C-like structs) but instead of having named data members, its elements are accessed by their order in the tuple.

A: Tuple is usually represented in Clojure through an associative data structure such as map {:name "david" :age 35} or record.
A vector ["david" 35] offers fast positional access (= 35 (nth ["david" 35] 1)), and you can store different types.
A list ("david" 35) or ("david" "justin" "david") offers fast access from the head and fast forward traversal. Although it can hold different types it would be most common for it to contain a single type, possibly containing duplicates, in a determined order. Contrast to a set #{"david" "justin"} which would contain no duplicates and is optimised for checking membership/presence.
Sorted sets (sorted-set) and maps (sorted-map) maintain the order of objects using a comparator.
Check out 4clojure and clojuredocs.org. Good luck!


text:
Q: What are nodes in RNN/LSTM? In this blogpost "The Unreasonable Effectiveness of Recurrent Neural Networks" the author says, that he is training "a 2-layer LSTM with 512 hidden nodes" for character prediction.
So it will look somewhat like
y1 = rnn1.step(x)
y = rnn2.step(y1)

What I dont get: What are these 512 hidden nodes in a context of an LSTM?
My first guess was, that it might be the dimension of the
matrices like "self.W_hh" in the following code:
class RNN:
  # ...
  def step(self, x):
    # update the hidden state
    self.h = np.tanh(np.dot(self.W_hh, self.h) + np.dot(self.W_xh, x))
    # compute the output vector
    y = np.dot(self.W_hy, self.h)
    return y

So self.W_hh $\in \mathbb R^{\text{number of nodes*number of nodes}}$
(I assume, that it has to be quadratic matrices, since the output has to get reused in the next timestep, is that right?). But since the input vectors are one-hot encoded characters and also the output vectors are scores for character probability, the matrices have to have the dimension  $\mathbb R^{\text{number of characters*number of characters}}$ and number of characters are 26.
So it left me with the question, what are the nodes?

A: For fully-connected layers, the number of 'nodes' is the output dimension of the weight matrix.  In other words, if we have a hidden layer, where:

*

*input layer, dimension $d_i$

*hidden layer 1, dimension $d_h$

... then the weight matrix for hidden layer 1 will be $d_i \times d_h$. $d_h$ in this case is the number of 'nodes' of hidden layer 1, it is the output dimension.
In RNNs and LSTMs, these concepts are unchanged.
However, nuance: there is an embedding layer in the input and the output, for RNNs, in general. So, the layers are like this:

*

*input layer, dimension $d_i$ (corresponds to the one-hot dimension)

*embedding layer, dimension $d_h$ (embeds the one-hot vector into embedding dimension $d_h$; generally this is just a matrix multiplication)

*LSTM, dimension $d_h$ (contains various $d_h \times d_h$ matrices)

*output embedding, dimension $d_o$ (in char-rnn, $d_o = d_i$, it decodes from the output embedding vectors, back into a probabilitiy distribution over possible characters)


text:
Q: Frame described by locally flat metric is in general not an inerial frame - true or false? In general relativity there is always a locally flat system, for which the transformed metric is the Minkowski metric up to second order at one point. But this does not mean, that the system, described by the new coordinates is automatically an inertial frame. Is that right?
If this is true: why can I apply Lorentz transformation of special relativity in that metric? The metric is locally flat so SR applies - but the frame is nevertheless no inertial frame. Isn't that a contradiction, because Lorentz-transformations are valid only in inertial systems?
I'm confused...

A: I tis very important to notice that you can do this at a given point, but not at any given curve. In fact, it is true that for geodesics you can define a locally flat coordinate system such that the Christoffel symbols vanish along the curve. This is compatible with the idea of the equivalence principle for $inertial$ observers.
However, for more general trajectories, it is not possible to define a such a coordinate system: the Christoffel symbols get corrections due to the acceleration of the trajectory, and these are compatible with the notion of fictious forces that are seen due to non-inertiality.
The way to analyze the problem above is by means of the Fermi normal coordinates (FNC). These are a coordinate system that is associated with a timelike trajectory and describes "what an observer undergoing this trajectory sees". In case you want learn more about this, I recommend https://arxiv.org/abs/1102.0529. In any case, it is possible to show that the metric in FNC can be written locally around the curve (up to first order in acceleration and curvature) as
$$\begin{aligned}
&g_{\tau \tau}=-\left(1+2 a_{\mathrm{i}}(\tau) x^{i}+R_{0 \mathrm{i} 0 \mathrm{j}}(\tau) x^{i} x^{j}\right), \\
&g_{\tau i}=-\frac{2}{3} R_{0 \mathrm{jik}}(\tau) x^{j} x^{k} \\
&g_{i j}=\delta_{\mathrm{ij}}-\frac{1}{3} R_{\mathrm{ikjl}}(\tau) x^{k} x^{l}
\end{aligned},$$
where $\tau$ is the proper time of the trajectory (and the timelike coordinate of the FNC) and $x^i$ denote the proper distance from the trajectory, which are the spacelike trajectories of the FNC. $a(\tau)$ is the trajectories proper acceleration and $R(\tau)$ is the curvature tensor along its motion.
The Christoffel symbols to first order in acceleration and curvature then read
$$\begin{aligned}
\Gamma_{i j}^{\tau} &=\frac{1}{3}\left(R_{0 \mathrm{ijm}}+R_{0 \mathrm{jim}}\right) x^{m} \\
\Gamma_{\tau i}^{\tau} &=a_{\mathrm{i}}+R_{0 \mathrm{i} 0 \mathrm{~m}} x^{m} \\
\Gamma_{\tau \tau}^{\tau} &=0 \\
\Gamma_{j k}^{i} &=\frac{1}{3}\left(R_{\mathrm{j} \mathrm{km}}^{\mathrm{i}}+R_{\mathrm{k} \mathrm{jm}}^{\mathrm{i}}\right) x^{m} \\
\Gamma_{\tau j}^{i} &=R_{0 \mathrm{mj}}{\mathrm{j}} x^{m} \\
\Gamma_{\tau \tau}^{i} &=a^{\mathrm{i}}+R_{0}^{\mathrm{i}}{ }_{0 \mathrm{~m}} x^{m}
\end{aligned},$$
which can be seen to vanish if $a^i = 0$ (inertial motion) and $x^i = 0$ (on top of the curve).


text:
Q: Iframe Inside JSP call Servlet I have a question
I have a JSP page, it has textbox and button (type is button)
when i input into textbox and click a button, value will pass to servlet and servlet handle it, after that it return value to other jsp page,
a iframe in main page will refresh to show result.
How can i do it?
Thank for your answer or suggestion

A: This is a little bit complicated case, but it can be done with a little imagination.
First, you need to pass your data from the jsp to your iFrame's form. This can be done using buttons onclick event to copy data to hidden iframe inputs.
window.frames['myIFrame'].document.getElementById('myIFrameHidenInput').value = document.getElementById('myJSPinput').value;

After finishing you should post, the iframe form to your servlet.
window.frames['myIFrame'].document.getElementById('myFormId').submit();

After the response comes back from the sevlet. You can display whatever you want to it.
Here is a nice resource regarding iFrames ( http://www.dyn-web.com/tutorials/iframes/ )