text:
Q: Notification service not working after clicking notification message in status bar I referred following links to study the demo example on Notification service in Android : Sai Geetha Blog and Vogella Tutorial.
Both worked but partially i.e. I've downloaded both projects as it is and executed them. Both has button to initiate the notification. On Button Click notification appears at the top status bar.
Here comes the problem, on click of that notification, neither any message is getting displayed nor intent is getting fired to navigate to new activity.
I'm new to this concept so any help appreciated...
EDIT
CreateNotification .class
public class CreateNotification extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void createNotification(View view) {
        NotificationManager nm= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        final int UNIQUE_ID = 123458;
        Intent navigationIntent = new Intent();
        navigationIntent.setClass(CreateNotification.this,
                NotificationReceiver.class);

        PendingIntent pi = PendingIntent.getActivity(this, 0, navigationIntent,
                0);
        String body = "New Notification added!!!";
        String title = "Title";
        Notification n = new Notification(R.drawable.ic_launcher, body,
                System.currentTimeMillis());
        n.number = 2;
        n.setLatestEventInfo(this, title, body, pi);
        n.defaults = Notification.DEFAULT_ALL;
        nm.notify(UNIQUE_ID, n);
    }
}

NotificationReceiver.class
public class NotificationReceiver extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        Log.i("Receiver", "NotificationReceiver");
    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:onClick="createNotification"
        android:text="Create Notification" >
    </Button>

</LinearLayout>

result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is the result activity opened from the notification" >
    </TextView>

</LinearLayout>

A: check this out
   public static NotificationManager nm;
public static final int UNIQUE_ID = 123458;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newone);
    createNotification();

}
public void createNotification() {
    NotificationManager nm= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final int UNIQUE_ID = 123458;
    Intent navigationIntent = new Intent();
    navigationIntent.setClass(NEWAct.this,
            TestActivity.class);
    navigationIntent.putExtra("selected_tab", "more");

    PendingIntent pi = PendingIntent.getActivity(this, 0, navigationIntent,
            0);
    String body = "New Notification added!!!";
    String title = "Title";
    Notification n = new Notification(R.drawable.ic_launcher, body,
            System.currentTimeMillis());
    n.number = 2;
    n.setLatestEventInfo(this, title, body, pi);
    n.defaults = Notification.DEFAULT_ALL;
    nm.notify(UNIQUE_ID, n);
}

after your activity launched, you must cancel that notification using the id(UNIQUE_ID)
              try {
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.cancel(UNIQUE_ID);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


text:
Q: Como obter dados do pedido do usuário no banco Firebase? Tenho um app Android em Kotlin que faz pedido delivery de pizza onde a empresa recebe os dados do pedido do usuário e quero que o usuário também receba os dados do pedido que ele fez, há algum tempo tento e não acho a solução. Segue método deve recuperar dados do pedido na classe de ver pedidos:
   private fun recuperarDados() {

        dialog = SpotsDialog.Builder()
            .setContext(this)
            .setMessage("Aguarde")
            .setCancelable(false)
            .build()
        dialog!!.show()

        val pedidoRef = idEmpresa?.let {
            idUsuarioLogado?.let { it1 ->
                firebaseRef
                    ?.child("pedidos_usuario")
                    ?.child("itens")

            }
        }

        val pedidoPesquisa = pedidoRef?.child("status")?.equalTo("confirmado")

        pedidoPesquisa?.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {

                pedidos.clear()
                if (dataSnapshot.value != null) {
                    for (ds in dataSnapshot.children) {
                        val pedido = ds.getValue(ItemPedido::class.java)
                        itemPedidos.add(pedido!!)

                    }
                    adapterPedido!!.notifyDataSetChanged()
                    dialog!!.dismiss()

                }

            }

            override fun onCancelled(databaseError: DatabaseError) {

            }
        })

    }

A: Eu faria a estrutura da base desta maneira

Para filtrar pelo lado da empresa os pedidos

val pedidoPesquisa = mFirebaseDatabaseReference.child("pedidos")
            .orderByChild("idempresa")
            .equalTo(1);//seu id da empresa

Para filtrar pelo lado do usuario os pedidos

   val pedidoPesquisa =  mFirebaseDatabaseReference.child("pedidos")
            .orderByChild("idusuario")
            .equalTo(1);//seu id de usuario

Para executar a busca

   pedidoPesquisa?.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {

            if (dataSnapshot.value != null) {
                for (ds in dataSnapshot.children) {
                    val pedido = ds.getValue(ItemPedido::class.java)
                    itemPedidos.add(pedido!!)

                }
                adapterPedido!!.notifyDataSetChanged()

            }

        }

        override fun onCancelled(databaseError: DatabaseError) {

        }
    })

redpajama_set_name: RedPajamaStackExchange


text:
Q: Checkbox Html Java Script I need to reload a page when a checkbook is clicked.
If the checkbox was unchecked before clicking then it should be checked after the page reloads.
If the checkbox was checked then after clicking the page should reload and the checkbox should be unchecked.
Moreover, I need to pull the information (if is checked or unchecked) from the checkbox to change my page accordingly.
How can I reload the page and pass this values changing this function? I am complete noob so please try to stay simple. Ty.
      echo '<input id="check_mostra_email" type="checkbox" value="mostra_email" onclick="reloadPage()"/>';

      echo '<script type="text/javascript">
        <!--
           function reloadPage()
           {
              if(document.getElementById("check_mostra_email").checked === true){
                document.forms["RelatorioGerencialCarteiras007"].submit();
                }

              else{
                document.forms["RelatorioGerencialCarteiras007"].submit();
                }
           }
        //-->
     </script>';

A: Why aren't you using PHP for this?
In your case after your reload you have a $_POST or $_GET variable which shows you if the checkbox was checked or not.


text:
Q: I want to make mongoose as follows Please help me with mongodb query in nodejs.
I want a query which give me email of person by finding by it ID.
const user=await User.findById(req.params.id).select('email');
I have tried this

A: In order to achieve what you're trying to do you have to query like this:
const user = await User.findById(req.params.id, { email: true })

The second object is the projection, that is the fields you want to return from the collection, in this case will only return the email, but you can do either:
const user = await User.findById(req.params.id, { email: true, _id: true })

Or even exclude fields:
const user = await User.findById(req.params.id, { email: false })


text:
Q: Getting started with hammer.js on Meteor.js I am having trouble enabling touch events with Meteor. I installed chriswessels:hammerpackage but for some reason it's not working. I am probably missing something very simple. Do I need to somehow initialize it?
When I simply add
Template.showProduct.gestures({
 'swipe': function(e, t) {
    e.preventDefault();
    console.log("HAMMERTIME!");
  }
});

Nothing happens. Here is a code sample http://meteorpad.com/pad/ZStmQwaPfP9LNDX2v/Hammertime
I changed
Template.player.events({
  'click': function () {
    Session.set("selectedPlayer", this._id);
  }
});

to
Template.player.events({
  'tap': function () {
    Session.set("selectedPlayer", this._id);
  }
});

Shouldn't that work?

A: Welly you are missing the CSS Selector.

The object keys should follow the format gestureName cssSelector and
  the value should be a callback function that is executed when the
  specified gesture is performed on the element(s) matching the CSS
  selector.

So change the code to this.
Template.showProduct.gestures({
 'swipe .myItem': function(e, t) {
    e.preventDefault();
    console.log("HAMMERTIME!");
  }
});

Where myItem should be a panel or whatever you want to swipe.


text:
Q: Device volume control buttons doesn't set ear speaker volume with audio attribute usage USAGE_VOICE_COMMUNICATION When playing audio file, I switch the sound from the external speaker to the internal one (ear speaker). The audio is played through SimpleExoPlayer. Switching occurs by the USAGE_VOICE_COMMUNICATION attribute. The sound starts playing through the earpiece, but the volume of this sound is not controlled by the system volume buttons, the volume of the media in the system changes.
I tried setting setContentType as CONTENT_TYPE_SPEECH, the problem remains.
The problem recurs on Google Pixel XL (Android 10), One Plus 7t (Android 10).
But not repeated on Samsung Galaxy S9 (Android 10).
What is the right way to make such a switch so that the volume of the correct speaker changes?
Here is my attributes:
private fun setupAttributesWithExternalSpeaker() {
    val audioAttributes = AudioAttributes.Builder()
            .setContentType(C.CONTENT_TYPE_MUSIC)
            .setUsage(C.USAGE_MEDIA)
            .build()

    simpleExoPlayer.setAudioAttributes(audioAttributes, true)
}

private fun setupAttributesWithInternalSpeaker() {
    val audioAttributes = AudioAttributes.Builder()
            .setContentType(C.CONTENT_TYPE_MUSIC)
            .setUsage(C.USAGE_VOICE_COMMUNICATION)
            .build()

    simpleExoPlayer.setAudioAttributes(audioAttributes, false)
}

Full player class here

A: How about using AudioManager.setMode
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);


text:
Q: How to Get the amount of disk space available of a UNC path(WITH WHITESPACES) in Java I am trying to use org.apache.commons.io.FileSystemUtils.freeSpaceKb(String path) in Java to get the free space of a UNC path that has white spaces. The problem is that this function does not work properly when there are white spaces.
Say there is a computer in the network called John-PC. John has a shared folder that has white spaces, and we want to store something on that folder. But first, we want to make sure that he has enough space on his local drive. So we use freeSpaceKb(String path) to get the free space available. If the path was like this it would have worked:
\\\john-pc\data\abc
But if we have white spaces in the path it does not work anymore.
\\\john-pc\data\abc def
I would really appreciate it if anyone would give me a good way of doing this.

A: Try to add quotes around the folder with whitespace. I haven't tried it but it might help.
\\john-pc\data\\"abc def\"

A: Most probably there is a bug with Commons-io-1.4.jar. Upgrading to Commons-io-2.4.jar will do the trick.
I'm still wondering if there is a way to use 1.4. Upgrading to 2.4 may cause some unknown issues. Any thoughts?


text:
Q: WinUAE telnet from serial.device I want to "call" a telnet BBS from my NComm running on WinUAE. Have someone achieved this and if so - how ?

A: Install telser and tell NComm to use telser.device as its serial

*

*http://aminet.net/package/comm/tcp/telser140

*http://aminet.net/package/comm/tcp/Telser_Keyfile
NComm can then be used to telnet out using modem-style AT commands.
atd server.com


text:
Q: Detect when data changed Here is my data structure :
name          value          date_received
foo           100            2013-09-19 10:00:00
bar           200            2013-09-19 10:00:00
foo           100            2013-09-19 10:05:00  //no change
bar           200            2013-09-19 10:05:00  //no change
foo           110            2013-09-19 10:08:00  // foo changed
bar           200            2013-09-19 10:08:00  // no change
......

Question:
I want a query (mysql) which can do something like:
select date_received where anyOf(foo, bar) changed from the previous
specified value in the past N hours.

There could be other names in the table but we are only interested in foo and bar.
Any pointers. To me it looks like we'll need a self join - but don't know how.
EDIT: looks like the below query is just a good starting point.
select date_received from (SELECT DISTINCT name, value from data) a
  INNER JOIN (select DISTINCT name, value, date_received from data)b
    on (a.name=b.name and a.value=b.value)

