text:
Q: Intersection Observer not working in browser While trying to use Intersection Observer to build an interactive HTML site, the images I used JavaScript on do not show up in the browser.
Why is this happening?
Here's the code:
const cards = document.querySelectorAll(".card")

const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      entry.target.classList.toggle("show", entry.isIntersecting)
    })
},
{
     threshold: 0.5,
})

cards.forEach(card => {
  observer.observe(card)
})

Menu

.card {
    transform: translateX(100px);
    opacity: 0;
    transition: 0.5s;
}

.card.show {
    transform: translateX(0);
    opacity: 1;
}

Stack Snippet:

const cards = document.querySelectorAll(".card")

const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      entry.target.classList.toggle("show", entry.isIntersecting)
    })
},
{
     threshold: 0.5,
})

cards.forEach(card => {
  observer.observe(card)
})
.card {
    transform: translateX(100px);
    opacity: 0;
    transition: 0.5s;
}

.card.show {
    transform: translateX(0);
    opacity: 1;
}

Menu


text:
Q: Azure Resources Management API. Authorization issue when creating Service Bus Hybrid Connection We try to use Azure Resources Management API to create a Hybrid Connection.
(https://learn.microsoft.com/en-us/rest/api/relay/hybridconnections.)
The problem we have is that every time we submit HTTP request it returns us 401 error with message:

{
  "error":{"code":"AuthenticationFailedInvalidHeader","message":"Authentication
  failed. The 'Authorization' header is provided in an invalid
  format."}}

We prefer to use REST API rather than SDK/nugget packages
Here is console app code:
using System;
using System.Globalization;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace HybridConnectionManagement
{
    class Program
    {
        public const string RelayAddress = "https://[namespace].servicebus.windows.net/";
        private static string RelaySasKeyName = "RootManageSharedAccessKey";
        private static string RelaySasKey = "[RootManageSharedAccessKey_Primary_Key]";

        static void Main(string[] args)
        {
            var createHybridConnectionEndpoint = "https://management.azure.com" +
                           "/subscriptions/[subscription_id]" +
                           "/resourceGroups/[resourceGroup]" +
                           "/providers/Microsoft.Relay" +
                           "/namespaces/[namespace]" +
                           "/hybridConnections/test-521?api-version=2017-04-1";

            var token = GetSASToken(RelayAddress, RelaySasKeyName, RelaySasKey);

            using (var httpClient = new HttpClient())
            {

                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);
                httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

                var response = httpClient.GetAsync(createHybridConnectionEndpoint).Result;
                var responseText = response.Content.ReadAsStringAsync().Result;

                //responseText is always:
                //{ "error":{"code":"AuthenticationFailedInvalidHeader","message":"Authentication failed.
                //The 'Authorization' header is provided in an invalid format."}}
                Console.WriteLine(responseText);
            }
        }

        public static string GetSASToken(string resourceUri, string keyName, string key)
        {
            var sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600); //EXPIRES in 1h
            string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
            var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
            var sasToken = String.Format(CultureInfo.InvariantCulture,
                "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
                HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

            return sasToken;
        }
    }
}

A: I was confused with different kinds of Authentication API.
For this case I didn't have to use SAS token. What I needed to use is Authorization Bearer token. Here is methods that acquires it:
        private string AcquireToken()
        {
            var credentials = new UserPasswordCredential(UserName, Password);
            var authenticationContext = new AuthenticationContext("https://login.windows.net/" + DirectoryName);
            var result = authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", AdClientId, credentials).GetAwaiter().GetResult();
            return result.AccessToken;
        }

So if you replace GetSASToken in sample above with this method, then it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing attribute of subclass within D3 based on dictionary value What is the best way to make sure I can differentiate each line by size based on the values of my dictionary.
Problem is all lines would adjust instead of my desired line and I am not sure how to approach it.
Down below is a simplified example.
draw.axis = function ()
{
    var element;
    function axis(g){
        element = g.append("g");

        element
            .append("g")
            .attr("class", axis dotted line)
            .attr("height", 100);  //default size

    }
}

var size_adjuster = [
    {size: "big",     adjusted: false  },
    {size: "regular", adjusted: false  },
    {size: "small",   adjusted: false  },
    {size: "small",   adjusted: true   },
    {size: "big",     adjusted: true   },
];

size_adjuster = function(){
    size_adjuster.forEach(function(item) {
        if(item.size == "big" && item.adjusted == false){
            item.adjusted == true;
            d3.selectedAll("g.axis.line line")
                .attr("height", 200);
        }
        else if(item.size == "regular" && item.adjusted == false){
            d3.selectedAll("g.axis.line line")
                .attr("height", 100);
        }
        else if(item.size == "small" && item.adjusted == false){
            d3.selectedAll("g.axis.line line")
                .attr("height", 50);
        }
    });
}


text:
Q: Kotlin - The accelerometer sampling rate is not independent of the location update interval I'm trying to make a sensor data collection app in Kotlin. However, I've been encountering a lot of issues when it comes to getting accelerometer data and location updates at different sampling rates. I need to set the accelerometer sampling rate at 4 Hz, and the location updates at 1 Hz.
Basically, changing the 'samplingPeriodUs' of the accelerometer's register listener has no impact on it, when I'm trying to get location updates. I'm able to get the location updates once every second just fine, but the accelerometer values are changing too rapidly and not accurately.
I've tested this as well. When I remove the location updates, and just check the accelerometer values, they are changing much more slowly and at a rate I want. When I try to get the location updates as well, the accelerometer sampling rate suddenly has no effect, and the values start changing too rapidly.
I've looked everywhere for a solution, but I cannot seem to find it. I would be very grateful if someone could help this very confused beginner!
Additionally, I am also attaching a snippet of the code:
class MainActivity : AppCompatActivity() {

    var latitude : Double = 0.0
    var longitude : Double = 0.0
    // start button flag
    private var resume = false

    private val locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult?) {
            locationResult ?: return
            for (location in locationResult.locations) {

                if (resume)
                {
                    latitude = location.latitude
                    longitude = location.longitude
                    findViewById<TextView>(R.id.longt).text = longitude.toString()
                    findViewById<TextView>(R.id.lat).text = latitude.toString()
                }

            }
        }
    }

    private val accelerometerListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {

            var sensor_label = ""
            var accelerometer_x = "0.0"
            var accelerometer_y = "0.0"
            var accelerometer_z = "0.0"

            var gyroscope_x = "0.0"
            var gyroscope_y = "0.0"
            var gyroscope_z = "0.0"

            if (event != null && resume)
            {
                if (event.sensor.type == Sensor.TYPE_ACCELEROMETER)
                {

                    val accX = event.values[0]
                    val temp01:Double = String.format("%.3f", accX).toDouble()
                    findViewById<TextView>(R.id.acc_X).text = temp01.toString()

                    val accY = event.values[1]
                    val temp11:Double = String.format("%.3f", accY).toDouble()
                    findViewById<TextView>(R.id.acc_Y).text = temp11.toString()

                    val accZ = event.values[2]
                    val temp21:Double = String.format("%.3f", accZ).toDouble()
                    findViewById<TextView>(R.id.acc_Z).text = temp21.toString()

                    accelerometer_x = temp01.toString()
                    accelerometer_y = temp11.toString()
                    accelerometer_z = temp21.toString()
               }

           }
        }

        override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
    }

    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Request location updates
        val locationRequest = LocationRequest().apply {
            interval = 1000
            fastestInterval = 1000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }
        val locationClient = LocationServices.getFusedLocationProviderClient(this)
        if(CheckPermission()){
            if(isLocationEnabled()){
                locationClient.requestLocationUpdates(locationRequest, locationCallback, null)
            }else{
                Toast.makeText(this, "Location service not enabled", Toast.LENGTH_SHORT).show()
            }

        }else{
            RequestPermission()
        }

        // Register accelerometer sensor listener
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
        val desiredInterval = SensorManager.SENSOR_DELAY_NORMAL

        Timer().scheduleAtFixedRate( object : TimerTask() {
                override fun run() {
                    sensorManager.registerListener(accelerometerListener, accelerometer, 100000, )
                }
            }, 0, 1000)
    }

    override fun onPause() {
        super.onPause()
        // unregister the sensor listener
        val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensorManager.unregisterListener(accelerometerListener)
    }

    private fun CheckPermission() : Boolean {
        if( (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
            || (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) ){
            return true
        }

        return false
    }

    private fun RequestPermission() {

        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ), 1000
        )

    }

    private fun isLocationEnabled() : Boolean{
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == 1000){
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                println("Permission granted")
            }
        }
    }

    // button start and stop
    fun resumeReading(view: View) {
        if (this.resume == true)
        {
            Toast.makeText(this, "Data collection has already been started!", Toast.LENGTH_SHORT).show()
        }
        else if (this.resume == false)
        {
            this.resume = true
            Toast.makeText(this, "Data collection has begun!", Toast.LENGTH_SHORT).show()

        }
    }

    fun pauseReading(view: View) {
        if (this.resume == false)
        {
            Toast.makeText(this, "Data collection has already stopped!", Toast.LENGTH_SHORT).show()
        }
        else if (this.resume == true)
        {
            this.resume = false
            Toast.makeText(this, "Data collection has stopped!", Toast.LENGTH_SHORT).show()
        }
    }

}