update Looks like below query works - easier than I thought it would be.
SELECT DISTINCT a.tr FROM (
   SELECT name, value, MAX(date_received) dr from data
    where date_received > now() - INTERVAL 2 hour
    GROUP BY name, value order by dr desc)a;

A: I do not see how your edited query solves the problem.  Where does the "last N hours" come in, for instance?
I would approach this by looking at the previous value, then using logic around the datetime constraints and value changes to see if there has been a change.  Your question is ambiguous:  Are you looking for changes only in the last N hours?  Are you looking for a change from the last value before N hours?  What happens if the value changes back?
All of these, though, could be answered by having the previous value and previous time on each row.  Here is an example of how to get this:
select t.*,
       (select t.date_received
        from t t2
        where t2.date_received < t.date_received and
              t2.name = t.name
        order by t2.date_received desc
        limit 1
       ) as prev_date_received,
       (select t.value
        from t t2
        where t2.date_received < t.date_received and
              t2.name = t.name
        order by t2.date_received desc
        limit 1
       ) as prev_value
from t
having <your logic goes here for the date time and changes you care about>;

This is using the having clause instead of a subquery, just out of convenience (this is not supported by other databases).
For instance, if you want any changes in the last N hours:
having date_received > now() - interval N hour and prev_value <> value


text:
Q: Repacking RDS database with pg_repack isn't online While running pg_repack on a RDS Postgresql 9.6.3, got this failure for one of writers:
ProgrammingError: permission denied for relation log_24034858
CONTEXT:  SQL statement "INSERT INTO repack.log_24034858(pk, row)
VALUES(CASE WHEN $1 IS NULL THEN NULL ELSE (ROW($1.id)::repack.pk_24034858) END, $2)"

But pg_repack should allow writes to repacked tables, why did it fail here?

A: We found a similar issue. The issue appears to be that log tables created in the repack schema don't have the correct permissions. Our solution was to use ALTER DEFAULT PRIVALEGES to fix this:
CREATE EXTENSION pg_repack;
ALTER DEFAULT PRIVILEGES IN SCHEMA repack GRANT INSERT ON TABLES TO PUBLIC;
ALTER DEFAULT PRIVILEGES IN SCHEMA repack GRANT USAGE, SELECT ON SEQUENCES TO PUBLIC;

A: According to Amazon you have to create pg_repack extension from your superuser account. But the extension is created with rds_superuser role instead. And all other objects are created with that role as owner, for example:
=> \dnS+ repack                                                                                │
                     List of schemas                                                                    │ subsidy | birth_month | birth_year
  Name  |     Owner     | Access privileges | Description                                               │---------+-------------+------------
--------+---------------+-------------------+-------------                                              │       1 |           7 |       1952
 repack | rds_superuser |                   |                                                           │       1 |           7 |       1952
(1 row)

You shouldn't change owner of schema. And you probably don't want to REASSIGN OWNED .... It is sufficient to change owner for each function in repack namespace to fix permission problems:
create extension pg_repack;
ALTER FUNCTION repack.version() OWNER TO postgres;
ALTER FUNCTION repack.version_sql() OWNER TO postgres;
ALTER FUNCTION repack.array_accum(anyelement) OWNER TO postgres;
ALTER FUNCTION repack.oid2text(oid) OWNER TO postgres;
ALTER FUNCTION repack.get_index_columns(oid,text) OWNER TO postgres;
ALTER FUNCTION repack.get_order_by(oid,oid) OWNER TO postgres;
ALTER FUNCTION repack.get_create_index_type(oid,name) OWNER TO postgres;
ALTER FUNCTION repack.get_create_trigger(oid,oid) OWNER TO postgres;
ALTER FUNCTION repack.get_enable_trigger(oid) OWNER TO postgres;
ALTER FUNCTION repack.get_assign(oid,text) OWNER TO postgres;
ALTER FUNCTION repack.get_compare_pkey(oid,text) OWNER TO postgres;
ALTER FUNCTION repack.get_columns_for_create_as(oid) OWNER TO postgres;
ALTER FUNCTION repack.get_drop_columns(oid,text) OWNER TO postgres;
ALTER FUNCTION repack.get_storage_param(oid) OWNER TO postgres;
ALTER FUNCTION repack.get_alter_col_storage(oid) OWNER TO postgres;
ALTER FUNCTION repack.repack_indexdef(oid,oid,name,boolean) OWNER TO postgres;
ALTER FUNCTION repack.repack_trigger() OWNER TO postgres;
ALTER FUNCTION repack.conflicted_triggers(oid) OWNER TO postgres;
ALTER FUNCTION repack.disable_autovacuum(regclass) OWNER TO postgres;
ALTER FUNCTION repack.repack_apply(cstring,cstring,cstring,cstring,cstring,integer) OWNER TO postgres;
ALTER FUNCTION repack.repack_swap(oid) OWNER TO postgres;
ALTER FUNCTION repack.repack_drop(oid,integer) OWNER TO postgres;
ALTER FUNCTION repack.repack_index_swap(oid) OWNER TO postgres;
ALTER FUNCTION repack.get_table_and_inheritors(regclass) OWNER TO postgres;


text:
Q: ASPxGridView - "Procedure or function 'deletetable' expects parameter '@id', which was not supplied." I'm using devexpress and i have two problems.
My insert stored procedure work fine.
I specified the ASPxGridView.KeyFieldName property.

*

*problem is with the delete stored procedure. I get the error Procedure or function 'delete' expects parameter '@id', which was not supplied.

*The second problem is with the update stored procedure. I get the error Procedure or function updatetable has too many arguments specified.
My Source Code:
// Sql script
USE [Data]
GO
/****** Object: StoredProcedure [dbo].[deletetable] Script Date: 06/12/2012
17:11:07   ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery3.sql|0|0|C:\Users\Ali\
AppData\Local\Temp\~vsBA26.sql
ALTER procedure [dbo].[deletetable]
@id int
as
delete from Tablo where id= @id

USE [Data]
GO
/****** Object: StoredProcedure [dbo].[updatetable] Script Date: 06/12/2012
17:13:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Batch submitted through debugger: SQLQuery5.sql|0|0|C:\Users\Ali
\Desktop\SQLQuery5.sql
ALTER procedure [dbo].[updatetablo]
@name VARCHAR(50),
@surname VARCHAR(50),
@job VARCHAR(50),
@age INT,
@id INT

as
UPDATE Table
set name= @name, surname= @surname, job= @job, age= @age
where (id= @id)

//.Aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="devexpresskullanimi.aspx.cs"
Inherits="veritabani_uygulamasi.devexpresskullanimi" %>

<%@ Register assembly="DevExpress.Web.ASPxGridView.v10.2, Version=10.2.5.0,
Culture=neutral, PublicKeyToken=b88d1754d700e49a"
namespace="DevExpress.Web.ASPxGridView" tagprefix="dx" %>
<%@ Register assembly="DevExpress.Web.ASPxEditors.v10.2,
Version=10.2.5.0, Culture=neutral,
PublicKeyToken=b88d1754d700e49a"
namespace="DevExpress.Web.ASPxEditors" tagprefix="dx" %>

<!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">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>

<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False"
ClientIDMode="AutoID" CssFilePath="~/App_Themes/DevEx/{0}/styles.css"
CssPostfix="DevEx" DataSourceID="SqlDataSource1" Width="277px"
KeyFieldName="id">
<Columns>
<dx:GridViewCommandColumn ShowSelectCheckbox="True" VisibleIndex="0">
<EditButton Visible="True">
</EditButton>
<NewButton Visible="True">
</NewButton>
<DeleteButton Visible="True">
</DeleteButton>
</dx:GridViewCommandColumn>
<dx:GridViewDataTextColumn FieldName="name" VisibleIndex="0">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="surname" VisibleIndex="1">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="job" VisibleIndex="2">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="age" VisibleIndex="3">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn FieldName="id" VisibleIndex="4">
</dx:GridViewDataTextColumn>
</Columns>
<Settings ShowFilterRow="True" />
<Images SpriteCssFilePath="~/App_Themes/DevEx/{0}/sprite.css">
<LoadingPanelOnStatusBar Url="~/App_Themes/DevEx/GridView/StatusBarLoading.gif">
</LoadingPanelOnStatusBar>
<LoadingPanel Url="~/App_Themes/DevEx/GridView/Loading.gif">
</LoadingPanel>
</Images>
<ImagesFilterControl>
<LoadingPanel Url="~/App_Themes/DevEx/GridView/Loading.gif">
</LoadingPanel>
</ImagesFilterControl>
<Styles CssFilePath="~/App_Themes/DevEx/{0}/styles.css" CssPostfix="DevEx">
<Header ImageSpacing="5px" SortingImageSpacing="5px">
</Header>
<LoadingPanel ImageSpacing="5px">
</LoadingPanel>
</Styles>
<StylesEditors ButtonEditCellSpacing="0">
<ProgressBar Height="21px">
</ProgressBar>
</StylesEditors>
</dx:ASPxGridView>
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NetConnectionString %>"
SelectCommand="selecttablo" DeleteCommand="deletetable"
DeleteCommandType="StoredProcedure" InsertCommand="inserttable"
InsertCommandType="StoredProcedure" OldValuesParameterFormatString=""
SelectCommandType="StoredProcedure" UpdateCommand="updatetable"
UpdateCommandType="StoredProcedure">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="surname" Type="String" />
<asp:Parameter Name="job" Type="String" />
<asp:Parameter Name="age" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="surname" Type="String" />
<asp:Parameter Name="job" Type="String" />
<asp:Parameter Name="age" Type="Int32" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</form>
</body>

Can anyone see what the problem might be or give me a hint on how to resolve this?

A: If you have spesified DataKeyNames then don't use
<asp:Parameter...>

Instead try using:
<asp:ControlParameter Name="ID" ControlID="YourGridViewName" PropertyName="SelectedDataKey.Value" />

And if you want to use asp:parameter.../ then you should use deleting, inserting or selecting events of SqlDataSource and implement folowing:
protected void yourDataSource_deleting(object sender, ObjectDataSourceMethodEventArgs e)
{
     e.InputParameters["yourParameterName"] = value;
}


text:
Q: Validate if RSA key matches X.509 certificate in Java I have a RSA Key and a X.509 Certificate which I use for SSL connections.
The key and certificate are stored in files in PEM format (generated by OpenSSL) and used in an Apache HTTP server environment.
Is there an easy way to validate if the key matches the certificate using only Java code (without executing the openssl binary and parsing the output), for example by using Java security and/or Bouncycastle library methods?

A: The following code compares the SHA-1 over the modulus within the public and private key. The modulus should be unique for each pair (unless you key pair generation mechanism or random generator is broken of course).
Note that the following code requires the key to be in unencrypted PKCS#8 format. It may be better to use PKCS#12 instead and load the binary PKCS#12 file in a KeyStore (providing the password).
openssl pkcs8 -topk8 -in key.pem -out keypk8.pem -nocrypt

And finally the Java code:
import static org.bouncycastle.util.encoders.Hex.toHexString;

import java.io.ByteArrayInputStream;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

public class CompareCertAndKey {

    /**
     * Checks if the certificate and RSA private key match.
     *
     * @param args the path to the certificate file in args[0] and that of the private key in args[1]
     */
    public static void main(String[] args) {
        try {
            final PemReader certReader = new PemReader(new FileReader(args[0]));
            final PemObject certAsPemObject = certReader.readPemObject();
            if (!certAsPemObject.getType().equalsIgnoreCase("CERTIFICATE")) {
                throw new IllegalArgumentException("Certificate file does not contain a certificate but a " + certAsPemObject.getType());
            }
            final byte[] x509Data = certAsPemObject.getContent();
            final CertificateFactory fact = CertificateFactory.getInstance("X509");
            final Certificate cert = fact.generateCertificate(new ByteArrayInputStream(x509Data));
            if (!(cert instanceof X509Certificate)) {
                throw new IllegalArgumentException("Certificate file does not contain an X509 certificate");
            }

            final PublicKey publicKey = cert.getPublicKey();
            if (!(publicKey instanceof RSAPublicKey)) {
                throw new IllegalArgumentException("Certificate file does not contain an RSA public key but a " + publicKey.getClass().getName());
            }

            final RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
            final byte[] certModulusData = rsaPublicKey.getModulus().toByteArray();

            final MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            final byte[] certID = sha1.digest(certModulusData);
            final String certIDinHex = toHexString(certID);

            final PemReader keyReader = new PemReader(new FileReader(args[1]));
            final PemObject keyAsPemObject = keyReader.readPemObject();
            if (!keyAsPemObject.getType().equalsIgnoreCase("PRIVATE KEY")) {
                throw new IllegalArgumentException("Key file does not contain a private key but a " + keyAsPemObject.getType());
            }

            final byte[] privateKeyData = keyAsPemObject.getContent();
            final KeyFactory keyFact = KeyFactory.getInstance("RSA");
            final KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyData);
            final PrivateKey privateKey = keyFact.generatePrivate(keySpec);
            if (!(privateKey instanceof RSAPrivateKey)) {
                throw new IllegalArgumentException("Key file does not contain an X509 encoded private key");
            }
            final RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
            final byte[] keyModulusData = rsaPrivateKey.getModulus().toByteArray();
            final byte[] keyID = sha1.digest(keyModulusData);
            final String keyIDinHex = toHexString(keyID);

            System.out.println(args[0] + " : " + certIDinHex);
            System.out.println(args[1] + " : " + keyIDinHex);
            if (certIDinHex.equalsIgnoreCase(keyIDinHex)) {
                System.out.println("Match");
                System.exit(0);
            } else {
                System.out.println("No match");
                System.exit(-1);
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(-2);
        }
    }
}

A: Thank you very much for the above code snippet. Its working for me with bouncycastle version 1.51
<bcprov-jdk15on-version>1.51</bcprov-jdk15on-version>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>${bcprov-jdk15on-version}</version>
</dependency>

Many Thanks for your code snippet.


text:
Q: Internet Explorer blocked this site from downloading files How to avoid this message in IE:

"To help protect your security,
  Internet Explorer blocked this site
  from downloading files to your
  computer. Click here for options"

This message occurs while an executable file is downloaded like a link format (http://www.example.com/demo.exe) from Google Mail. It should work without disturbing any changes in IE settings. But while you download the EXE file in new tab it is Working. On direct clicking, it is showing the above mentioned message.
How to solve this problem?

A: Go to tools->internet options->advance, and there you have a series of options you can select or not. Select all that are related to download files, and deselect the ones that restrict them. That should do it.
Another thing you can do is turn of the firewall, but this is not very recommendable.


text:
Q: How do you compare the time portion of a time string? I have in my preferences some strings that represent a start time and and ending time.
I wrote this function to determine if the current time is within the start and ending time. The format of the date strings is "HH:mm". The function takes the strings that are from the preferences.
I'm sure I'm missing some code for the comparing because my parsing returns a something like this:
Thu Sep 29 12:24:33 EDT 2011
But all I need is to get this:
12:24
Here is the function. Can you help me correct the coding?
Thanks.
Truly,
Emad
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
        String endTime) {

    String pattern = "HH:mm";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    boolean booleanValueToReturn = false;

    try {
        Date startTimeToCompare = sdf.parse(startTime);
        Date endTimeToCompare = sdf.parse(endTime);

        /*
         * These are for the current time in date format.
         */
        Date currentTime = new Date(System.currentTimeMillis());

        Log.w("Emad", "Current Time: " + currentTime + "   Start Time is: "
                + startTimeToCompare + "   End Time is : "
                + endTimeToCompare);

        /*
         * Check if current time is equal or greater than the start time.
         */
        if (currentTime.compareTo(startTimeToCompare) == 0
                || currentTime.compareTo(startTimeToCompare) == 1) {

             booleanValueToReturn = true;

            /*
             * Now check if the current time is equal or less than the end
             * time.
             */
            if (currentTime.compareTo(endTimeToCompare) == 0
                    || currentTime.compareTo(endTimeToCompare) == -1) {

                booleanValueToReturn = true;
            } else {
                 booleanValueToReturn = false;
            }
        } else {
             booleanValueToReturn = false;
        }

    } catch (java.text.ParseException e) {
    }

    return booleanValueToReturn;

A: You are using SimpleDateFormat Incorrectly.
String pattern = "HH:mm" should be format in which your input Date String is. otherwise how is SimpleDateFormat going to know which portion represents what.
Create two SimpleDateFormat, f1 (with Input String Format)  and f2 ( with output String Format) ;
Use f1.parse() to get Date object for Input String.
Then use f2.format() on this Date Object to get Output String representation.
Refer to SimpleDateFormat for details on how to specify date Format.
public static boolean currentTimeIsWithinStartAndEnd(String startTime,
        String endTime) {

           // assuming input date string is of format MM/dd/yyyy. Change it according to your needs.

            String inputPattern = "MM/dd/yyyy";
            String outputPattern = "HH:mm";
            SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern);
            SimpleDateFormat outputFormatter = new SimpleDateFormat(outputPattern);

            Date startTimeToCompare = inputFormatter.parse(startTime);
            String dateInRequiredFormat = outputFormat.format(startTimeToCompare);


text:
Q: Using trigger to check conditional uniqueness (MySQL) I have a MySQL table, that has a unique index constraint over multiple (2) columns: "username", and "provider". The index works fine and does not allow inserting rows with duplicated usernane+provider combination.
But I do want to allow insertion of the same usernane+provider combination in case another column, "active", has the value false. I do not have a problem with multiple duplicate rows all marked as active FALSE.
MySQL, unlike Microsoft SQL Server, does not support conditional/filterable indexing.
While I could not find a more appropriate solution, I thought to use a trigger (after insertion to the table) to check whether the value that was just inserted is duplicated, considering the "active" value.
Can I get the trigger to fail the INSERT statement? Is there a better solution for this case?


text:
Q: Retrieve mp3 from raw folder according to its name in android I have a problem with retrieving mp3 file from raw folder according to its name in android. The files are named word_1.mp3, word_2.mp3, word_3.mp3.
I can retrieve string and image but don't know how to do this with audio file.
I have two activities named Main.java and  Subjects.java. There's ListView in Main.java that after clicking on items, according to the position it shows the string and image that are coded for example: subject_1, subject_2 and image_1.jpg, image2.jpg by means of Adapter from string file and drawable folder. My code is shown below:
------------ Main.java ------------
Subjects_total_number = global.Subjects_total_number;
    Subjects = new String[Subjects_total_number];
    for(int x = 1; x < Subjects_total_number+1; x = x+1) {
        String this_subject = "subject_" + String.valueOf(x);
        int resID = getResources().getIdentifier(this_subject, "string", getPackageName());
        Subjects[x-1] = getResources().getString(resID);
    }

    setListAdapter(new MyAdapter(this,
            android.R.layout.simple_list_item_1, R.id.textView1,
            Subjects));

    lv = getListView();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, final View view,
            int position, long id) {
            Intent i = new Intent(getApplicationContext(), Show_Subjects.class);
            String Subject_number = String.valueOf(position+1);
            i.putExtra("subject_number", Subject_number);
            startActivity(i);

        }

      });

--------------- Subjects.java -------------
***** Retrieving string according to code subject_ from string file ****
TextView tv1 = (TextView) findViewById(R.id.textView1);
    String stringName_1 = "subject_" + String.valueOf(Subject_number);;
    int resID_1 = getResources().getIdentifier(stringName_1, "string", getPackageName());
    tv1.setText(resID_1);

***** Retrieving image according to code subject_ from drawable folder****
ImageView iv = (ImageView) findViewById(R.id.imageView2);
    String imageName = "image_" + String.valueOf(Subject_number);
    int image_res_ID = getResources().getIdentifier(imageName,"drawable",getPackageName());
    iv.setImageResource(image_res_ID);

???? So how to do this with mp3 files and set Adapter for it according to file coded name and after clicking on the fist item of the listview, we have a play button in Subjects.java activity that after clicking it plays word_1.mp3.
Thanks in advance...


text:
Q: Functions not doing anything I have a gameObject called BounceBack that is supposed to bounce the ball back far away when they collide together.
public class BounceBack : MonoBehaviour
{
    public GameObject Player;
    public float force;

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag(Player.tag))
        {
            Player.GetComponent<PlayerController>().ForceBack(force);
        }
    }
}

The ball Player (ball) script:
public class PlayerController : MonoBehaviour
{
    public int acceleration;
    public int speedLimit;
    public int sideSpeed;

    public Text countText;
    public Text winText;

    public GameObject pickUp;
    public GameObject finishLine;

    //internal void ForceBack() //Not sure what it does and why it's there.
    //{
    //    throw new NotImplementedException();
    //}

    private int count;
    private Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        SetCount();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal") * sideSpeed * rb.velocity.magnitude / acceleration;
        //float moveVertical = Input.GetAxis("Vertical") * acceleration;

        if (rb.velocity.magnitude <= speedLimit)
        {
            rb.AddForce(0.0f, 0.0f, acceleration); // add vertical force
        }
        rb.AddForce(moveHorizontal, 0.0f, 0.0f); // add horizontal force
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag(pickUp.tag))
        {
            other.GetComponent<Rotate>().Disapear();
            count++;
            SetCount();
        }
        if (other.gameObject.CompareTag(finishLine.tag))
        {
            acceleration = 0;
            sideSpeed = 0;
            finishLine.GetComponent<GameEnd>().FadeOut();
            if (count >= 2)
            {
                winText.GetComponent<WinTextFadeIn>().FadeIn("Vous avez remporté la partie!");
            }
            else
            {
                winText.GetComponent<WinTextFadeIn>().FadeIn("Vous avez perdu. Réesayer?");
            }
        }
    }

    private void SetCount()
    {
        countText.text = "Count : " + count.ToString();
    }

    public void ForceBack(float force)
    {
        Rigidbody rb = GetComponent<Rigidbody>();
        rb.AddForce(0.0f, 0.0f, -force, ForceMode.VelocityChange);
        Debug.Log("Pass");
    }
}