text:
Q: phpBB sql transaction function not working I'm using phpBB and this code is not working as expected.  It's simply using the phpBB sql_transaction function to start an sql transaction, then commit it.  But the exception should be thrown half way through and issue a rollback using the same function.
However, the rollback never happens.  Queries 1 and 2 take effect, and I can't get them to rollback.
The documentation states that if there is an sql error, it will automatically issue a rollback, but I'm trying to roll it back if there is a php error, such as a timeout or something.
I'm using MySQL 5.7, phpBB 3.0.11, and php 5.6.
Can someone point out the issue?
$db->sql_transaction('begin');

try {
    $sql = 'UPDATE aaa_temp SET method = "a" WHERE id = 1';
    $db->sql_query($sql);

    $sql = 'UPDATE aaa_temp SET method = "b" WHERE id = 2';
    $db->sql_query($sql);

    throw new Exception('OMG TOTAL ERROR');

    $sql = 'UPDATE aaa_temp SET method = "c" WHERE id = 3';
    $db->sql_query($sql);

} catch (Exception $ex) {
    $db->sql_transaction('rollback');
    trigger_error($ex->getMessage(), E_USER_ERROR);
}

$db->sql_transaction('commit');

Thanks in advance!  I know it's got to be something really simple and stupid, but let me know if more detail is needed.
EDIT: Just so it's clear, I'm talking about SQL transactions in MySQL.

A: It turns out that the table I was trying to rollback updates to was using the MyISAM storage engine, which doesn't support transactions.
Ironically, that is specifically how phpBB builds them.  sql_transaction('rollback') returned true because the rollback did indeed work, it just didn't pick up on the SQL warning about data not being rolled back.
Figured this out by enabling the general_query_log in MySQL to see exactly what this function was doing in the background:
SET AUTOCOMMIT=0;

UPDATE aaa_temp SET method = "a" WHERE id = 1;

UPDATE aaa_temp SET method = "b" WHERE id = 2;

ROLLBACK;

SET AUTOCOMMIT=1;

So since I had a mixture of MyISAM and InnoDB tables, changes to the latter ones were being rolled back while changes to the formers were not.

A: You have a misconception of how Exceptions work. If you have a try{...}catch(...){...} block, and an exception is thrown somewhere inside the try{...} portion, then that is a signal that your codes flow will jump to the beginning of the catch(...){...} block.
All code that happened before the exception was thrown does happen. Only code inside the try block that is after the exception does not happen. There is no rollback that takes place that eliminates all processes that were done previously because that would be extremely (extraordinarily) difficult for the php developers to make. Imagine if your php code did something like send an email. How do you expect a rollback to take place then when the email was already sent? Hence, rollbacks do not happen.


text:
Q: Is there any pitfalls running Tomcat and JBoss on the same server? I need to run on my development Linux server an instance of Tomcat v6.0 so I can test the apps I develop. On the same (physical) server, I need to run an instance of hudson-ci. Since Tomcat will be on and off more often than not, I consider running another server (i.e. JBoss AS 6) on a different port for the continuous integration software.
Is there any pitfalls I should be mindful of ahead of time?

A: No, just make sure there are no port conflicts (each one will use multiple ports). You should be able to start Tomcat, and then start JBoss, look for errors, fix, repeat.


text:
Q: Can't receive chat message if I don't send one first I checked out similar questions But I could not solve my problem.
I implemented a chat app using Smack 4.2.
The strange thing is that I can only receive chat messages if I send one one first.
Here is my connection code:
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setHost(HOST)
.setPort(PORT)
.setXmppDomain(serviceName)
.setUsernameAndPassword(USERNAME + "@"+HOST, PASSWORD)
.setCompressionEnabled(false)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setSendPresence(true)
.build();

connection = new XMPPTCPConnection(config);
connection.connect();
connection.login();

And this is how I send the message:
final Message msg = new Message();
msg.setTo(jid);
msg.setFrom(myjid);
msg.setBody(message.getText().toString());
msg.setStanzaId(rd);
msg.setType(Message.Type.chat);
connection.sendStanza(msg);

How can I receive a message even BEFORE I send one to the other user ?
Thanks!!!
SOLVED
I cannot believe I wasted so much time on this. The problem is that Smack 4.2.0 is buggy (it's a beta version after all). All I needed to do is use Smack 4.1.9 instead.


text:
Q: @ConversationScoped bean behaves as @RequestScoped since OmniFaces 2.5 FacesViews I tried to upgrade my Java EE 7 / JSF 2.2 application to Omnifaces 2.6. Currently I am running version 2.4.
After that, I have noticed a strange behavior when using @ConversationScoped and Ajax-Requests. When calling, the area, which should get rendered after the request, gets cleared (no exception on the server, response status code 200).
Next, I have a kind of wizard implementation, based on @ConversationScoped. It holds a class called ViewManager which has itself a List of Views. Initializing works fine and this list gets filled. But somehow it gets cleared (set to null) when the first form/view gets submitted. The setter for this is never called after the initialization, so it is not changed by my code. Somehow the view manager instance is still available, only this list of view within the view manager is null, which is kind of strange.
With omnifaces 2.4, everything did work fine (this is why I did not add some code of my wizard). I checked the changelog and noticed the MultiViews configuration when using ExtensionlessURLs. Don't know why this could effect my problem, but i tried it...with no success.
I have no idea what could be the problem, so maybe you can help me.
Thanks in advance :)

A: In OmniFaces, the FacesViews extensionless URLs feature got in version 2.5 an overhaul in order to support the so-called MultiViews as you can read on this blog.
During this overhaul I made a backwards compatibility mistake in the FacesViewsViewHandler where the <h:form> action URL is being manipulated in order to include the virtual folders of the MultiViews feature. The query string parameters were dropped from the original action URL and not added back.
The @ConversationScoped relies on the cid request parameter being present in the <h:form> action URL as in /context/page?cid=1. This thus became /context/page and therefore the conversation isn't retained across postbacks.
I will fix this in next OmniFaces release, for now you can get back the desired behavior by adding the below context parameter to web.xml.
<context-param>
    <!-- Workaround for disappearing @ConversationScoped ?cid= parameter -->
    <!-- This can be removed in next OmniFaces version after 2.6 -->
    <param-name>org.omnifaces.FACES_VIEWS_VIEW_HANDLER_MODE</param-name>
    <param-value>BUILD_WITH_PARENT_QUERY_PARAMETERS</param-value>
</context-param>

This parameter triggers a different way of building the URL whereby the entire query string from the original action URL is explicitly retained.


text:
Q: Magento connect issue when trying to load ANY extentions I was wondering if anyone else was having the same issue:
community/Locale_Mage_community_fr_FR: Unknown cipher in list: TLSv1
Was trying to load the French language extention as well as other one's but ufortunately came up with the above error. We had no changes on the server or anything else, other versions are working fine.
The only thing we had done different was URL re-writes (which after deletion did not change anything) as well as different URL assigned to store views (DE,FR,PL, etc have their own URL's).
We uploaded it to test the new Magento but it seems to cause problems.
Anyone has a clue on how to approach this issue?


text:
Q: Powershell working with Directories Hi new to Powershell only ever butchered existing scripts or worked with bash before.
I am trying to list all directories with one criteria and then execute a commend on their contents.
Basically I want to recursively search all dirs called Processed and remove all items over 31 days. What I have so for are the commands below:
$limit = (Get-Date).AddDays(-31)
$path = "C:\Users\mark.hodgson\Desktop\New folder"
$dirs = Get-ChildItem $path -Recurse -Directory| Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "Processed"} |select-object Fullname