The AddForce function does not do anything. I tried with setActive(false) and it's not working either. The only thing that works is Debug.Log(). I'm not sure if the speedlimit and acceleration are interfering with the function.
EDIT: I'm not sure if the problem is from Unity but I can't access any variable of the class from the forceBack function inside the class.
EDIT2: I also tried to call the AddForce function directly in the Bounce Back script but it's not working either.
Player.GetComponent<Rigidbody>().AddForce(0.0f, 0.0f, -force, ForceMode.VelocityChange);

Player (Ball) Screenshot
Bounce Back Screenshot

A: So, a couple things:
1.) The physics system should already cause the ball to bounce if you've set up the colliders and rigidbodies properly.  You should only need to do something like this if the ball should gain momentum when it bounces, which is unlikely.  You should post screenshots of their inspectors if this answer doesn't help.
2.) On your rb.AddForce() call, you're applying a force in world-space, which may be the wrong direction to bounce.  If you know the ball is oriented the way it's moving, then you can call AddRelativeForce with the same parameters.  If the ball's orientation is not controlled, then you need to calculate the correct world-space direction to use before applying the force.
3.) Finally, just to confirm, the objects with BounceBack attached do have a non-zero value in the 'force' parameter in the inspector, right?


text:
Q: React setState multiple arrays based on index I have a rather tricky question to ask,
I'm working on a page that accepts several inputs from the Data-Base
and with that I'm generating several inputs( the number of inputs  is not constant)
basically like this:
 const form = this.state.inputs.map((input, i) => {
      if (input) {
        return (

              {input.inputName}

              <input
                name={`${input.inputName}-${i}`}
                type={input.inputType}
                id={input.inputLabel}
                onChange={this.onChange}
              />

        );
      }
    });

after generating the form with the unknown number of values ( depends on the Data-Base)
I want to save all the values of that form, but because I do not know the number of inputs I made 2 arrays ( I need to save the value and the name to be later shown in a different page)
  state = {
  ....
    inputData: {
      names: [],
      values: []
    }
  ....
  };

but I'm having trouble of actually saving the values in the setState
 onChange = e => {
    e.preventDefault();
    const { name, value } = e.target;
    var nameIndex = name.split('-');
    const names = [];
    const values = [];
    values[nameIndex[1]] = value;
    names[nameIndex[1]] = nameIndex[0];
    const inputData = { names, values };
    this.setState({ inputData });
  };

the setState works like this:
on my map I give each input a name that contains the index that's generated by the map so the name is like "inputname-1", and I use split to take out the 1 and update the two arrays I did in the setState (values,names) and everytime the user writes in the input it changes the value inside the array like so: values[1]=(users input...) ,
but I noticed that if I change the 2nd value for example, the values before him in the index 1 and 0 become undefined, am I missing something?

A: You are creating a new names and values array with just one index populated in it. This is why you are overwriting other indices in the array
You could do something like this if you want to update only the specific indexes without mutation:
const { name, value } = e.target;
const [key, index] = name.split('-');

this.setState(prevState => ({
   ...prevState,
   inputData: {
      values: Object.assign([], {...prevState.inputData.values }, { [index]: value }),
      names: Object.assign([], {...prevState.inputData.names }, { [index]: key })
   }
}))

Another option is to take a copy of the prevState.inputData.values using the spread syntax and update it's value at specific index and then set it to inputData:
const { name, value } = e.target;
const [key, index] = name.split('-');

this.setState(prevState => {
  const cloneValues = [...prevState.inputData.values],
        cloneNames = [...prevState.inputData.names];

  cloneValues[index] = value;
  cloneNames[index] = key;

  return {
    ...prevState,
    inputData: {
      values: cloneValues,
      names: cloneNames
    }
  }
})


text:
Q: CSS: border-box not working as expected on a table? I'm trying to give a table a left margin, and set the width of the table plus its margin to 100% of the containing div.
Normally I'd do this with width: 100% and box-style: border-box, but this doesn't seem to be working on a table.
Here's my CSS:
table {
    width: 100%;
    margin-left: 2em;
    border: 1px solid black;
    box-sizing: border-box;
    display: table; /* tried adding this but doesn't seem to help */
}

You can see the problem here in a JSFiddle: http://jsfiddle.net/7C66d/
I can see it in Chrome, Firefox and Safari.

A: I think you are confused, you use padding with border-box, not margin.
http://jsfiddle.net/7C66d/4/
HTML

why is this table	not border-box

CSS
#wrapper {
    width: 100%;
    padding-left: 2em;
    box-sizing: border-box;
}

table {
    width: 100%;
    border: 1px solid black;
    display: table;
}

A: If you don't want a wrapper, you can use display:block as it will set the width to 100% by default.
Code:
table {
    margin-left: 2em;
    border: 1px solid black;
    display: block;
}


text:
Q: Anyway to compare two columns that are way different MySQL I'm having a little of a struggle comparing two columns in MySQL.
This is quite hard to explain but I'll try my best.
I have a column called name and another one called locale_name. Now i need to compare strings from those two columns that have a +number (between 0-9) at the end of each string. It would be easy to do so if all the strings had just the number at the end but some of the have other symbols for example
column locale_name has Something+2
column name has Something+2''
And now i need to somehow skip the symbols at the end and compare just numbers at the end of each string... I hope that made sense. I tried several queries already but i just don't know a way of how to get rid of those symbols or anyway around it.


text:
Q: Regular expression to match all phone numbers I have tried matching Phone numbers with the regular expressions provided by Android in Patterns.Phone,this matches a lot of things that are not phone numbers.I have also tried using:
(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?

However,I found that the Test was not successfull for all the inputs.I would like to validate the following inputs using a regular expression:
  67450450
  +9144-27444444
  27444444
  27470570
  +12142261347
  +61406366180
  0891 2577456
  2577456
  +91 9550461668
  9550461668
  03-1234567
  1860 425 3330

Basically any nymber format supported here:WTND

A: you can use the following code to check phone #:

    private boolean validPhone(String phone) {
        Pattern pattern = Patterns.PHONE;
        return pattern.matcher(phone).matches();
    }

if(validPhone("67450450")){
  Toast.makeText(this,"The phone number is valid");
}
 else
{
  Toast.makeText(this,"The phone number is not valid");
}

A: This isn't clean/efficient, just thrown together to match your sample data:
\b\d{7,10}|\+\d{4}-\d{8}|\+\d{11}|\d{4}\s\d{7}|\+\d{2}\s\d{10}|\d{2}-\d{7}|\d{4}\s\d{3}\s\d{4}\b


text:
Q: is there a way i can change the color of the arrow in the appBar after using pushNamed? The reason is cause the background color of my new page is 'white' and so is the arrow so it is not visible.

A: The code example of your AppBar:
AppBar(
  leading: IconButton(
    onPressed: Navigator.of(context).pop,
    icon: const Icon(
      Icons.arrow_back,
      color: Colors.black,
    ),
  ),
);

Instead of Colors.black you can use whatever color you want

A: in the new page, add leading to your appbar:
Scaffold(
            appBar: AppBar(
            leading: IconButton(icon: Icon(Icons.arrow_left, color: Colors.black,),onPressed:(){}),
            ),

OR
Apply theme:
appBarTheme: AppBarTheme(
  iconTheme: IconThemeData(color: Colors.black),


text:
Q: Moving unique_ptr in the declaration of a vector I try to move some unique_ptr in a vector during it declaration and I get a error. I think that I make a copy without knowing it.
I don't understand why I get the problem at the declaration while it works very well during a push_back.
I simplified the problem in few lines.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;

int main() {

    unique_ptr<int> i1 = make_unique<int>(142);
    unique_ptr<int> i2 = make_unique<int>(242);
    unique_ptr<int> i3 = make_unique<int>(342);

    vector<unique_ptr<int>> v;

    //Those lines work
    v.push_back(move(i1));
    v.push_back(move(i2));
    v.push_back(move(i3));

    //ERROR
    vector<unique_ptr<int>> v2 {move(i1), move(i2), move(i3)};

    return 0;
}

The error is :
use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const
std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp =
std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

What am I missing ?
Thanks !

A: When you do
vector<unique_ptr<int>> v2 {move(i1), move(i2), move(i3)};

you are not actually moving directly into the vector v2. Instead the compiler will create a std::initializer_list of the moved unique pointers, and pass that list object to the std::vector constructor which will then attempt to copy the elements from the initializer list.
Unfortunately I know of no way to solve the problem, of using the intermediate initializer list to initialize a vector of unique pointers.

A: The line
vector<unique_ptr<int>> v2 {move(i1), move(i2), move(i3)};

creates a std::initializer_list, which only provides access to its members via reference-to-const. This initializer_list is constructed by moving from each unique_ptr, but the vector is then initialised by copying elements from the initializer_list. It's this copy that causes your compilation error.


text:
Q: Fitting logistic function in R, response unconstrained to 0 < Y < 1 I want to fit a logistic function of the form $$f(t) = \frac{C}{1+ab^{-t}}$$to some data that I have, using R.
There is some uncertainty to $f(t)$, and its magnitude is assumed to be constant. There is no uncertainty in $t$.
Answers to the question Logistic regression for bounds different from 0 and 1 mention that it's possible, but don't specify how. I am interested in estimating $C$, $a$ and $b$ and also $R^2$.


text:
Q: Detect whether the word you is a subject or object pronoun based on sentence context. Ideally using regex, in python. I'm making a simple chatbot, and it's currently having problems responding to phrases like "I love you" correctly (it'll throw back "You love I" out of the grammar handler, when it should be giving back "You love me").
In addition, I'd like it if you could think of good phrases to throw into this grammar handler, that'd be great. I'd love some testing data.
If there's a good list of transitive verbs out there (something like a "top 100 used") it may be acceptable to use that and special case the "transitive verb + you" pattern.

A: Well, what you're trying to implement is definitely very challenging but also very difficult.
Logic
As a starter, I would look a bit into the Grammar rules first.
Basic sentence structure :

*

*SUBJECT + TRANSITIVE VERB + OBJECT

*SUBJECT + INTRANSITIVE VERB

(Of course, we could also talk about "Subject+Verb+Indirect Object+Direct Object" formats, etc (e.g. I give you the ball) but this would get too complicated for now...)
Obviously, this scheme is VERY simplistic, but let's stick to that for now.
Then (another over-simplistic assumption), that each part is a single word.
so basically you have the following Sentence Scheme :
WORD WORD WORD

which could be generally matched using a regex like :
([\w]+)\s+([\w]+)\s+([\w]+)?

Explanation :
([\w]+)     # first word (=subject)
\s+         # one or more spaces
([\w]+)     # second word (=verb)
\s+         # one or more spaces
([\w]+)?    # (optional) third word (=object - if the verb is transitive)

Now, obviously to formulate sentences like "You love me" and not "You love I", your algorithm should also "understand" that :

*

*The third part of the sentence has the role of the Object

*Since "I" is a personal pronoun (used only in nominative case : "as a subject"), we should you its "accusative form" (=as an object); so, for this purpose, you may also need e.g. personal pronoun tables like :

*

*I   - my   - me

*You - your - you

*He  - his  - him

*etc...

Just a few ideas... (purely out of my enthusiasm for linguistics :-))

Data
As for the wordlists you are interested in, just a few samples :

*

*330 Most Common English Verbs (most - if not all of them - are
transitive)

*Personal Pronouns Chart

A: What you want is a syntactic analyser (aka parser)- this can be done by a rule-based system as described by @Dr.Kameleon, or statistically. There are many implementations out there, one being the Stanford one. These will generally tell you what the syntactic role of a word is (e.g. subject "You are here", or object "She like you"). How you use that information to turn statements into questions is a whole different can of worms. For English, you can get a fairly simple rule-based system to work OK.


text:
Q: What is neuroph GUI import file format? Just starting with Neuroph NN GUI. Trying to create a dataset by importing a .csv file. What's the file format supposed to be?
I have 3 inputs and 1 output so I assumed the format of the import file would be ..
1,2,3,4
6,7,8,9
But I get error 9, or 4 or 10 depending on what combination I try of newlines, commas etc.
Any help out there ?
many thanks,
john.

A: That's because you aren't counting with the output column. The lastest columns are for the output.
So, for example, if you have 10 inputs and 1 output, your file will need to have 11 columns.
I came here, because the Neurophy can't import CSVs with title line. Example of a data file that works for me:
1.0,1.0,1.0
1.0,2.0,2.0
1.0,3.0,3.0
1.0,4.0,4.0
1.0,5.0,5.0
1.0,6.0,6.0
1.0,7.0,7.0
1.0,8.0,8.0
1.0,9.0,9.0
1.0,10.0,10.0
2.0,1.0,2.0
2.0,2.0,4.0
2.0,3.0,6.0
2.0,4.0,8.0
2.0,5.0,10.0
2.0,6.0,12.0
2.0,7.0,14.0
2.0,8.0,16.0
2.0,9.0,18.0
2.0,10.0,20.0


text:
Q: Getting warning from JSF: The response was already committed by the time we tried to set the outgoing cookie for the flash I have a page1.jsf, in this page i have a commandButton that put an object in ELFlash, and redirects to page2.jsf. In this page i recover the object by ELFlash. Everything works fine. But while the user remains in page2.jsf, for every ajax request, tomcat shows this warning message:
20/07/2013 09:43:37 com.sun.faces.context.flash.ELFlash setCookie
WARNING: JSF1095: The response was already committed by the time we tried to set the outgoing cookie for the flash.  Any values stored to the flash will not be available on the next request.

What does it really mean?

A: I think that problem might be related to http chunking.
Solution is to increase response buffer size.
After that cookies will be set correctly and Flash Scope should work too.
Use this code:
public class FlashScopeFixerFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // Below line: response.getWriter() must be invoked to buffer size setting work. Just DO NOT touch this!
    response.getWriter();
    HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
    wrapper.setBufferSize(10000000);
    chain.doFilter(request, wrapper);
}

@Override
public void init(FilterConfig arg0) throws ServletException {}
@Override
public void destroy() {}
}

And in web.xml:
<filter>
    <filter-name>FlashScopeFixerFilter</filter-name>
    <filter-class>dk.sd.medarbejderdata.common.FlashScopeFixerFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>FlashScopeFixerFilter</filter-name>
    <url-pattern>*.xhtml</url-pattern>
</filter-mapping>

A: This warning may be caused if you're using Flash for ajax requests. Probably you're trying to do a redirect with ajax set to true and in the listener you're putting values into Flash. Verify if ajax is needed and set it to false for redirections.
Just don't mix ajax=true on commandButtons with flash and you'll be free of this warning.

A: Instead of using a Filter as mentioned in @Rafal K answer, you can also increase the response buffer size by setting a context parameter in your web.xml
<!-- increase buffer size to avoid JSF1095 errors -->
<context-param>
    <param-name>javax.faces.FACELETS_BUFFER_SIZE</param-name>
    <param-value>131072</param-value>
</context-param>

The size is given in bytes and should be larger than your biggest page. You can easily check the size of your pages in Firefox by right clicking and selecting View Page Info.

A: Flash as it should suggest the name is meant to be a sort of temporary container concept between the life cycle of jsf. The point is the following: the object stored in the flash will be promoed to the user in the very next view he will encounter(remember that jsf follows the mvc), thus after being 'used' it will disappear, namely will be removed.
I think that's why you get such error, and that is not related directly with mojarra.


text:
Q: How to import (install) dependencies (packages) from a global system environment to a virtual environment I have installed my needed packages (dependencies) in the global system environment instead of my virtual environment (virtualenv) because i have used the command pip install <package-name> outside of the virtual environment.
So i want to know how can i make a list out of them and install them in any of my virtualenvs?

A: This is useful in a case that anyhow you have installed some packages (dependencies) in your global system environment instead of your virtualenv, by mistake.
For example by using the command "pip install", not "pipenv install" (outside of virtual environment).
So the solution is:

*

*In the global system environment (outside of any virtualenv), create a "requirements.txt" file from all of your installed packages:
$ pip freeze > requirements.txt

*Import installed dependencies from the created "requirements.txt" file to the Pipfile by running the below command in the root that the above created file "requirements.txt" exist; but first check:
a) If Pipfile not exist:
$ pipenv install

b) If Pipfile do exist (i.e. already created virtualenv):
$ pipenv install -r requirements.txt

Then your package listing files "Pipfile" & "Pipfile.lock" would be updated and locked.
But I personally recommend that for avoiding this problem to happen, always use the command
$ pipenv install
instead of $ pip install.

A: You can create file in your global system environment the format of this file is like following:
 my_backages.txt

    $ pip install -U Flask-SQLAlchemy
    $ pip install --upgrade
    $ pip install flask

then you can use pipfile as next :
$ pip install -r my_backages.txt


text:
Q: HTML div being overlayed by section I am trying to lay out a page using sections but am running into some problems.  My code is below...
https://jsfiddle.net/ytv4zp4b/

        Test Content

                Social Links

                Print Link

    Footer

section{background-color:grey;}
.width{background-color:red;max-width:500px;margin:auto;}
.sharing{max-width:500px;margin:auto;}
.sharingsocial{float:left;background:green;}
.sharingprint{float:right;background:yellow;}

I can't work out why the .sharing div is overlayed by the footer section, where am I going wrong?

A: Add following div before closing the .sharing div.
Code :

https://jsfiddle.net/ytv4zp4b/2/

A: Just replace float:left to display:inline-block for .sharingsocial it will work!
here is updated Fiddle

A: You could use overflow: hidden on .sharing to trigger a new new block formatting context
https://jsfiddle.net/ytv4zp4b/3/
Note: that this method will clip your content in case you want to go over the .sharing container boundaries.

A: The Problem
The CSS float property is causing all subsequent elements to float as well. See here for more on floats.
The Solution
You must set clear: both in order to stop other elements from floating as well.
You can accomplish this by adding the following to your CSS:
.width:after {
    content: '';
    display: block;
    clear: both;
}

Demo

section{
  background-color: grey;
}

.width{
  background-color:red;
  max-width:500px;
  margin:auto;
  }

.width:after {
    content: '';
    display: block;
    clear: both;
}

.sharing{
  max-width:500px;
  margin:auto;
}

.sharingsocial{
  float:left;
  background:green;
}
.sharingprint{
  float:right;
  background:yellow;
}

        Test Content

                Social Links

                Print Link

    Footer


text:
Q: Create a mock object for mat-selection-list Am working on the angular test cases for mat-selection-list ,On the click event am calling onClick method and passing searchList as an argument.
<mat-selection-list #searchList class="search-selection-list">
      <mat-list-option class='child-list-dimension' checkboxPosition='before' *ngFor='let data of gridDimensionsData | filter:searchText'
                       (click)='onClicked(searchList)'>
        {{data}}
      </mat-list-option>
    </mat-selection-list>

onClicked(matSelectionList: MatSelectionList): void {
    this.selectedCount = matSelectionList.selectedOptions.selected.length;
  }

How can i pass matselectionList mock data as an argument to the onClick method?
This is the .spec file
describe('When onClicked method is called', () => {
    it('should set selectedCount', () => {
      spyOn(component, 'onClicked');
      const atSelectionList: MatSelectionList[] = [];
      component.onClicked(selectionList);

    });

  })

i made some changes on beforeEach but wont work .
Chnages 1:
selectionList = fixture.debugElement.query(By.directive(MatSelectionList));

Changes 2:
describe('When onClicked method is called', () => {
    it('should set selectedCount', async () => {
      spyOn(component, 'onClicked');
      const trigger = fixture.debugElement.query(By.css('.search-selection-list')).nativeElement;
      fixture.detectChanges();
      component.onClicked(trigger);
      await fixture.whenStable().then(() => {
      });
    });
  });

Thanks in advance.
Expecting a better solution.


text:
Q: How to add new object to NSMutableArray? I wonder how can I add an new item on NSMutableArray in each button click. I already did addObject("something") in button action. The result is always something the object.count still 1. What I want is in each click the object on NSMutableArray adding.
Right now the result I get is like below:
This when I clicked three times
(something)(something)(something)

But the result that I want is like this
(something,something,something)

when I clicked 5 times
(something,something,something,something,something)

... and so on
Here is my code
@IBAction func press(sender: UIButton) {
    var mutar : NSMutableArray = NSMutableArray()
    mutar.addObject("something")
    println(mutar)
}

A: It is because you are allocating the array every time whenever you press the button. It will always get reduced to count 0 on allocation.
Keep this line out of the IBAction method and add it to viewDidLoad():
var mutar : NSMutableArray = NSMutableArray()

A: You need to add your array as an instance variable of your class.
At the top of your class, put:
var array = NSMutableArray()

You are currently initializing an array and adding one object to it, each time you click the button, hence you only have one object each time.

A: Problem is that when you click the button it will create new NSMutableArray
Create instance variable
var mutar : NSMutableArray = NSMutableArray()
@IBAction func press(sender: UIButton) {

      mutar.addObject("something")

     println(mutar)
}

A: Create a global array and allocate memory only once either from viewDidLoad or viewWillAppear or viewDidAppear, In your case on every click you are allocating memory to that array then adding that object into array. So initialize and allocate memory only once and than add object on button click, you will get your expected result.

A: Here is my objective c code snippet:
array = [NSMutableArray arrayWithArray:[[[NSUserDefaults standardUserDefaults] valueForKey:string] componentsSeparatedByString:@","]];
if (array==nil)
    array = [NSMutableArray arrayWithObjects:crctId, nil];
else if (![array containsObject:crctId]){
    flag = YES;
    if(crctId!=nil)
    {
        [array addObject:crctId];
    }
}