When I echo $dirs the list looks good as below:
PS C:\Users\mark.hodgson\Desktop\New folder> echo $dirs

FullName
--------
C:\Users\mark.hodgson\Desktop\New folder\Folder1\FolderA\Processed
C:\Users\mark.hodgson\Desktop\New folder\Folder1\FolderB\Processed
C:\Users\mark.hodgson\Desktop\New folder\Folder2\Processed
C:\Users\mark.hodgson\Desktop\New folder\Folder3\Processed
C:\Users\mark.hodgson\Desktop\New folder\Folder4\Processed
C:\Users\mark.hodgson\Desktop\New folder\Folder5\Processed

but when I try to work with the items as below or even just do an ls it returns or deletes all folders off my desktop!!
$dirs | ForEach-Object { Get-ChildItem -Recurse -Force | Where-Object { !$_.PSIsContainer -eq $_.LastWriteTime -lt $limit } | Remove-Item -Force }

same if I use for $dir in $dirs
I must be getting the basics wrong here! I can hard code the paths but would love to do a proper job.
Cheers,
hodgm

A: You need to reference the current pipeline item inside the ForEach-Object body:
$dirs | ForEach-Object { Get-ChildItem $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit } | Remove-Item -Force }


text:
Q: How to move files from subfolders with certain extension to different subfolder I have tens of thousands .jpg's in folders like .\[date]\jpg , for example:
.\2018_03_01\jpg
.\2018_03_02\jpg

...and so on.
I need to move them one step backwards, i.e.
.\2018_03_01\jpg\*.jpg

...to
.\2018_03_01\*.jpg

...and so on.
All of those date-named folders don't contain the jpg subfolder these occasions should be dealt with.
I suppose this can be done with XCopy or traditional .bat batch, but how?

A: The command XCOPY is for copying files and entire directories and not for moving files.
The solution is using a FOR loop in a command prompt window. There is no need for a batch file.
Open a command prompt window in the directory containing the subdirectories 2018_03_01 and 2018_03_02 and run following command line:
@for /D %I in (*) do @if exist "%I\jpg\*.jpg" echo Move files from %I\jpg ... & move "%I\jpg\*.jpg" "%I\" & rd "%I\jpg"

This FOR command line processes each non hidden subdirectory in current directory.
For each subdirectory an IF condition is executed to check existence of any *.jpg file in subdirectory jpg of current date subdirectory.
On true condition first an information is output with ECHO telling you what happens next. Then the command MOVE is executed to move the JPEG files from subdirectory jpg one level up in directory hierarchy and last command RD is executed to delete subdirectory jpg if it is empty now.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*echo /?

*for /?

*if /?

*move /?

*rd /?
See also Single line with multiple commands for an explanation of & used twice in the command line.


text:
Q: Spring Hibernate PrimeFaces error with PostgreSQL schema url I have some problem about connecting postgresql database with spring bean,
the database url is jdbc:postgresql://localhost:5432/Misure, in this there are many schema, and in the schema monitoraggio there are many table, I want the table clienti
This is my code:
application-context.xml

    <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
    <!-- Enable Spring Annotation Configuration -->
    <context:annotation-config />
    <!-- Scan for all of Spring components such as Spring Service -->
    <context:component-scan base-package="spring.service"></context:component-scan>
    <!-- Create Data Source bean -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/Misure" />
        <property name="username" value="postgres" />
        <property name="password" value="Fabio1990"/>
    </bean>
    <!-- Define SessionFactory bean -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>Cliente.hbm.xml</value>
            </list>
        </property>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
    </bean>
    <!-- Transaction Manager -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- Detect @Transactional Annotation -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

This is hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    </session-factory>
</hibernate-configuration>

This is cliente.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="data.Cliente" table="clienti">
    <id column="id" name="clienteId" type="java.lang.Long">
      <generator class="identity">
        <param name="identity">clienti_id_seq</param>
      </generator>
    </id>
    <property column="nome" name="clienteNome" type="string">
    </property>
    <property column="cognome" name="clienteCognome" type="string">
    </property>
    <property column="telefono" name="clienteTelefono" type="string">
    </property>
    <property column="mail" name="clienteMail" type="string">
 </property>
    <property column="permesso" name="clientePermesso" type="string">
    </property>
    <property column="commessa" name="clienteCommessa" type="string">
</property>
  </class>
</hibernate-mapping>

This is registerCliente.java:
package beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import data.Cliente;
import spring.service.ClienteService;

@ManagedBean
@SessionScoped
public class RegisterCliente {

    @ManagedProperty("#{clienteService}")
    private ClienteService clienteService;

    private Cliente cliente = new Cliente();

    public ClienteService getClienteService() {
        return clienteService;
    }

    public void setClienteService(ClienteService clienteService) {
        this.clienteService = clienteService;
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public String register() {
        // Calling Business Service
        clienteService.register(cliente);
        // Add message
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("The Employee "+this.cliente.getClienteNome()+" Is Registered Successfully"));
        return "";
    }
}

This is clienteService.java:
package spring.service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import data.Cliente;

@Component
public class ClienteService {
    @Autowired
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Transactional
    public void register(Cliente cliente){
        // Acquire session
        Session session = sessionFactory.getCurrentSession();
        // Save employee, saving behavior get done in a transactional manner
        session.save(cliente);
    }
}

and this is a simple form by primeface:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <script name="jquery/jquery.js" library="primefaces"></script>
    <title>Register Employee</title>
</h:head>
<h:form>
    <p:growl id="messages"></p:growl>
    <p:panelGrid columns="2">
        <p:outputLabel value="Enter Employee Name:"></p:outputLabel>
        <p:inputText value="#{registerCliente.cliente.clienteNome}"></p:inputText>
        <p:outputLabel value="Enter Employee cognome:"></p:outputLabel>
        <p:inputText value="#{registerCliente.cliente.clienteCognome}"></p:inputText>
        <p:outputLabel value="Enter Employee Telefono"></p:outputLabel>
        <p:inputText value="#{registerCliente.cliente.clienteTelefono}"></p:inputText>
        <p:outputLabel value="Enter Employee Mail"></p:outputLabel>
         <p:inputText value="#{registerCliente.cliente.clienteMail}"></p:inputText>
        <p:outputLabel value="Enter Employee Commessa"></p:outputLabel>
         <p:inputText value="#{registerCliente.cliente.clienteCommessa}"></p:inputText>
    </p:panelGrid>
    <p:commandButton value="Register" action="#{registerCliente.register}" update="messages"></p:commandButton>
</h:form>
</html>

The error is:
ERROR: ERROR: the relation "clienti" not exist
  Position: 13
mar 19, 2015 4:29:53 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
AVVERTENZA: #{registerCliente.register}: org.hibernate.exception.SQLGrammarException: could not execute statement
javax.faces.FacesException: #{registerCliente.register}: org.hibernate.exception.SQLGrammarException: could not execute statement
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.hibernate.exception.SQLGrammarException: could not execute statement
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 19 more
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3556)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:97)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:480)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:191)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:175)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:210)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at spring.service.ClienteService.register(ClienteService.java:28)
    at spring.service.ClienteService$$FastClassByCGLIB$$a5b2d0d5.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:710)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:643)
    at spring.service.ClienteService$$EnhancerByCGLIB$$d4d2685b.register(<generated>)
    at beans.RegisterCliente.register(RegisterCliente.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:191)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:272)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 20 more
Caused by: org.postgresql.util.PSQLException: ERRORE: la relazione "clienti" non esiste
  Posizione: 13
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 61 more

mar 19, 2015 4:29:54 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.faces.el.EvaluationException: org.hibernate.exception.SQLGrammarException: could not execute statement
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3556)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:97)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:480)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:191)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:175)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:210)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:711)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:703)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:698)
    at spring.service.ClienteService.register(ClienteService.java:28)
    at spring.service.ClienteService$$FastClassByCGLIB$$a5b2d0d5.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:710)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:643)
    at spring.service.ClienteService$$EnhancerByCGLIB$$d4d2685b.register(<generated>)
    at beans.RegisterCliente.register(RegisterCliente.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:191)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:272)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 20 more
Caused by: org.postgresql.util.PSQLException: ERRORE: la relazione "clienti" non esiste
  Posizione: 13
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 61 more