text:
Q: How do I write generic reusable promise then/catch handlers? I have a number of calls to json endpoints that look something like this.  This is in the context of a Vue component, but really it doesn't matter overmuch.  All these handlers do is display a bootstrap message with a success/error, all the smarts are in the server.
So it's really not all that different than all those console.log("it worked!") handlers, except that my handlers need extra arguments.
//The Vue component
let myVue = this;

axios.post(this.action_url, qs.stringify(data), config)
.then(function (response) {
      // it's a bit more complicated as it looks at response contents
      // for the actual message
      myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
    });

})
.catch(function (error) {
      myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "failure");
});

elsewhere...
let myVue = this;

axios.post(another_url, qs.stringify(data2), config2)
.then(function (response) {
      myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
    });
.catch ....

})

I'd just like to code the response and error handler once and reuse them.  But, because I need to know something from my execution context, myVue in this case, I can't just import a function and pass in the response, or am I missing something?
function handleResponse(response){
    //  I need extra contextual variables, not just response
    myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
};

which, if it worked, I could use as
axios.post(this.action_url, qs.stringify(data), config)
.then(handleResponse(response))
.catch(someErrorhandler(error));

rather than repeating a closure with the exact same contents each time.
Coming from Python, I think maybe a curry (pre-assigning an argument to a function call, in this case either myVue or {myVue: myVue}) can do it, but what is the idiomatic JS way to achieve handler reuse, if the handlers are identical?  Anything using built-in es6 is preferred over bringing in an extra dependency like Lodash.

A: You were on the right track with currying:
function handleResponse(myVue) {
  return function handleResponse(response){

    myVue.$root.$emit(base_messages.EV_USER_MESSAGE, "success");
  };
}

to be used as
axiosPromise.then(handleResponse(myVue));


text:
Q: About the GNU make dependency files *.d In the makefile of a program, one has to write rules that define the dependencies of each object file. Consider the object file fileA.o. It is obvious that this object file depends on the source file fileA.c. But it will also depend on all the header files that this source file includes. So the following rule should be added to the makefile:
    # This rule states that fileA.o depends on fileA.c (obviously), but also
    # on the header files fileA.h, fileB.h and fileC.h
    fileA.o: fileA.c fileA.h fileB.h fileC.h

Note that the rule has no recipe. One could add a recipe to it, but it is strictly speaking not necessary, because GNU make can rely on an implicit rule (with recipe) to compile a *.c file into a *.o file.
Anyway, writing such rules manually is a hellish task. Just imagine the work to keep the makefile rules in sync with the #include statements from the source code.
The GNU make manual describes in chapter 4.14 "Generating Prerequisites Automatically" a methodology to automate this procedure. The procedure starts with the generation of a *.d file for each source file. I quote:

For each source file name.c there is a makefile name.d which lists what files the object file name.o depends on.

The manual proceeds:

Here is the pattern rule to generate a file of prerequisites (i.e, a makefile) called name.d from a C source file called name.c :

    %.d: %.c
        @set -e; rm -f $@; \
         $(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
         sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
         rm -f $@.$$$$

Sadly, the manual does not explain in detail how this rule actually works. Yes, it gives the desired name.d file, but why? The rule is very obfuscated..
When looking at this rule, I get the feeling that its recipe will only run smoothly on Linux. Am I right? Is there a way to make this recipe run correctly on Windows as well?
Any help is greatly appreciated :-)

A: Exit on all errors
@set -e;

Delete existing dep file ($@ = target = %.d)
rm -f $@;

Have the compiler generate the dep file and output to a temporary file postfixed with the shell pid ($< = first prerequisite = %.c, $$$$ -> $$ -> pid)
$(CC) -M $(CPPFLAGS) $< > $@.$$$$;

Capture the target matching $*.o ($* = match stem = %), replace it with the target followed by the dependency file itself, output to dep file
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \

Delete temp dep
rm -f $@.$$$$

Let's plug in foo, CC = gcc, and CPPFLAGS = '' to see what happens after make has finished expanding stuff:
foo.d: foo.c
    @set -e; rm -f foo.d; \
     gcc -M foo.c > foo.d.$$; \
     sed 's,\(foo\)\.o[ :]*,\1.o foo.d : ,g' < foo.d.$$ > foo.d; \
     rm -f foo.d.$$

The shell itself will expand $$ to the pid, and the final rule in the dep file will look something like
foo.o foo.d : foo.c foo.h someheader.h

Note that this is a pretty outdated way of generating dependencies, if you're using GCC or clang you can generate them as part of compilation itself with CPPFLAGS += -MMD -MP.
Say you have a program called foo:
objs := foo.o bar.o
deps := $(objs:.o=.d)

vpath %.c $(dir $(MAKEFILE_LIST))

CPPFLAGS += -MMD -MP

foo: $(objs)

.PHONY: clean
clean: ; $(RM) foo $(objs) $(deps)

-include $(deps)

That's all you need, the built-in rules will do the rest. Obviously things will be a little more complicated if you want the object files in a different folder or if you want to build outside the source tree.
The vpath directive allows you to run make in a different directory and have the files created there, e.g. make -f path/to/source/Makefile.

A: Responding to K Mulier:
Try: gmake -C $workdir ...
That sets CURDIR = ${workdir} but leaves $PWD (from env) alone.
All temp/output files are created in ${workdir}.
Also, I set the variable $. = ${PWD} and use that to specify anything relative to the dir in which gmake was run (i.e. the source dir).
So, instead of
CPPFLAGS += -I../include
there is
CPPFLAGS += -I$.  -I$./../include


text:
Q: Understanding Memory Usage by PyTorch DataLoader Workers When running a PyTorch training program with num_workers=32 for DataLoader, htop shows 33 python process each with 32 GB  of VIRT and 15 GB of RES.
Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory? htop shows only about 50 GB of RAM and 20 GB of swap is being used on the entire machine with 128 GB of RAM. So, how do we explain the discrepancy?
Is there a more accurate way of calculating the total amount of RAM being used by the main PyTorch program and all its child DataLoader worker processes?
Thank you

A:
Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory?

Not necessary. You have a worker process (with several subprocesses - workers) and the CPU has several cores. One worker usually loads one batch. The next batch can already be loaded and ready to go by the time the main process is ready for another batch. This is the secret for the speeding up.
I guess, you should use far less num_workers.
It would be interesting to know your batch size too, which you can adapt for the training process as well.

Is there a more accurate way of calculating the total amount of RAM being used by the main PyTorch program and all its child DataLoader worker processes?

I was googling but could not find a concrete formula. I think that it is a rough estimation of how many cores has your CPU and Memory and Batch Size.
To choose the num_workers  depends on what kind of computer you are using, what kind of dataset you are taking, and how much on-the-fly pre-processing your data requires.
HTH

A: There is a python function called tracemalloc which is used to trace memory blocks allocated to python. https://docs.python.org/3/library/tracemalloc.html

*

*Tracebacks

*Statics on memory per filename

*Compute the diff between snapshots

import tracemalloc
tracemalloc.start()
do_someting_that_consumes_ram_and releases_some()
# show how much RAM the above code allocated and the peak usage
current, peak =  tracemalloc.get_traced_memory()
print(f"{current:0.2f}, {peak:0.2f}")
tracemalloc.stop()

https://discuss.pytorch.org/t/measuring-peak-memory-usage-tracemalloc-for-pytorch/34067


text:
Q: Updating apk SHA1 differs even after using same keystore I have uploaded my app to Goggle Play few months back after signing it with a release keystore, I have stored that Keystore for future updation. Now I have updated the apk with some changes, while trying to upload the new apk signed with same keystore along with same alias and password, the apk is not allowed to upload to Goggle Play.
Playstore shows me following error :

The only change is, earlier the appication was developed and build using eclipse and now in android studio  Can this be the reason for showing the above error???

A: From the error message I would say you have mixed up the keystores, or android studio is just using the wrong one to do the release build. The best way to be completely sure is to clearly setup your build.gradle, and build it yourself on the command line using
 ./gradlew clean assembleRelease

What is probably happening is that Android Studio is using your debug keystore (ie. the default) to sign the release build because it can't find the original keystore you used in eclipse, or you have the wrong password somewhere...
Have a look at this configuration, note the location of the keystores, the naming convention and how it corresponds to the build.gradle. Note the signingconfigs and how they are setup for the release build. To build from the command line, simply cd into the directory with your "gradlew" file, and run
./gradlew clean assembleRelease

to build the release apk, or
./gradlew clean assembleDebug

to build the debug apk. If it fails, try
./gradlew clean assembleRelease --stacktrace

Screenshot of build.gradle and filesystem setup
But please remember not to put your keys in your source control! That means editing your .gitignore file.
There is a stack of information on how to do this here:
http://developer.android.com/tools/publishing/app-signing.html


text:
Q: SharePoint mapped Layouts/15/Images folder/image.jpg - not showing up In my SharePoint 2013 site, where I am deploying few of the images in the layouts/Images/Test and when I am trying to access it on sharepoint, I am just seeing an 'X' mark. Where as there are few other images in the same folder and accessed similarly(/_layouts/15/Images/Test/testImage5.jpg) and I am able to see those images. But this newly added image is just showing up as cross mark.
Kindly suggest What can be the issue.

A: *

*Please ensure you are referring correct Web Application(where your
images are deployed).

*Navigate to IIS and Locate the file path in
Web App -> right-click -> browse, check URL is correct (replace
localhost to web app url)

A: Use developer tool to check the image full url, and then request the url in a new tab of browser, if the image couldn't show, the image url would not correct.
Use IIS manager to confirm the path also.


text:
Q: Getting values from form and saving in database but spaces are inserted instead of form values <?php /* Template Name: Dummy Practice Page*/?>

            <form method="post">

                <input name="nametxt" id="nametxt" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

                <input name="designationtxt" id="designationtxt" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required>

                <input name="designationtxt" id="descriptiontxt" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required>

                <input id="submitbtn" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;   " name='Submit' value='Add Member' />

            </form>

<?php
     global $wpdb;
    $table = $wpdb->prefix.'tboxteam';
     $data = array('name' =>  isset($_POST['nametxt']), 'designation' =>  isset($_POST['designationtxt']), 'description' =>  isset($_POST['descriptiontxt']));
     $format = array('%s','%s','%s');
     $wpdb->insert($table,$data,$format);
?>

A: PHP isset returns boolean value to check if the array index exists. https://www.php.net/manual/en/function.isset.php
"name" => isset($_POST["nametxt"]) ? $_POST["nametxt"] : ""
This is what you should do