i think Spring context don't find the schema "monitoraggio", but see only the general database "misure", and it can't find the request table "clienti"
Can you tell me if is possibile to insert in the database-url the schema? i've tryed with misure?defaultschema=monitoraggio but doesn't work.
Thanks a lot for the answer
EDIT:
If I use hibernate.cfg.xml for connecting my database, the code begin:
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Misure</property>
    <property name="hibernate.default_schema">monitoraggio</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">Fabio1990</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="Cliente.hbm.xml"/>
  </session-factory>

</hibernate-configuration> -->

and with the string
`<property name="hibernate.default_schema">monitoraggio</property>`

provide me to see the correct schema and the correct table, but I want do it with spring and the beans dataSource in the applicationcontext.xml file

A: in postgres  concept is different here is concept of Database &schema one Database have lot of schema & hibernate take public schema by default & you are connecting it with  Database not with schema
you  can do one thing i am giving you option
1.decelare schema at   Dao level
2 at Entity level hibernate have  keyword schema at the time of entity intalization

A: @Entity
@Table(name="demotable" ,schema="demo")
public class DemoEntity{
}
please see I think it will help you I mean to say you are making hbm.xml file But  make Entity in java  is good
I also edit you hbm file see
use it may be it work for you
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="data.Cliente" schema="monitoraggio"  table="clienti">
    <id column="id" name="clienteId" type="java.lang.Long">
      <generator class="identity">
        <param name="identity">clienti_id_seq</param>
      </generator>
    </id>
    <property column="nome" name="clienteNome" type="string">
    </property>
    <property column="cognome" name="clienteCognome" type="string">
    </property>
    <property column="telefono" name="clienteTelefono" type="string">
    </property>
    <property column="mail" name="clienteMail" type="string">
 </property>
    <property column="permesso" name="clientePermesso" type="string">
    </property>
    <property column="commessa" name="clienteCommessa" type="string">
</property>
  </class>
</hibernate-mapping>

A: There is no defaultschema=monitoraggio parameter for the JDBC driver.
Since the driver version 9.3-1103  you can use currentSchema=monitoraggio though.
For a list of all valid connection parameters, please see the manual:
https://jdbc.postgresql.org/documentation/94/connect.html#connection-parameters
A more robust solution would be to change the search_path of your user to make it permanently point to that schema making unquoted table references work:
alter user postgres set search_path = 'monitoraggio,public';

Don't forget to commit that if you have turned autocommit off in your SQL client.