A: <?php /* Template Name: Dummy Practice Page*/?>

        <form method="post">

            <input name="nametxt" id="nametxt" type="text" style="height:30px; width: 350px; " maxlength="5" placeholder="Name" required>

            <input name="designationtxt" id="designationtxt" type="text" style="height:30px; width: 350px; " maxlength="50" placeholder="Designation" required>

            <input name="descriptiontxt" id="descriptiontxt" type="text" style="height:30px; width: 350px; " maxlength="1000" placeholder="Description" required>

            <input id="submitbtn" type='submit' style="height:40px; width: 130px; padding:10px; color:dodgerblue; background-color:black; border-radius:20px;   " name='Submit' value='Add Member' />

        </form>

 <?php
 // Checking if form submitted
 if(isset($_POST['Submit'])){

       // Fetching values if they are not empty.
    if( isset($_POST['nametxt']) || isset($_POST['designationtxt']) ||isset($_POST['descriptiontxt']) ){

        global $wpdb;

        $data = array('name' =>  $_POST['nametxt'], 'designation' =>  $_POST['designationtxt'], 'description' =>  $_POST['descriptiontxt'] );

        $table = $wpdb->prefix.'tboxteam';

        $format = array('%s','%s','%s');

        $wpdb->insert($table,$data,$format);
    }
 }

 ?>


text:
Q: Mobile smooth scrolling with bootstrap i'm creating a web with bootstrap, and I would like to add an smooth scrolling effect. It works perfectly on the desktop, but in the mobile version when you click on a link of the menu the scroll is much larger than the beginning of the section.
I'm using this code:
// Smooth scrolling
  $(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top -60
    }, 1000);
  });

// Closes responsive menu when a scroll trigger link is clicked
  $('.js-scroll-trigger').click(function() {
    $('.navbar-collapse').collapse('hide');
  });

// Activate scrollspy to add active class to navbar items on scroll
  $('body').scrollspy({
    target: '#mainNav',
    offset: 60
  });

You can check the test page at: http://pruebas.mareaestudio.com/raposo/
Thanks


text:
Q: Duplicate the workbook with the invoice number list I have an two excel sheet,

*

*Format.xlsx (having 2 tabs)

Tab 1 - Summary annexure
Tab 2 - Annexure A

*Invoice list - Having unique list of invoices

I want to duplicate "Format.xlsx" (i.e copy and paste) number of times in the invoice list and excel to be named as per relevant invoice number.
eg say I have two invoices with numbers 123 and 456, I want the format to be copy-pasted twice, to an excel sheet, having named changed to 123 and 456.
Also, without changing the format of the excel template.
I tried the below code
invoice_num_list = pd.read_csv('Invoice List.csv') #List of invoices
print(invoice_num_list.shape)

# Output (140, 1)

Format = pd.read_excel('Format.xlsx') #Template having 2 tabs

for invoice_num in invoice_num_list:
    Format.to_excel(f'{invoice_num}.xlsx')

But the above code is not duplicating the sheet 140 times, but only once.
Also, the format of the excel template was changed and formula placed is completely erased.
The intention is to copy-paste the format 140 times (for respective invoice numbers) having relevant formula in Tab 1, later on placing new data in Tab 2, Tab 1 would be automatically updated.
Help would be much appreciated!
Link to sample data -
https://drive.google.com/drive/folders/1inrofeT6v9P0ISEcmbswvpxMMCq5TaV0?usp=sharing

A: I think the sample code below will do what you want.
Note that it uses openpyxl.load_workbook() instead of pd.read_excel(), which allows all tabs, formulas and formatting in the existing workbook to be preserved.
Also note that the for loop in your code needed to be adjusted slightly to correctly iterate through the invoices in the other file.
import pandas as pd
import openpyxl
invoice_num_list = pd.read_csv('Invoice List.csv') #List of invoices
print(invoice_num_list.shape)

# Here we use only the first 5 invoices, as a test
invoice_num_list = invoice_num_list[invoice_num_list.index < 5]
print(invoice_num_list)

Format = openpyxl.load_workbook('Format.xlsx') #Template having 2 tabs

for invoice_num_index, invoice_num in invoice_num_list.itertuples():
    print(f"{invoice_num}")
    Format.save(f'{invoice_num}.xlsx')

Output:
(140, 1)
    Invoice number
0  KA-AVSR-Feb22-1
1  KA-AVSR-Feb22-2
2  KA-AVSR-Feb22-3
3  KA-AVSR-Feb22-4
4  KA-AVSR-Feb22-5
KA-AVSR-Feb22-1
KA-AVSR-Feb22-2
KA-AVSR-Feb22-3
KA-AVSR-Feb22-4
KA-AVSR-Feb22-5


text:
Q: Kafka Strimzi on AKS: How to config PLAIN listeners when external listeners(ScramSha512, TLS encryption) & ACL is already configured I have already configured the external listeners and ACL as it follows (those are functional)
listeners:
 plain: {}
 external:
  type: loadbalancer
  tls: true
  authentication:
   type: scram-sha-512
authorization:
 type: simple

This is hosted on a AKS cluster. Consuming from on prem it does work already and also producing from inside the cluster but with publicIP:9094 as bootstrapServers.
I would like to add a producer inside the cluster and use 9092 port (like this BootstrapServers = "my-cluster-kafka-bootstrap:9092", I suppose) with minumun necessary effort (even without ACL if possible, without any authentication, without any encryption).
What would recommend?
Thank you in advance!

A: SO thanks to Jakub from Strimzi https://github.com/scholzj, this is the minimal config
listeners:
  plain:
    authentication:
      type: scram-sha-512
  external:
    type: loadbalancer
    tls: true
    authentication:
      type: scram-sha-512
authorization:
  type: simple

And the C# client would look like this
        var conf = new ProducerConfig
        {
            BootstrapServers = "my-cluster-kafka-bootstrap:9092",
            SecurityProtocol = SecurityProtocol.SaslPlaintext,
            SaslMechanism = SaslMechanism.ScramSha512,
            SaslUsername = "admin",
            SaslPassword = "xxx",
        };

Explanation would be:

Kafka has only one authorizer configuration for the whole cluster. So
it is either on or off for all listeners. The plain listener is
without encryption, but if you need authorization for the external
listener, you will need enable authentication there (since without
authentication the authorization would deny everything).


text:
Q: What does this ps command do on Linux? I try to get the output of the top 5 processes in a Linux system. I'm expecting to get the percentage of processor (CPU) used but I'm a little worried about if the command that I'm using gets the CPU or the RAM; what is the output?
ps -A --sort -rss -o comm,pmem | head -n 6

The man documentation of ps indicates that the output is the process, but I'm suspecting that is the RAM memory.  Could you clarify the output for me, please?

A: It's a process sorting by rss which is resident set size - memory usage - and then showing you the command and percentage memory usage. Header line and top 5 processes.
For an explanation of what RSS actually is, see this answer on unix: https://unix.stackexchange.com/questions/35129/need-explanation-on-resident-set-size-virtual-size
To get the top 5 by CPU load as you asked:
ps -A --sort -pcpu -o comm,pmem,pcpu | head -n 6


text:
Q: How can I convert a ndarray/multi-dimensional array to a parquet file? I have a <class 'numpy.ndarray'> array that I would like saved to a parquet file to pass to a ML model I'm building.
My array has 159573 arrays and each array has 1395 array in each.
Here is a sample of my data:
[[0.         0.         0.         ... 0.24093714 0.75547471 0.74532781]
 [0.         0.         0.         ... 0.24093714 0.75547471 0.74532781]
 [0.         0.         0.         ... 0.24093714 0.75547471 0.74532781]
 ...
 [0.         0.         0.         ... 0.89473684 0.29282009 0.29277004]
 [0.         0.         0.         ... 0.89473684 0.29282009 0.29277004]
 [0.         0.         0.         ... 0.89473684 0.29282009 0.29277004]]

I tried to convert using this code:
import pyarrow as pa
pa_table = pa.table({"data": Main_x})
pa.parquet.write_table(pa_table, "full_data.parquet")

I get this stacktrace:
5 frames
/usr/local/lib/python3.7/dist-packages/pyarrow/table.pxi in pyarrow.lib.table()

/usr/local/lib/python3.7/dist-packages/pyarrow/table.pxi in pyarrow.lib.Table.from_pydict()

/usr/local/lib/python3.7/dist-packages/pyarrow/array.pxi in pyarrow.lib.asarray()

/usr/local/lib/python3.7/dist-packages/pyarrow/array.pxi in pyarrow.lib.array()

/usr/local/lib/python3.7/dist-packages/pyarrow/array.pxi in pyarrow.lib._ndarray_to_array()

/usr/local/lib/python3.7/dist-packages/pyarrow/error.pxi in pyarrow.lib.check_status()

ArrowInvalid: only handle 1-dimensional arrays

I'm wondering if there is a way to save a multi-dimensional array to parquet?

A: Parquet/Arrow isn't best suited to save this type of data.
It's better at dealing with tabular data with a well defined schema and specific columns names and types.
In particular the numpy conversion API only supports one dimensional data.
Having that said you can easily convert your 2-d numpy array to parquet, but you need to massage it first.
You're best option is to save it as a table with n columns of m double each.
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq

matrix = np.random.rand(10, 100)
arrays = [
    pa.array(col)  # Create one arrow array per column
    for col in matrix
]

table = pa.Table.from_arrays(
    arrays,
    names=[str(i) for i in range(len(arrays))] # give names to each columns
)
# Save it:
pq.write_table(table, 'table.pq')

# Read it back as numpy:
table_from_parquet = pq.read_table('table.pq')
matrix_from_parquet = table_from_parquet.to_pandas().T.to_numpy()

The intermediate table has got 10 columns and 100 rows:
|         0 |          1 |          2 |         3 |          4 |          5 |          6 |         7 |         8 |          9 |
|----------:|-----------:|-----------:|----------:|-----------:|-----------:|-----------:|----------:|----------:|-----------:|
| 0.45774   | 0.92753    | 0.252345   | 0.982261  | 0.503732   | 0.543526   | 0.22827    | 0.347948  | 0.654259  | 0.152693   |
| 0.287813  | 0.793067   | 0.972282   | 0.739047  | 0.0689906  | 0.102235   | 0.110273   | 0.166839  | 0.907481  | 0.427729   |
| 0.523928  | 0.511737   | 0.473887   | 0.771607  | 0.707633   | 0.276726   | 0.943073   | 0.788174  | 0.305119  | 0.511876   |
| 0.67563   | 0.947449   | 0.895125   | 0.246979  | 0.703503   | 0.256418   | 0.93113    | 0.116715  | 0.330746  | 0.566704   |
| 0.471526  | 0.45332    | 0.546384   | 0.822873  | 0.333542   | 0.518933   | 0.229525   | 0.381977  | 0.893204  | 0.932781   |
...


text:
Q: Load a binary into flash memory using gdb I'd like to flash a binary file into my ARM MCU flash memory using gdb.
Currently I'm able to load an elf like this:
# arm-none-eabi-gdb --command=flash.gdb "myfirmware.elf"

# cat flash.gdb
set confirm off
target remote 127.0.0.1:7224
monitor reset
load
detach
quit

Basically the load command is good at loading elf sections to the right addresses.
However to put multiple firmware in the MCU flash memory, I'd like to send a complete binary image.
In order to test it, I made a zero.bin image (containing nothing but 0):
# hexdump zero.bin
0000000 0000 0000 0000 0000 0000 0000 0000 0000
*
0020000