Unrelated but:
By default postgres is the superuser for the database. It is usually not a good idea to use that for your regular work (it's like working as root in Linux all the time). You should create a regular user to manage your application tables.

A: unfortunately the dialog to hibernate for postgres is not the top.
To solve the problems of mapping you have to have is setup like this:
suppose we use spring4 + hibernate4:
in servlet-context.xml you must have the following configuration:
dataSource:
<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/yourDb" />
        <property name="username" value="user" />
        <property name="password" value="password" />
    </bean>

sessionFactory:
<bean id="SessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
                <value>org.youre.package.dto</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

Java code mapping:
@Entity
@Table(name = "nametable")
public class NameObjectimplements Serializable{
    private UUID  id;
    private String firstName;
    .
        .
        .
     //   etc...

    public NameObject() {

    }

    @Id
    @Column(name = "ID")
**@org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType")**
    public UUID  getId() {
        return id;
    }
    @Column(name = "`firstName`")
    public String getFirstName() {
        return firstName;
    }

//   setter method....

the important backquotes !!!! Because unfortunately it is case sensitive !!!!
Do DAO, the Service and for inserting the Controller must set your UUID as follows:
@RequestMapping(value = "obj/save", method = RequestMethod.POST)
    public String insertObject(HttpServletRequest request, Model model) {
        NameObject obj= new NameObject();
        obj.setId(UUID.randomUUID());
        objService.saveUser(obj);  //@Autowried
        return "obj/saveok";
    }


text:
Q: How to get the size of a Text View in SwiftUI w/o rendering the view? On my content view, I'd like to display a small table. To illustrate: In HTML I'd just say

First item	First value

Second item	Second value

Third item	Third value

In SwiftUI, I could do this:
VStack {
    HStack {
        Text("First item")
        Spacer()
        Text("First value")
    }
    HStack {
        Text("Second item")
        Spacer()
        Text("Second value")
    }
    HStack {
        Text("Third item")
        Spacer()
        Text("Third value")
    }
}

However, these HStack()s will use all available space. I want to shrink the table's width dynamically to the minimum, like HTML would do. I know I can use a LazyVGrid, but then I'd need to compute the column widths by myself.
Looks easy... Just iterate over each rows Text()s, and note the maximum value.
However: There seems to be no easy way to get the dimensions of a view without rendering it first.
I'm lost. Should I render the Text()s in a lonely corner of my View in transparent color to obtain the dimensions?
I feel that this should be easy, and that I'm missing something obvious.


text:
Q: Docker memory limit is exceeded I have the following docker-compose file:
version: "2.4"
services:
  auto_check:
    image: python
    mem_limit: 97M

That upon startup runs the following python script:
x = 'a' * (2 * 10 ** 8)

As expected, the docker fails with error code 137.
However, when I set mem_limit: 98M, the error does not reproduce.
Any idea why docker allows such an extreme memory limit violation?
The image size is 135MB (ubuntu20+python3).
(Running on WSL2-ubuntu:20.04)
Thanks for helping!

A: This happens because memswap_limit defaults to the value of mem_limit, meaning you get mem_limit regular memory and another memswap_limit ( == mem_limit) of swap memory, for a total of 2x mem_limit.
You can either set mem_limit to be half as much as your actual required limit, or alternatively you can set memswap_limit: 0M to disable swap altogether.
Running
/usr/bin/time --verbose python3 -c "x = 'a' * (2 * 10 ** 8)" 2>&1 1>/dev/null | grep 'Maximum resident'

on my machine we can see that
Maximum resident set size (kbytes): 203708

memory is used by this Python script at its peak. In MiB terms that's 203708000 / 1024 / 1024 ~ 194MiB. Half of that is ~97MiB. That's where the 98-99M limit you observed comes from. ~98MiB for regular memory, ~98MiB for swap, a total of ~194MiB, which is ~the peak memory consumption of python3 -c "x = 'a' * (2 * 10 ** 8)"


text:
Q: Git LFS not commiting large files I am trying to add 2 files to git LFS. Here is the console output:
But in Sourcetree I get this:

But in my repo it says:

I'm new to Git LFS so not sure the order of everything. I feel it's all setup ready to go but trying to commit I still get the error telling me to add them to LFS. Did i miss something?
Thanks


text:
Q: Edit hosts file from within PowerShell I need to be able to manage my environments using a PowerShell script.  I need to change my host file periodically.  However, whenever I try to edit the host from my script, I get the following error:
Access to the path C:\windows\system32\drivers\etc\hosts is denied

Currently my script looks like this:
Function ManageHosts([string] $environment)
{
cd C:\windows\system32\drivers\etc
if($environment.StartsWith("p"))
{
get-content .\hosts.prod | set-content .\hosts -force
}
else
{
get-content .\hosts.dev | set-content .\hosts -force
}
}

A: This is a question of privileges.  If you're an admin on your local box, I can help.
Try this: Right-click your Powershell icon and select Run As Administrator.  Then try running your script; it will work.
However, this doesn't answer how you can do this from within a script.  You can add some code to your script that will automatically try to make your PS session elevated, but you will still have to interact with the security dialog box that shows up anytime you try and run something as an admin that's Vista or later.  So, not sure how much easier this is than just starting your session as an admin, but add this to the beginning of your script:
$WindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$WindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($WindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($WindowsPrincipal.IsInRole($adminRole))
{
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
}
else
{
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
exit

A: You need to run this script with administrator privileges. Simply open PowerShell ISE as Administrator and it should run.
If you're looking to automate the running of the script, you'll need to run this as a startup script, or use psexec to execute as System or Administrator, or create a scheduled task.


text:
Q: I have a complicated density function, how to find the constant? Say, I have a density function: $f(x)=a e^{-((x-c)^2-b^2)^2}$ and $x$ can take any value in the real line. Obviously, I want to figure out the relation between $a$, $c$ and $b$ to make its integral to $1$. Can anyone provide some hints?

A: I fear there is no closed form for what you're searching, but I might be wrong!
You can anyway simplify the setting a bit, noticing that the parameter $c$ only shifts the function along the $x$-axis, so you can take WLOG $c=0$. Also, since the parameter $b$ has a symmetric role (i.e. if you replace $b$ with $-b$ the function does not change) you can work only on the following constraint
\begin{equation}
2a\int_0^{+\infty}e^{-(x^2-b^2)^2} dx = 1
\end{equation}
with $b\geq 0$ and $a>0$.


text:
Q: Weird line break added to ajax loaded content I'm having the same problem explained there except the mysterious line breaks is added at the beginning of my loaded content.
When using Firebug or different inspector, here's what I have:

                                                  <--- ghost line

And this ghost line results in a line break when displaying content.
Also, this problem happens only for one of my ajax request. I'm actually using it inside the jquery droppable & sortable.
Here's my code if you can spot something wrong:
$(".form_container").sortable({
        // ...
        receive: function(event,ui) {
            // ...
            $.ajax({
                dataType: 'html',
                data: '',
                type: 'GET',
                url: link,
                success: function (data){
                    // ...
                    $('.form_container').find('.form_item').html(data);
                }
            });
        }
    });

I've already been through my code to delete empty lines at the end of my files but nothing changed.
I'm waiting for your precious answer. Thanks!
---  1st EDIT ---
The link is a simple URL. That URL is a controller that send back pure HTML. When checked with Firebug, the response has no line break in it.
---  2nd EDIT ---
The element I'm dropping on my sortable list looks something like this

....

Then I get the link value in JS in order to perform the request.
I tried to change this line
$('.form_container').find('.form_item').html(data);

for
$('.form_container').find('.form_item').html('Test');

And then I've no problem. If I try to debug data (with alert(data) or in Firebug), the HTML is correct, no line breaks. :(

A: To me its seems to be server side issue .
Possible debug spots :

*

*server side script from where the response is generated

*trim the data if not sure of server side script
$('.form_container').find('.form_item').html(data.trim());

*use CSS to ignore the spaces on parent element e.g

Hope this will help

A: Are you able to tighten up the spaces in the HTML?
Spaces / line-breaks in code can be interpreted as textnodes and rendered as spaces and/or line breaks on the page.
See if this works:


text:
Q: CKeditor remove all html tag except div,span on paste event I want to remove all html tags from CKeditor when user uses Ctrl+v to paste the content.  Following is the code I've written. Not working as I expected.
<script type="text/javascript">
    CKEDITOR.on('instanceReady', function(ev) {
    var edits=ev.editor;
    edits.on( 'paste', function(event) {
        var content =  event.data['html'];
        content = $('<div />').html(content).text();
        var $temp=$(content).find('br,p').contents().unwrap().end().end();
        var newtext = $temp.text();
        edits.setData(newtext);
    });
    });
</script>

1) I wish to remove all the tags except div,span. But In my code I've to specify which tag to remove. I'm sure there must be some better way to do that
2) Also this code is removing all html tags too. So definitely something is wrong with code
Any better suggestions ??

A: Try this:
function strip_tags(html, keepTags) {

    var ptn = new RegExp('<(?!\/?(' + keepTags.join('|') + '))[^>]+>', 'g');
    return html.replace(ptn, '');
}

$('').html(content).text() will remove all tags, so just use strip_tags(content,  [ 'div', 'span' ]);
http://jsfiddle.net/rooseve/tqHLu/1/


text:
Q: how to remove an entire line in with a pattern using sed i have a file :
hi:: hello hai
welcome
bye

I want to remove the lines with the word hi
I tried the following command:
sed -i -e "/hi/d" filename

but the output was
 :: heloo hai

How can I remove the entire line using sed?? That is the line "hi::hello hai"

A: Try /^.*hi.*$/d  can.t test right now so it is a wild guess

A: This should be sufficient:
sed -e '/hi/d' file

Tested and works.
tom@eee ~ % cat test
hi:: hello hai
welcome
bye
tom@eee ~ % sed -e '/hi/d' test
welcome
bye

Also as damienfrancois stated grep works too:
tom@eee ~ % grep -v 'hi' test
welcome
bye

A: Using awk you can do this
awk '!/^hi/' file
welcome
bye

This will remove lines with hi in start of line.  You does not say if the world can be in middle of the sentence. If so, do:
awk '!/hi/'
welcome
bye


text:
Q: Sorting Events in MySQL by start and / or end date I have the following starting position:
In a table are events with a start and end date.
I would like to sort these events in the query with the following dimensions:
current events > future events > completed events
SELECT
    startAt,
    endAt,
    (
        CASE
            WHEN DATE(endAt) > DATE(NOW()) AND DATE(startAt) < DATE(NOW()) THEN 1
            WHEN DATE(endAt) > DATE(NOW()) AND DATE(startAt) > DATE(NOW()) THEN 0
            ELSE -1
        END
    ) as position
FROM
    events
ORDER BY
    position DESC

Now the problem:
Sorting by the three categories works with the above query, but within the categories the following sortings must be applied:
Current events (sorted by end date) > future events (sorted by start date) > completed events (sorted by end date)
So first all running events that will expire soon will come in descending order (i.e. have more time than the previous ones), then all future events that will start soon in descending order (i.e. start later than the previous ones) and then all completed events in descending order.
SOLVED with the help of @Tim Biegeleisen
SELECT
    startAt,
    endAt
FROM
    events
ORDER BY
    (
        CASE
            WHEN endAt > CURDATE() AND startAt < CURDATE() THEN 1
            WHEN endAt > CURDATE() AND startAt > CURDATE() THEN 0
            ELSE -1
        END
    ) DESC,
    (
        CASE
            WHEN startAt < CURDATE() THEN endAt
            ELSE startAt
        END
    ) ASC

A: You may try this logic:
SELECT
    startAt,
    endAt
FROM events
ORDER BY
    CASE WHEN startAt < CURDATE() THEN endAt ELSE startAt END;

The logic of the above ORDER BY clause is that if an event's start date be strictly less than right now, then it means that the event is either in progress or completely finished, in which case we sort using its endAt value.  Otherwise, we sort using startAt.
Based on your comments below, it seems that you also want to first order records by the event status, then order within each group:
SELECT startAt, endAt
FROM events
ORDER BY
    CASE WHEN endAt > CURDATE() AND startAt < CURDATE() THEN 0
         WHEN endAt > CURDATE() AND startAt > CURDATE() THEN 1
         ELSE 2 END,
    CASE WHEN startAt < CURDATE() THEN endAt ELSE startAt END;

A: Try case statement to select he date for order.

  SELECT
    startAt,
    endAt,
    (
        CASE
            WHEN DATE(endAt) > DATE(NOW()) AND DATE(startAt) < DATE(NOW()) THEN 1
            WHEN DATE(endAt) > DATE(NOW()) AND DATE(startAt) > DATE(NOW()) THEN 0
            ELSE -1
        END
    ) as position
  FROM
        events
  ORDER BY
      CASE
          WHEN DATE(endAt) > DATE(NOW()) AND DATE(startAt) < DATE(NOW()) THEN endAt
          WHEN DATE(endAt) > DATE(NOW()) AND DATE(startAt) > DATE(NOW()) THEN startAt
      ELSE endAt
      END DESC


text:
Q: Essential singularity and pole Prove that if $f$ has an essential singularity at $z_0$ and $g$ has a pole at $z_0$, then $f+g$ has an essential singularity at $z_0$
I know that if $z_0$ is an essential singularity then |f(z)| is neither bounded near $z_0$ nor goes to infinity as $z \to z_0$ and vice versa. But evaluating $|f+g|$ as $z \to z_0$ we see $|f+g| \leq |f|+|g|$ which clearly is unbounded (since both $f$ and $g$ are unbounded) but it is not clear that $|f+g|$ does not approach infinity. Any ideas?

A: By definition, a function $f$ has an essential singularity in $z_0$ if its Laurent's expansion in $z_0$ has infinite non-null negative terms, while the function $g$ has a pole, so its Laurent expansion has a finite number of non-null negative terms in $z_0$. It's now clear that the Laurent expansion of the sum has infinite non-null negative terms. (When I say "negative terms" I mean terms with negative exponent).


text:
Q: How do I use the edge version of Sunspot direct from Github instead of via Rubygems? In order to overcome a bug with solr, I need to run a newer version than the one included in the Rubygems version of Sunspot. I noticed on Github that there has been a very recent commit which includes a newer version of Solr.
How do I configure my Gemfile to pull straight from the repo instead of from RubyGems. Currently I have the following;
gem 'sunspot'
gem 'sunspot_rails'
gem 'sunspot_test'
gem 'sunspot_cell', :git => 'git://github.com/zheileman/sunspot_cell.git'

group :development, :test do
  gem 'sunspot_solr'
  gem 'progress_bar'
end

If I simply add the repo to the sunspot gem line, everything falls apart when I run bundle. As the sunspot_solr gem is within the sunspot repo, I don't know the line I should use to grab that from the repo.
Thanks,
Graeme

A: Got it! The answer is to point to the main repo on github and use require where appropriate to narrow it down to the relevant sub-section.
The edited Gemfile is as follows;
gem 'sunspot', :git => "git://github.com/sunspot/sunspot.git"
gem 'sunspot_rails', :git => "git://github.com/sunspot/sunspot.git", :require =>  "sunspot_rails"
gem 'sunspot_test'
gem 'sunspot_cell', :git => 'git://github.com/zheileman/sunspot_cell.git'

group :development, :test do
  gem 'sunspot_solr', :git => "git://github.com/sunspot/sunspot.git", :require => "sunspot_solr"
  gem 'progress_bar'
end

A: I am not a ruby developer, but here is a walkthrough on Installing Gems from Git that may be helpful.


text:
Q: UIStackView : Change UIStackView image width using storyboard The issue : Image take most of the stack and text shrinks
I tried to change content hugging priority but no changes !
How to do it in UIStackview using storyboard?
What I want the cell to look like Eventbright event Cell?

What I got is an image that take most of the cell?

A: Instead of Fill, change the Distribution of the UIStackView to Fill Proportionally and add constraints for the width of each element. Those constraints will serve as a guide to proportions on one element to each other and not as fixed sizes.

A: I tried it the following way.
The overall set up is given in pic:

At run time result is as given:

*

*First Stack view is fill proportionally

*imageview width is 1:4 of stackview width (control and drag from imageview to stackview and set equal width to 25% )

From control and drag select equal width. as shown

*

*stack view 2 is fill equally

*stack view 3 is fill equally

Hope it can help


text:
Q: search within array PHP I have an array which contains some data. for example ---
$data = array(

    'CATEGORY 1' => array(
        array('id'=> 0, 'name' => 'John', 'category' => 'CATEGORY1'),
        array('id'=> 1, 'name' => 'Jack', 'category' => 'CATEGORY1'),
        array('id'=> 2, 'name' => 'Jame', 'category' => 'CATEGORY1'),
    ),
    'CATEGORY 2' => array(
        array('id'=> 0, 'name' => 'Mile', 'category' => 'CATEGORY2'),
        array('id'=> 1, 'name' => 'Mike', 'category' => 'CATEGORY2'),
        array('id'=> 2, 'name' => 'Matt', 'category' => 'CATEGORY2'),
    )

);

Now how can i write a function like this ---
if ($post ='CATEGORY 1') {
// filter all the name where category => CATEGORY1
}

expected output --
'John', 'Jack', 'Jame';

i have tried like so ---
$filters = array
                (
                "id" => array
                    (
                    "filter" => FILTER_VALIDATE_INT,
                    "flags" => FILTER_FORCE_ARRAY,
                    "options" => array
                        (
                        "min_range" => 1,
                        "max_range" => 120
                    )
                ),
                "name" => array
                    (
                    "filter" => FILTER_CALLBACK,
                    "options" => "ucwords"
                ),
                "category" => array
                    (
                    "filter" => FILTER_CALLBACK,
                    "options" => "ucwords"
                )
            );

print_r(filter_var_array($data, $filters));

but that returns me null, how can i search within the array with the condition where category is category1 fetch all the names belongs to that ...
i know it can be a really dumb question, but people sometime get stuck on a really basic problem.
Hope someone knows the answer.

A: <?php
$data = array(

    'CATEGORY 1' => array(
        array('id'=> 0, 'name' => 'John', 'category' => 'CATEGORY1'),
        array('id'=> 1, 'name' => 'Jack', 'category' => 'CATEGORY1'),
        array('id'=> 2, 'name' => 'Jame', 'category' => 'CATEGORY1'),
    ),
    'CATEGORY 2' => array(
        array('id'=> 0, 'name' => 'Mile', 'category' => 'CATEGORY2'),
        array('id'=> 1, 'name' => 'Mike', 'category' => 'CATEGORY2'),
        array('id'=> 2, 'name' => 'Matt', 'category' => 'CATEGORY2'),
    )

);

$post = 'CATEGORY 1';
$pluck = 'name';

var_dump( array_reduce($data['CATEGORY 1'], function($result, $array) use ( $pluck ) {
    isset($array[$pluck]) && $result[] = $array[$pluck];
    return $result;
}, array()));

A: Simply use foreach like as
$result = [];
foreach($data as $value){
  foreach($value as $k => $v){
      if($v['category'] == 'CATEGORY1')
        $result[] = $v['name'];
  }
}
print_r($result);

Demo

A: Bellow code will help you out
<?php
$data = array(

    'CATEGORY 1' => array(
        array('id'=> 0, 'name' => 'John', 'category' => 'CATEGORY1'),
        array('id'=> 1, 'name' => 'Jack', 'category' => 'CATEGORY1'),
        array('id'=> 2, 'name' => 'Jame', 'category' => 'CATEGORY1'),
    ),
    'CATEGORY 2' => array(
        array('id'=> 0, 'name' => 'Mile', 'category' => 'CATEGORY2'),
        array('id'=> 1, 'name' => 'Mike', 'category' => 'CATEGORY2'),
        array('id'=> 2, 'name' => 'Matt', 'category' => 'CATEGORY2'),
    )

);

$post='CATEGORY 1';
$elements=$data[$post];
$names=array();
foreach ($elements as $ele) {
$names[]=$ele['name'];
}

print_r($names);

click here get realtime output


text:
Q: Multi-Language application with manual language choosing I have an app and in the first interface I need to choose one language.
I'm only using two lang.
And I want the text on the login to to be in that lang I choosed.
Should I use Localization?
This is my main.dart
    void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SplashScreen(),
      routes :{
        'lang' : (context) => Languagepage(),
        'fr_version' :(context) => LoginFormfrancais(),
        'ar_version' :(context) => LoginFormarabic(),

      },
    );
  }
 }

and this is the languages page where to choose: I only have two language:
  class _LanguagepageState extends State<Languagepage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color.fromARGB(255, 4, 24, 54),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Color.fromARGB(255, 228, 116, 42),
                  onPrimary: Color.fromARGB(255, 4, 24, 54),
                  shadowColor: Colors.greenAccent,
                  elevation: 3,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(32.0)),
                  minimumSize: Size(900, 100), //////// HERE
                ),
                onPressed: () {
                  Navigator.pushNamed(context, 'fr_version');
                },
                child: Text('FRANCAIS'),
              ),
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: Color.fromARGB(255, 228, 116, 42),
                  onPrimary: Color.fromARGB(255, 4, 24, 54),
                  shadowColor: Colors.greenAccent,
                  elevation: 3,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(32.0)),
                  minimumSize: Size(900, 100), //////// HERE
                ),
                onPressed: () {
                 Navigator.pushNamed(context, 'ar_version');
                },
                child: Text('العربية'),
              ),
            ])));
  }
}


text:
Q: null java.lang.AssertionError in InteliJ Ultimate plugin Android Support Build Succeeds but when i try to Generate Signed apk i got this error.
Exception in plugin Android Support.
with Error message null.
null
java.lang.AssertionError
    at org.jetbrains.android.exportSignedPackage.ExportSignedPackageWizard.createApk(ExportSignedPackageWizard.java:419)
    at org.jetbrains.android.exportSignedPackage.ExportSignedPackageWizard.createAndAlignApk(ExportSignedPackageWizard.java:368)
    at org.jetbrains.android.exportSignedPackage.ExportSignedPackageWizard.access$200(ExportSignedPackageWizard.java:76)
    at org.jetbrains.android.exportSignedPackage.ExportSignedPackageWizard$1$1.run(ExportSignedPackageWizard.java:150)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:726)
    at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:176)
    at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:556)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:501)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:66)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:163)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:137)
    at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:334)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