# arm-none-eabi-gdb
(gdb) target remote 127.0.0.1:7224
(gdb) mon reset halt
(gdb) mon reset init
(gdb) set arm fallback-mode auto
(gdb) set debug arm
(gdb) restore zero.bin binary 0x0
Restoring binary file zero.bin into memory (0x0 to 0x20000)
Writing to flash memory forbidden in this context
(gdb) info mem
Using memory regions provided by the target.
Num Enb Low Addr   High Addr  Attrs
0   y   0x00000000 0x00020000 flash blocksize 0x800 nocache
1   y   0x00020000 0x100000000 rw nocache
(gdb) delete mem 1
warning: Switching to manual control of memory regions; use "mem auto" to fetch regions from the target again.
(gdb) delete mem 0
(gdb) mem 0 0x100000000 rw nocache
(gdb) info mem
Using user-defined memory regions.
Num Enb Low Addr   High Addr  Attrs
1   y   0x00000000 0x100000000 rw nocache
(gdb) restore zero.bin binary 0x0
Restoring binary file zero.bin into memory (0x0 to 0x20000)
(gdb) x/10 0x0
0x0:    0x20003000      0x00003c5d      0x00003c7d      0x00003c7d
0x10:   0x00000000      0x00000000      0x00000000      0x00000000
0x20:   0x00000000      0x00000000

So this doesn't seem to work, as you can see in 0x0 it should be full of '0' but it still contains my previous firmware (the vector table actually)
What do I miss? Or maybe there is another way to load a binary using gdb?

A: If you are using OpenOCD,
mon flash write_bank <num> <file_name> <offset>

should help you.
For example, if your flash starts at 0x400000,
mon flash write_bank 0 zero.bin 0x100000
will write the zero.bin file at 0x500000, assuming that address is writable.

A: You can't delete memory region. Because GDB uses vFlashWrite packet for writing to flash memory and M or X packets for writing to RAM.
I know only one way to write binary data to flash memory using gdb.
You need to transform your binary image to elf-file with one single .data section.
powerpc-objcopy -I binary -O elf32-powerpc -B PowerPC -S zero.bin zero.elf
For checking your new elf-file use readelf.
powerpc-readelf -h -t zero.elf
In the end just use load command with flash base address, because this elf-file has not any address information. (or you can use --change-addresses 0x0 option with objcopy)
load zero.elf 0x0
I checked this on PowerPC. GDB version is 8.1.
This GDB was configured as "--host=x86_64-pc-linux-gnu --target=powerpc-eabi".


text:
Q: Assign names to the vector elements of a list in R I was wondering if we could we assign names to each vector element in the output of function foo below?
For the example below, giving elements of $pubs names: "pubs_-1SD", "pubs_+1SD" and for the elements of $time names: "time_-1SD", "time_+1SD"?
data <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/salary.csv')

foo <- function(data, vars) lapply(data[,vars], function(x) mean(x) + c(-1, 1)*sd(x))

foo(data, c("pubs", "time")) # EXAMPLE OF USE

# $pubs
# [1]  5.348203 33.909862 ## `"pubs_-1SD"` and `"pubs_+1SD"

# $time
# [1]  3.312931 12.848359 ## `"time_-1SD"` and `"time_+1SD"`

A: You could pass the column names in sapply and assign names using setNames :
foo <- function(data, vars) sapply(vars, function(x)
  setNames(mean(data[[x]]) + c(-1, 1)*sd(data[[x]]),
           paste0(x, '_', c('-', '+'), '1SD')), simplify = FALSE)

foo(data, c("pubs", "time"))

#$pubs
#pubs_-1SD pubs_+1SD
# 5.348203 33.909862

#$time
#time_-1SD time_+1SD
# 3.312931 12.848359

A: We could use Map
foo <- function(data, vars) {

           Map(function(x, y) setNames(mean(x) + c(-1, 1)*sd(x),
                sprintf('%s_%s1SD', rep(y, 2), c('-', '+'))), data[,vars], vars)
    }

foo(data, c("pubs", "time"))
#$pubs
#pubs_-1SD pubs_+1SD
# 5.348203 33.909862

#$time
#time_-1SD time_+1SD
# 3.312931 12.848359


text:
Q: Calculation of $\int \sin^2 x\frac{\sin x-\cos x}{\sin x+\cos x}dx$
Calculation of $\displaystyle \int\frac{\sin^2 x\cos x}{
\sin x+\cos x}dx$ and $\displaystyle \int^{\pi}_{0}\frac{1}{1-2a\cos x+a^2}dx, ,0<a<1$

$\bf{Attempt}$ For (a) $\displaystyle \frac{1}{2}\int\frac{\sin^2 x\bigg[(\sin x+\cos x)+(\sin x-\cos x)\bigg]}{\sin x+\cos x}dx $
$\displaystyle =\frac{1}{4}\int (1+\cos 2x)dx+\frac{1}{2}\int \sin^2 x\frac{\sin x-\cos x}{\sin x+\cos x}dx$
could some help me how to solve $\displaystyle \int \sin^2 x\frac{\sin x-\cos x}{\sin x+\cos x}dx$
For (b) Can we solve it any geometrical way like taking unit circle . thanks

A: For (a),
\begin{eqnarray}
&&\int\frac{\sin^2 x\cos x}{\sin x+\cos x}dx\\
&=&\int \frac{\sin^2x(\cos^2x-\sin x\cos x)}{\cos^2x-\sin^2x}dx\\
&=&\frac14\int \frac{(1-\cos(2x))(1+\cos(2x)-\sin(2x))}{\cos(2x)}dx\\
&=&\frac14\int\frac{1-\cos^2(2x)-(1-\cos(2x))\sin(2x)}{\cos(2x)}dx\\
&=&\frac14\int(\sec(2x)-\cos(2x)-\tan(2x)+\sin(2x))dx\\
&=&\frac14(\frac12\ln(\frac{\cos x+\sin x}{\cos x-\sin x})-\frac12\sin(2x)+\frac12\ln(\cos (2x))-\frac12\cos(2x))+C\\
&=&\frac18(\ln(\frac{\cos x+\sin x}{\cos x-\sin x})-\sin(2x)+\ln(\cos(2 x))-\cos(2x))+C\\
&=&\frac18(2\ln(\cos x+\sin x)-\sin(2x)-\cos(2x))+C.
\end{eqnarray}
For (b), let $t=\tan\frac{x}{2}$ and then
\begin{eqnarray}
&&\int^{\pi}_{0}\frac{1}{1-2a\cos x+a^2}dx\\
&=&\int^{\pi}_{0}\frac{1}{1-2a\frac{1-\tan^2\frac x2}{1+\tan^2\frac x2}+a^2}dx\\
&=&\int_0^\infty\frac{1}{1-2a\frac{1-t^2}{1+t^2}+a^2}\frac{2}{1+t^2}dt\\
&=&\int_0^\infty\frac{1}{(1+a)^2t^2+(1-a)^2}dt\\
&=&\frac{2}{(1+a)^2}\int_0^\infty\frac1{t^2+(\frac{(1-a}{1+a})^2}dt\\
&=&\frac{2}{(1+a)^2}\frac{1+a}{1-a}\arctan\frac{t}{\frac{1-a}{1+a}}\bigg|_{0}^\infty\\
&=&\frac{\pi}{1-a^2}.
\end{eqnarray}

A: Hint:
$$1-2a\cos x+a^2 =e^{-ix}( e^{ix}(1+a^2)-a(e^{2ix}+1)) = \frac{z(1+a^2)-a(z^2+1)} z $$
with $e^{ix} = z$ that it $dx= \frac{-idz}{z}$
Hence,
$$\displaystyle \int^{\pi}_{0}\frac{1}{1-2a\cos x+a^2}dx, =-i\int_{\gamma}\frac{dz}{z(1+a^2)-a(z^2+1)} ,0<a<1$$
Where, $$\gamma =\{e^{ix}: x\in (0,\pi)\}$$
Now consider $$\Gamma =\{e^{ix}: x\in (0,\pi)\}\cup [-1,1]$$
and apply Cauchy formula for
$$\oint_{\Gamma}\frac{dz}{z(1+a^2)-a(z^2+1)} \equiv \oint_{\Gamma}f(z)dz = 2i\pi\sum Res(f,)$$
where, $$f(z)=\frac{1}{z(1+a^2)-a(z^2+1)}$$
So the only think remain is to compute the polar and Residues. can you take it from here?


text:
Q: SQL Remove all leading zeros My join returns null because I am not able to remove the leading zeros. Basically, I am trying to replace the pol.Policy_Number with src.Policy_Number for a large number of policies. Is there a way I can remove the leading 0s in the ON statement for src.Policy_Number? I think Padding is needed, but I am new to SQL so any help would be much appreciated. That pol policy numbers always equal src policy numbers if it was not for the leading 0s in pol
This is not a duplicate. I am not looking for a select. I need to put padding next to the ON statement so any leading 0s from src.Policy_Number will be removed so the JOIN can return rows. Please don't close the question a duplicate
 UPDATE pol
SET pol.Policy_Number = src.Policy_Number
FROM Policy_Table pol
INNER JOIN SourceTable src
 on  pol.Policy_Number =src.Policy_Number--00000000000000ABCD200,0000000000000EFT200
 Where src.Policy_Number IN('ABCD200','EFT200')

A:  UPDATE pol
SET pol.Policy_Number = src.Policy_Number
FROM Policy_Table pol
INNER JOIN SourceTable src
on  pol.Policy_Number =replace(ltrim(replace(src.Policy_Number,'0',' ')),' ','0')


text:
Q: Sharepoint 2010 Service Pack 2 + Language Packs Our test server currently contains SP1 + 5 SP1 language packs. Do we need to install SP2 (ENG/US) followed by 5 new language packs, such as the German one for instance.
400 MB in size though? How come all these Language Packs are the same size as the intial SP2 installation pack? I recall that these usually are around 30-40 MB for SP1. This means hours and hours of downtime if this ever goes to a production server.
Any feedback is much welcomed.

A: Yes, you will need the SP2 package for each language pack.  The product configuration wizard will fail if you have SP2 for SharePoint, but not the language packs.


text:
Q: Using existing mysql database in lampp I'm using ubuntu 13.04 in a 32 bit machine. I have Windows 8 installed also. I have set up lampp in my ubuntu OS. Now I want to use mysql databases of Windows in ubuntus lampp. I have searched a lot online, but couldn't find any suitable solution. Can anyone help please?

A: Use mysqldump.exe to dump the database contents under Windows into a .sql file. You can then either load it in under Ubuntu by using the mysql tool, or you can load it into a separate system so that it is accessible under both Ubuntu and Windows.

A: To create a php development environment in Ubuntu installed with MySQL and Apache, you may try this link :   https://engineersview.wordpress.com/2013/06/03/php-development-in-ubuntu/

A: I don't know how by heart how to do it, but I know that you can configure MySQL to allow remote connections. By this, you can have your Windows machine run the MySQL server and connect from the virtual Ubuntu over network.


text:
Q: Win7 all applications run in 640x480 I have no idea how to fix this, i am using a virtual machine in virtualbox and can't change the resolutions when i run an exe (Game for example)
If anyone has a solutions please help!
win7 image
ingame image (fullscreen shows black borders)