A: Solved After Updated SDK and Android Build tools

*

*Goto Android SDK Manager

*

*Check For Updates for packages

*Android SDK tools

*Android SDK Platform-tools

*Please Note that The Build-tools must be present and updated.
in my case i have build-tools with rev. 23.0.3

Also Make Sure You Have at least one SDK Platform Installed and Updated.

*

*In My case :


text:
Q: Convert data types from string to list (Coastal Buoy data) for DateListPlot I downloaded Coastal buoy data from the CDIP webpages and saved it as a text file. The trouble is that the data has spaces between the YYY MM DD hh mm.
{Edit 4/5/2019: Updated link  Please see comment below}
With FileNames and Import, I was able to import the data from a text file.
fn = FileNames["*.txt"]; (*I am interested in the first text file in this list*)
h2018 = Import[fn[[1]], "Data"]

What I want to do is convert the first 5 columns to DateList and then plot the 9th column against this new DateList.
I tried doing this to no effect because I am trying to convert the data to a string and then replacing spaces in the new string with / and then using DateList.
StringReplace[ToString[h2018[[3 ;;, 1 ;; 3]]], "," .. -> "/"];
StringReplace[%, " " -> ""];
dl=DateList[%];

How do I convert this string to a DateList and complete my plotting of column 9 in h2018 with the DateList, dl?
I did try to convert this string to a list of numbers using the information in this question but without success.
Flatten@ToExpression@StringSplit[%];

A: Here's one way to do it:
data = Import["http://www.ndbc.l.noaa.gov/data/realtime2/46218.txt",
              "Table", HeaderLines -> 2][[All, {1, 2, 3, 4, 5, 9}]];

ts = TimeSeries[Composition[Flatten, MapAt[DateObject, #, 1] &,
                            Reverse, TakeDrop[#, -1] &] /@ data];

DateListPlot[ts]

(If you don't want to convert to a TimeSeries[], you can omit that part.)

Since the other answer has already been accepted, let me just illustrate how one might use the functionality of Dataset[] for this task:
data = Import["http://www.ndbc.l.noaa.gov/data/realtime2/46218.txt", "Table"];
data = MapAt[StringReplace[#, "#" -> ""] &, Delete[data, 2], 1];
data = Dataset[AssociationThread[First[data], #] & /@ Rest[data]];

ds = <|"Timestamp" -> DateObject[{#YY, #MM, #DD, #hh, #mm}],
       "WaveHeight" -> Quantity[#WVHT, "Meters"]|> & /@ data

Show[ds[DateListPlot, All], FrameLabel -> {None, "Wave Height (m)"}]

A: Use the functions in the Date & Time guide to manipulate dates. This step-by-step answer.
Import the table.
raw = Import["http://www.ndbc.l.noaa.gov/data/realtime2/46218.txt", "Table"];

Notice that Mathematica has imported the numbers as numbers and not as strings.  Look at row 3 and columns from the start to column 5.
Head /@ raw[[3, ;; 5]]

{Integer, Integer, Integer, Integer, Integer}

First collapse the 5 column headers for the date-times in row 1 and 2.  This is not strictly needed but will keep the headers consistent with the data.
raw[[;; 2]] = Flatten@MapAt[StringJoin, 1]@TakeDrop[#, 5] & /@ raw[[;; 2]];

Next feed the values in the first 5 columns into DateObject.  The columns are in the exact order that DateObject expects so there is no need to adjust their positions. This is performed on row 3 until the end.
raw[[3 ;;]] = Flatten@MapAt[DateObject, 1]@TakeDrop[#, 5] & /@ raw[[3 ;;]];

Since the first 5 columns have been collapsed into 1 the information is now in column 5 instead of column 9, (9 - 5 + 1).  Take from row 3 until the end and columns 1 and 5 to plot with DateListPlot.
DateListPlot[raw[[3 ;;, {1, 5}]]]

Hope this helps.


text:
Q: Access VM shared folder via ssh (python parametiko) not working I have some trouble with parametiko...
Context : I am working on windows 10, and I have a virtual machine (ubuntu 20) installed using VMware.
On my windows, I have a folder "ubuntu_shared" that I have shared with my VM.
On my windows cmd line, if I run
ssh <user>@<host>
cd /mnt/hgfs/ubuntu_shared

it works fine.
But if I run with python the same process:
k = paramiko.RSAKey.from_private_key_file(LOCAL_SSH_PRIVATE_KEY)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

num_tries = 0
ssh_connected = False
while not ssh_connected and num_tries < 10:
    try:
        ssh.connect(hostname=VM_HOST, username=VM_USER, allow_agent=False, pkey=k)
        ssh_connected = True
        print(f"connected via ssh to {VM_USER}@{VM_HOST}")
    except Exception as e:
        print("still trying...")
        num_tries += 1
        time.sleep(1)
if not ssh_connected:
    ssh.close()
    raise Exception(f"failed to connect : {e}")

command = "cd /mnt/hgfs/ubuntu_shared"
stdin, stdout, stderr = ssh.exec_command(command)
if stderr:
    print(stderr.read().decode())

which outputs :
sh: line 0: cd: /mnt/hgfs/ubuntu_shared: Not a directory

What am I doing wrong on python ? doesn't seem like it's different is it ?
Thanks in advance :)

A: OK I actually found a way to fix the issue so I'll answer my own question if ever it can help someone.
It seem that when using paramiko I need to set the permissions to the wanted folder first.
Adding this once the ssh is connected fixed it for me :
sftp_client = ssh.open_sftp()
sftp_client.chmod(r"/mnt/hgfs/ubuntu_shared", 7700)


text:
Q: Kendo-UI Editor Placeholder I have some Editor boxes that I'd like to add placeholder text to.
<textarea rows="10" cols="20" data-bind="kendoEditor: {
      value: Text,
      attr: { placeholder: 'Test place holder' }}" >
 </textarea>

It looks like the placeholder text tag isn't passed through from the textarea to the editor.
Here's a sample editor box to play with: http://jsfiddle.net/cN2ke/
I think I'll have to listen for the Editor's change event, and if there's no text paste in my watermark HTML.
The problem I have with that is when the page's posted how to strip the watermark's back out. I guess I could do a string compare on the placeholder value but that seems kind of cheesy to me.
Thought I'd check and see if anyone has a good solution for water mark text in an editor control
Thanks!

A: Here's my implemented solution
Text area
<textarea id="custInfoPriorPerformance" rows="10" cols="20" data-bind="kendoEditor: { value: AccountPlanVM.AccountPlan.PriorYearSummary }" > </textarea>

In the View Model Create an options variable with the control's Id, observable, and placeholder text
self.PlaceholderOptions =
        {
            CustomerInfoAccountBackground: ['#custInfoAccountBackground', self.AccountPlanVM.AccountPlan.AccountBackground, "
" + 'Placeholder Example Text' + "
"]
        };

On load, I bind to the focus/blur of the editor box. And before posting the form back, I clear out placeholder text from the observables.
//Editor Placeholder methods
    self.BindEditorPlaceholders = function() {
        for (var propt in self.PlaceholderOptions) {
            //Options array
            var options = self.PlaceholderOptions[propt];

            // get a reference to the Editor
            var editor = $(options[0]).data("kendoEditor");

            //Currently saved value
            var currentValue = options[1]();

            //If we don't have any text saved, inject placeholder
            if (!currentValue) {
                editor.value(options[2]);
            }

            //Attach Events to Editor Iframe
            $(options[0]).siblings(".k-content").focus(options, self.EditorFocus);
            $(options[0]).siblings(".k-content").blur(options, self.EditorBlur);
        }
    };

    self.EditorFocus = function(e) {
        //Options array
        var options = e.data;

        // get a reference to the Editor
        var editor = $(options[0]).data("kendoEditor");

        //Current editor value
        var htmlValue = editor.value();

        if (htmlValue == options[2]) {
            //Clear editor value
            editor.value('');
        }
    };

    self.EditorBlur = function (e) {
        //Options array
        var options = e.data;

        // get a reference to the Editor
        var editor = $(options[0]).data("kendoEditor");

        //Current editor value
        var htmlValue = editor.value();

        if (htmlValue == '') {
            //Set editor value back to placeholder
            editor.value(options[2]);
        }
    };

    self.CleanEditorPlaceholders = function() {
        for (var propt in self.PlaceholderOptions) {
            //Options array
            var options = self.PlaceholderOptions[propt];

            // get a reference to the Editor
            var editor = $(options[0]).data("kendoEditor");

            //Currently saved value
            var currentValue = options[1]();

            //If the current text is the placeholder, wipe it out
            if (currentValue == options[2]) {
                options[1]('');
            }
        }
    };

A: @Andrew Walters: Thanks for your solution. I tried to implement the focus and blur event handlers on the .k-content sibling, under self.BindEditorPlaceholders, but the focus event did not fire for me using the Kendo 2014.1.624 (beta) release. So, I wanted to post an alternative (based on the Kendo Editor source code) for anyone else experiencing the same issue:
Under self.BindEditorPlaceholders, instead of:
$(options[0]).siblings(".k-content").focus(options, $scope.EditorFocus);
$(options[0]).siblings(".k-content").blur(options, self.EditorBlur);

one can try:
$(editor.body).on('focus.kendoEditor', options, $scope.EditorFocus);
$(editor.body).on('blur.kendoEditor', options, $scope.EditorBlur);

I'm not saying it's the better of the two methods, and it may or may not be better to avoid relying upon the sibling position of the .k-content DOM element, for future Kendo releases. But, it works.


text:
Q: Spring batch and quartz running job status I am using spring batch 3.0.2 and quartz 2.2.1 . Both using their meta tables as provided by both API. Spring batch job is scheduled by quartz and invoking on scheduled time. There is all information in both Quartz and Spring batch tables.
Now I would like to get the job running status which is schedules by quartz. I am not able to figure out , how can I relate quartz job key with spring batch. So that I can find the running status spring batch job scheduled by quartz system.
Can someone please help me on this? I can provide if there is any other information required.

A: You can use jwatch api and parse the JSON response as per requirements on JSP page.
https://code.google.com/archive/p/jwatch/wikis/RESTfulAPI.wiki


text:
Q: Java: Using type punning on primitive arrays? I need to be able to convert byte arrays to/from other primitive type arrays, but instead of casting, I need type punning. Correct term for raw copy without casting?
I thought it would be possible to do the following:
// idea: byte[12] -> int[3], and int[3] -> byte[12]

int[] ints;

ByteBuffer bb = ByteBuffer.wrap(
    new byte[]{ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3 });
IntBuffer ib = bb.asIntBuffer();

ints = ib.array(); // java.lang.UnsupportedOperationException
ints = ib.duplicate().array(); // java.lang.UnsupportedOperationException

Unfortunately, it seems that bb.asIntBuffer() is not creating a new IntBuffer by copying the content "bitwise" or "raw", but creates a new "view" on existing ByteBuffer. That's why .array() is intended to fail.
I browsed around in JDK's sources, and found few classes, which are used by all these buffer classes and would do the stuff I need, but are internal (such as the class Unsafe).
While I think that my goal could be achieved by wrapping the byte buffer in some ObjectInputStream and read the primitive values by .readInt(), I think it would be a messy and slow workaround.
So, are there any other solutions possible without doing magical primitive type arithmetics (shifting, checking endians, ...)?
NOTE: I need both directions: byte[12] -> int[3], and int[3] -> byte[12]

A: According to the javadoc, array() [1] returns the buffer's backing array which is the array you specify with the call to wrap() [2].
Hence, you must create a new array with the desired type. But the arithmetics can still be handled via the Buffer classes.
ByteBuffer bb = ByteBuffer.wrap(new byte[]{ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3 });
IntBuffer ib = bb.asIntBuffer();

int[] intArray = new int[ib.limit()];
ib.get(intArray);

Backwards requires a little bit of calculation by yourself.
ByteBuffer newBb = ByteBuffer.allocate(intArray.length*4);
newBb.asIntBuffer().put(intArray);
byte[] byteArray = newBb.array();

See:
[1] http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html#array%28%29
[2] http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html#wrap%28byte[]%29

A: Many thanks to wierob for his code for converting byte[]->int[] !
I played around a bit to get the opposite direction working.
1) API
// byte[] -> int[]
public static int[] punnedToInteger(byte[] in){
    ByteBuffer bb = ByteBuffer.wrap(in);
    IntBuffer pb = bb.asIntBuffer();

    int[] out = new int[pb.limit()];
    pb.get(out);

    return out;
}

// int[] -> byte[]
public static byte[] punnedFromInteger(int[] in){
    byte[] out = new byte[in.length * Integer.SIZE / Byte.SIZE];
    ByteBuffer bb = ByteBuffer.wrap(out);

    for(int i=0; i<in.length; ++i){
        bb.putInt(in[i]);
    }

    return out;
}

2) Test case
{
    byte[] bytes = new byte[]{ 0,0,0,1, 0,0,1,0, 0,1,0,0, 1,0,0,0 };
    int[] ints = punnedToInteger(bytes);
    System.out.println(Arrays.toString(bytes));
    System.out.println(Arrays.toString(ints));
    System.out.println();
}
{
    int[] ints = new int[]{ 1, 256, 65536, 16777216 };
    byte[] bytes = punnedFromInteger(ints);
    System.out.println(Arrays.toString(ints));
    System.out.println(Arrays.toString(bytes));
    System.out.println();
}

3) Output
[0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]
[1, 256, 65536, 16777216]

[1, 256, 65536, 16777216]
[0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]


text:
Q: Creating Imagebutton programmatically I want to create several ImageButtons programmatically. I am able to create them but the click event listener keeps receiving the same view (Button 2), whether I click on button 0 ,button1 or button 2.
    RelativeLayout gameBoard = (RelativeLayout) findViewById(R.id.RelGameboard);

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);

    for(int i = 0 ; i <  3 ; i++)
    {

        ImageButton btnGreen = new ImageButton(this);
        btnGreen.setImageResource(R.drawable.bola_verde);
        btnGreen.setLayoutParams(lp);
        btnGreen.setOnClickListener(mGreenBallOnClickListener);
        btnGreen.setBackgroundColor(Color.TRANSPARENT);
        btnGreen.setTag(i);
        btnGreen.setId(i);

                    gameBoard.addView(btnGreen);

     }'

Click event listener:
private View.OnClickListener mGreenBallOnClickListener = new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        //check which green ball was clicked
        ImageButton imgBtn = (ImageButton) v;

    Log.i("greeny","Clicked on green ball->"+imgBtn.getTag()+" v.ID->"+v.getId());
    }
};

For any imagebutton drawn, when I click I get :  Clicked on green ball->2 v.ID->2
The buttons are in different positions ( i set a different padding for each one of them but in order to simplify the code I didn't put it here )

A: Try adding a onClickListener -
private View.OnClickListener ClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int selected_item = (Integer) v.getTag();
    }
};

EDIT
Try creating a array of ImageButtons -
ImageButton[] btnGreen = new ImageButton[3];

for (int i = 0; i < 3; i++) {
    btnGreen[i] = new ImageButton(this);
    btnGreen[i].setImageResource(R.drawable.bola_verde);
    btnGreen[i].setLayoutParams(lp);
    btnGreen[i].setOnClickListener(ClickListener);
    btnGreen[i].setBackgroundColor(Color.TRANSPARENT);
    btnGreen[i].setTag(i);
    btnGreen[i].setId(i);

    gameBoard.addView(btnGreen[i]);
}

A: This happen because you do not set layout of button, All button in same place.
Use Aboveof,Belowof,left,right,center

Example
params.addRule(RelativeLayout.ALIGN_PARENT_ABOVE);
    relativeLayout.addView(button, params);

A: Try this code:
RelativeLayout gameBoard = (RelativeLayout)findViewById(R.id.RelGameboard);

ImageButton[] imageButtons;

private final int NUMBER_OF_IMAGE_BUTTONS = 5; //your number of image buttons

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);

imageButtons = new ImageButton[NUMBER_OF_IMAGE_BUTTONS];

for(int i = 0 ; i < NUMBER_OF_IMAGE_BUTTONS; i++){
   imageButtons[i] = new ImageButton(this);
   imageButtons[i].setImageResource(R.drawable.bola_verde);
   imageButtons[i].setLayoutParams(lp);
   imageButtons[i].setOnClickListener(mGreenBallOnClickListener);
   imageButtons[i].setBackgroundColor(Color.TRANSPARENT);
   imageButtons[i].setTag(i);
   imageButtons[i].setId(i);
   gameBoard.addView(imageButtons[i]);
}