text:
Q: Displaying background image with correct ratio I have got a container with two background-images on the left and right side of it.
The left image should be shown with height 100%, and the right image with width 50%.
The image itself has a high resolution and I want them to be displayed in a correct ratio. So the width for the left image and the height of the right image should be auto.
But my problem is, that the div-container needs dimensions for showing. How do I do that, as I don't know both parameters?
Update: If I'm using width: 300px for the div-container, I can use background-size: 100% auto and this is working. But I don't know the width...
So what would be a good way to realize that?

main {
  background-color: green;
  height: 500px;
  position: relative;
}
#left_image {
  background-image: url(images/left.jpg);
  height: 100%;
  display: inline-block;
  background-size: cover;
}
#right_image {
  background-image: url(images/right.jpg);
  width: 50%;
  display: inline-block;
  background-size: cover;
  position: absolute;
  right: 0;
}

A: What about using ?

#left_image {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
}

This would also work for IE8. Don't know an advantage for using background-image...


text:
Q: Tensorflow2 - How to assing name to a tf_op_layer? One of my model outcomes is a tf_op_layer, I'd need to assign an outcome name for it. However, I noticed that the argument name is not working for tf_op_layer in general.
A dummy example of what I'm facing. At the summary, it can be seen the missing name for the op_layer. On the other hand, it works well for Dense Layer.
x_input = tf.keras.layers.Input(shape=(1,), name='input_test')
x = tf.keras.layers.Subtract(name='subtraction_1')([x_input, tf.constant([[12.]])])
x_out_1 = tf.keras.layers.Multiply(name='multiply_1')([x, tf.constant([[3.]])])
x_out_2 = tf.keras.layers.Dense(1, name='dense_1')(x)

model = tf.keras.models.Model(x_input, [x_out_1, x_out_2])
model.summary()

# Model: "model"
# __________________________________________________________________________________________________
# Layer (type)                    Output Shape         Param #     Connected to
# ==================================================================================================
# input_test (InputLayer)         [(None, 1)]          0
# __________________________________________________________________________________________________
# tf_op_layer_sub (TensorFlowOpLa [(None, 1)]          0           input_test[0][0]
# __________________________________________________________________________________________________
# tf_op_layer_mul (TensorFlowOpLa [(None, 1)]          0           tf_op_layer_sub[0][0]
# __________________________________________________________________________________________________
# dense_1 (Dense)                 (None, 1)            2           tf_op_layer_sub[0][0]
# ==================================================================================================
# Total params: 2
# Trainable params: 2
# Non-trainable params: 0
# _________________________

I'm using TensorFlow version 2.1.0.
Are there other ways that I can properly assign a name for the op_layer?
Thanks in advance,

redpajama_set_name: RedPajamaStackExchange


text:
Q: Large size Attachment upload auto-removed by Salesforce. Is it a bug? I've a Visualforce page that uploads multiple Attachments selected by user. I used following code to upload attachments:
...
<apex:repeat value="{!AttList}" var="att">
    <apex:inputFile value="{!att.Body}" filesize="{!att.BodyLength}" />
</apex:repeat>
...

Apex code:
public class AttachmentController {
    ...
    public list<Attachment> AttList { get;set; }
    public void UploadAtt() {
        try {
            for (Attachment a : AttList) {
                if (a.BodyLegnth > 5242880)
                     throw new CustomException('File size is larger than 5 MB');
            }
        }
        catch(Exception ex) {
            ApexPages.addMessages( ex );
        }
    }
    ...
}

But the Exception never gets thrown because salesforce automatically removes the file from the AttList variable, totally annoying behavior. This has been noticed for files larger than 5 MB.
Now, I tried something different and bind the inputFIle component to a wrapper class like this:
...
<apex:repeat value="{!AttList}" var="wrap">
    <apex:inputFile value="{!wrap.att.Body}" filesize="{!wrap.att.BodyLength}" />
</apex:repeat>
...

Apex code:
public class AttachmentController {
    ...
    public list<Attachment> AttList { get;set; }
    public void UploadAtt() {
        try {
            for (wAtt a : AttList) {
                Attachment a = w.att;
                if (a.BodyLegnth > 5242880)
                    throw new CustomException('File size is larger than 5 MB');
            }
        }
        catch(Exception ex) {
            ApexPages.addMessages( ex );
        }
    }
    ...
    class wAtt {
        public Attachment att { get;set; }
    }
}

Strangely this FIXES the bug to certain bit. So, now I can upload a file over 5 MB and now the error is trapped. And the Exception is thrown to user notifying that error has occurred while uploading the attachments.
This is a very strange issue. "Usually" one would expect if there is a limitation on platform, developer needs to trap it and handle it, but this time salesforce has taken that away from us and made it automatic. But this has raised a serious limitation such that how will user be notified why attachment has not been uploaded. It doesn't make sense to me if user has selected 5 attachments, and when I do insert the list, only 4 gets inserted but 1 failed "without" ever notifying the end user.
Now, even with this fix, it allows uploading of Attachment list with file over 5 MB and below 10 MB, and automatically ignore/remove any file that is larger than 10 MB by salesforce without getting trapped in Apex class code. It really is very bad.
Does anyone else have face this issue or have any permanent fix for this?

A: I really don't know how catch the uploaded file error using apex (server-side), but I've avoided that limitation using javascript (client-side) before the form is submitted in order to notify the user about the limitation.
This is an example:
    <apex:page standardController="document" >

        <apex:form styleClass="js-wrapp">
            <apex:inputFile value="{!document.body}" filename="{!document.name}"/ >
            <apex:commandButton value="Save" action="{!save}"/>
        </apex:form>

       <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"  />
       <script>

function getIEFileSize(file){
     var myFSO = new ActiveXObject("Scripting.FileSystemObject"),
    filepath = file.value,
    thefile = myFSO.getFile(filepath);
    return thefile.size;
}

   $(function(){
    $('form.js-wrapper').submit(function(){
        var isOk = true;
        $('input[type=file]').each(function(){
            if(typeof this.files[0] !== 'undefined'){
                var file = this.files[0],
                size = typeof ActiveXObject !== 'undefined' ?
                    getIEFileSize(file)
                    :
                    file.fileSize || file.size;

                isOk = 5242880 > size;
                if(!isOk){
                  alert(this.files[0].name +' file is bigger than 5MB');
                }

                return isOk;
            }
        });
        return isOk;
    });
   });

       </script>

</apex:page>

The script will work for any amount of file inputs checking all of them.

A: No, this is the way I have done it as well for custom file uploads.  They set the limits on the CRM for a reason.  I do wish some things were handled in a better way for developers but I think this solution for an apex page still holds true.


text:
Q: How to extract the web service method name in mule  I am working with mule <cxf:proxy-service> and need to extract the web service method name to attach to message for later use.
We've a service proxy class implementing Callable interface. Initially we tried to get operation name like this:
public Object onCall(MuleEventContext eventContext) throws Exception {
    try {
        MuleMessage inboundMessage = eventContext.getMessage();

        Set<String> props = inboundMessage.getInvocationPropertyNames();
        System.out.println("CXF invocation properties ==> " + props);
        System.out.println("CXF invocation property ==> " +  inboundMessage.getInvocationProperty("cxf_operation"));

but the above code gives incorrect operation name. (We've 4 operations in service and it always give the 2nd operation name). Below is the mule flow used for this:
<flow name="proxyService">
    <http:inbound-endpoint address="${some.address}"
        exchange-pattern="request-response">

        <cxf:proxy-service wsdlLocation="classpath:abc.wsdl"
            namespace="http://namespace"
            service="MyService">

        </cxf:proxy-service>
    </http:inbound-endpoint>
    <component class="com.services.MyServiceProxy" />

So, I resorted to write an inbound cxf interceptor to extract the operation name. I wrote below interceptor which works fine with <cxf:jaxws-service> but not with <cxf:proxy-service> element.
Here is my interceptor:
public class GetCXFOperation extends AbstractPhaseInterceptor<Message> {

public GetCXFOperation() {
    super(Phase.PRE_INVOKE);

}

@Override
public void handleMessage(Message message) throws Fault {
    Exchange exchange = message.getExchange();
    Endpoint ep = exchange.get(Endpoint.class);
    OperationInfo op = exchange.get(OperationInfo.class);
    if(op != null){
    System.out.println("Operation Name: " + op.getName().getLocalPart());
    } else{
         Object nameProperty = exchange.get("org.apache.cxf.resource.operation.name");
    if(nameProperty != null)

    System.out.println(nameProperty.toString());
    }

}

}
Seeking guidance as to how to extract operation name in <cxf:proxy-service>? Is there an easy mule way of getting correct answer? Or is there a different phase in which I should be invoking my interceptor? What phases work with <cxf:proxy-service>


text:
Q: Heroku complaining about sqlite3 after I already uninstalled it I am trying to push to heroku and I originally got an error message like:
Detected sqlite3 gem which is not supported on Heroku.
 !     https://devcenter.heroku.com/articles/sqlite3

So I replaced sqlite3 with heroku and now it still complains the same error message
Can someone help me out
Here is my gemfile and gemfile.lock
source 'https://rubygems.org'

gem 'rails', '3.2.13'
gem 'pg'
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'backbone-on-rails'

gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    actionmailer (3.2.13)
      actionpack (= 3.2.13)
      mail (~> 2.5.3)
    actionpack (3.2.13)
      activemodel (= 3.2.13)
      activesupport (= 3.2.13)
      builder (~> 3.0.0)
      erubis (~> 2.7.0)
      journey (~> 1.0.4)
      rack (~> 1.4.5)
      rack-cache (~> 1.2)
      rack-test (~> 0.6.1)
      sprockets (~> 2.2.1)
    activemodel (3.2.13)
      activesupport (= 3.2.13)
      builder (~> 3.0.0)
    activerecord (3.2.13)
      activemodel (= 3.2.13)
      activesupport (= 3.2.13)
      arel (~> 3.0.2)
      tzinfo (~> 0.3.29)
    activeresource (3.2.13)
      activemodel (= 3.2.13)
      activesupport (= 3.2.13)
    activesupport (3.2.13)
      i18n (= 0.6.1)
      multi_json (~> 1.0)
    arel (3.0.2)
    backbone-on-rails (1.0.0.0)
      eco
      ejs
      jquery-rails
      rails (>= 3.1)
    builder (3.0.4)
    coffee-rails (3.2.2)
      coffee-script (>= 2.2.0)
      railties (~> 3.2.0)
    coffee-script (2.2.0)
      coffee-script-source
      execjs
    coffee-script-source (1.6.3)
    eco (1.0.0)
      coffee-script
      eco-source
      execjs
    eco-source (1.1.0.rc.1)
    ejs (1.1.1)
    erubis (2.7.0)
    execjs (1.4.0)
      multi_json (~> 1.0)
    hike (1.2.3)
    i18n (0.6.1)
    journey (1.0.4)
    jquery-rails (3.0.4)
      railties (>= 3.0, < 5.0)
      thor (>= 0.14, < 2.0)
    json (1.8.0)
    mail (2.5.4)
      mime-types (~> 1.16)
      treetop (~> 1.4.8)
    mime-types (1.23)
    multi_json (1.7.7)
    pg (0.16.0)
    polyglot (0.3.3)
    rack (1.4.5)
    rack-cache (1.2)
      rack (>= 0.4)
    rack-ssl (1.3.3)
      rack
    rack-test (0.6.2)
      rack (>= 1.0)
    rails (3.2.13)
      actionmailer (= 3.2.13)
      actionpack (= 3.2.13)
      activerecord (= 3.2.13)
      activeresource (= 3.2.13)
      activesupport (= 3.2.13)
      bundler (~> 1.0)
      railties (= 3.2.13)
    railties (3.2.13)
      actionpack (= 3.2.13)
      activesupport (= 3.2.13)
      rack-ssl (~> 1.3.2)
      rake (>= 0.8.7)
      rdoc (~> 3.4)
      thor (>= 0.14.6, < 2.0)
    rake (10.1.0)
    rdoc (3.12.2)
      json (~> 1.4)
    sass (3.2.10)
    sass-rails (3.2.6)
      railties (~> 3.2.0)
      sass (>= 3.1.10)
      tilt (~> 1.3)
    sprockets (2.2.2)
      hike (~> 1.2)
      multi_json (~> 1.0)
      rack (~> 1.0)
      tilt (~> 1.1, != 1.3.0)
    thor (0.18.1)
    tilt (1.4.1)
    treetop (1.4.14)
      polyglot
      polyglot (>= 0.3.1)
    tzinfo (0.3.37)
    uglifier (2.1.2)
      execjs (>= 0.3.0)
      multi_json (~> 1.0, >= 1.0.2)

PLATFORMS
  ruby

DEPENDENCIES
  backbone-on-rails
  coffee-rails (~> 3.2.1)
  jquery-rails
  pg
  rails (= 3.2.13)
  sass-rails (~> 3.2.3)
  uglifier (>= 1.0.3)

Also heres my database.yml
development:
  adapter: postgresql
  encoding: unicode
  database: poster_development
  host: localhost

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: postgresql
  encoding: unicode
  database: poster_test
  host: localhost

production:
  adapter: postgresql
  encoding: unicode
  database: poster_production

A: Is the sqlite3 gem in the production group of your Gemfile?
If you're developing locally with sqlite3, then you probably want something like this in your Gemfile.
group :production do
  gem 'pg'
end

group :development, :test do
  gem 'sqlite3'
end

Don't forget to run bundle install


text:
Q: Highcharts JS showing wrong colors I'm trying to create a heatmap with values from -2 to 10.
I want:
-2 to be red
0 to be white
10 to be green
I tried this http://jsfiddle.net/m5xfx0wa/1/ but seems to not be working.
colorAxis: {

            stops: [
                [-2, '#ff0000'],
                [0, '#ffffff'],
                [10, '#00ff00']
            ],
            min: -2,
            max: 10
        },

Any ideas?

A: You have to understand the difference between the scale and the range. In your case, the scale used in stops is between 0 and 1 and your range is defined by the min and max.
So you should do something like:
stops: [
                [0, '#ff0000'],
                [0.2, '#ffffff'],
                [1, '#00ff00']
            ],


text:
Q: A book that I'm reading says I've lived is correct instead of I've been living in this sentence A) I've lived here since I was two years old.
B) I've been living here since I was two years old.
Someone please explain to me how is the second sentence incorrect here.


text:
Q: Is there a way to access the empathy roster via the user-menu? I am new to gnome shell (just upgraded my system from ubuntu 10.10 to 11.10 and manually installed gnome-shell) and I am looking for an efficient way to access the empathy roster.
The user-menu has an entry to toggle IM status, but I didn't find a way to access the roster from that menu. In gnome 2 the empathy roster was available by clicking on the chat-entry in the context menu of "Indicator Applet" ...
Is there a way to access the empathy roster via the user-menu?

A: With the empathy-menu extension I got exactly what I was looking for: It makes the empathy-roster accessible through a "Chat" entry in the user-menu.


text:
Q: Need to scale images to fit using XSL FO I am working on a project in which we have charts and a table exported to PDF.  We are using Apache FOP for the PDF generation.  The charts are in SVG and display fine if there's only one.  However, we will have cases in which there are up to four, and in these instances only three of the four are fitting on the generated PDF.  I need all images to fit regardless of number.  I'm afraid simply putting the page in landscape will be a temporary solution for when we need even more to fit.  The sizes of each chart are set in pixels from the svg generated in the client by the Highcharts library.  It appears as though the images are inserted into the pdf without any scaling, even though I set attributes for the instream-foreign-object per an example seen here: Scaling images using scale-to-fit
So I need each chart to "shrink to fit".  I have tried setting the length and width of the  element that encloses each  element that contains an instream-foreign object (I am also including my xsl).  Within the instream-foreign -object I am assigning the svg width & height to the values from the actual chart svg.  I thought maybe this was the problem, but if I don't include these dimensions the charts don't appear in the pdf.  I also tried setting the scaling attribute to "non-uniform" per the question here: Scale images with fixed height and the results were no better.  It actually stretched a chart across the whole page thus displaying only one of four. Here's my xsl:
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
    <fo:root>
    <fo:layout-master-set>
        <fo:simple-page-master master-name="exportPage">
            <fo:region-body />
            </fo:simple-page-master>
        </fo:layout-master-set>
        <fo:page-sequence master-reference="exportPage">
        <fo:flow flow-name="xsl-region-body">
            <fo:block id="mainTitleBlock" font-family="arial, helvetica, sans-serif" color="#5c068c" font-weight="bold">
                <xsl:value-of  select="exports/export/charts/@mainTitle"/>
            </fo:block>
            <fo:block id="timestampBlock" font-family="arial, helvetica, sans-serif" font-size="small" color="#6D869F">
                <xsl:value-of  select="exports/export/charts/@timeStamp"/>
            </fo:block>
            <!-- This is where the charts go -->
            <!-- Within this block will be an inline element for each chart-->
        <fo:block id="chartBlock" width="8.25in" height="6in">

          <xsl:apply-templates select="exports/export/charts/chart"/>

        </fo:block>
                <fo:block id="tableBlock" >
                    <xsl:apply-templates select="exports/export/table"/>
                </fo:block>
            </fo:flow>
            </fo:page-sequence>
         </fo:root>
</xsl:template>
   <!-- Creates the table -->
<xsl:template match="table">
<fo:table table-layout="fixed" width="100%" >
    <fo:table-header>
    <fo:table-row>
    <xsl:apply-templates select="tblRow[position() = 1]"/>
    </fo:table-row>
    </fo:table-header>
    <fo:table-body>
    <xsl:apply-templates select="tblRow[position() > 1]"/>
    </fo:table-body>
</fo:table>
</xsl:template>

<xsl:template match="hdrCell">
    <fo:table-cell background-color="#666" border-right-style="solid" border-right-width="1px" border-right-color="white" empty-cells="show">
    <fo:block color="white" font-family="arial, helvetica, sans-serif" font-size="x-small"><xsl:value-of select="."/></fo:block>
    </fo:table-cell>
</xsl:template>

<xsl:template match="tblCell">
    <fo:table-cell border-bottom-style="solid" border-bottom-width="1px" border-bottom-color="#E3E3E3" >
    <fo:block color="#7E7E7E" font-family="arial, helvetica, sans-serif" font-size="x-small"><xsl:value-of select="."/></fo:block>
    </fo:table-cell>
</xsl:template >

<xsl:template match="tblRow[position() > 1]">
    <fo:table-row>
    <xsl:apply-templates />
    </fo:table-row>
</xsl:template>

<xsl:template match="chart">
<fo:inline>
    <fo:instream-foreign-object xmlns:svg="http://www.w3.org/2000/svg" content-width="scale-to-fit" content-height="100%" width="100%" scaling="uniform">
    <svg:svg width="{svg:svg/@width}" height="{svg:svg/@height}">
    <xsl:copy-of select="svg:svg"/>
    </svg:svg>
    </fo:instream-foreign-object>
</fo:inline>
</xsl:template>

 </xsl:stylesheet>

What am I missing?  Would it help to display the charts in table-cells (thus breaking the convention of not using tables for layout- the horror!)?  How can I get these to scale and fit in the page?
Thanks,
Brandt

A: The scale property makes the chart fit in the containing block. If you haven't set dimensions for that block, the formatting engine won't know what size to scale to so it will use 100%.
I don't know what happens when you place more than one chart into one block.
You may need to put the charts in a table, one chart per column so you can set the column widths depending on the number of charts.


text:
Q: Como passo parâmetros pelo curl? Colegas,
estou reformulando minha pergunta. Tenho um cliente do qual preciso fazer uma integração de um outro site pelo dele. Estou usando o curl para isso. Porém ao invés do usuário usar o acesso do outro site, a integração faria com que o usuário ao se logar no nosso site, teria o acesso ao conteúdo do site dele, sem precisar se logar de novo. Estou usando o seguinte comando:
 // Inicia o cURL
$ch = curl_init();
// Define a URL original (do formulário de login)
$campos = array("login"=>$jmUsuario->email,"classroom_id"=>$jmUsuario->email,"sign"=>$sign);
$parametros = json_encode($campos);
curl_setopt($ch, CURLOPT_URL, 'http://www.siteX.com.br/api/auth/');
curl_setopt($ch, CURLOPT_POSTFIELDS, $parametros);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT,0);
curl_setopt($ch, CURLOPT_POST, 0);
$content = curl_exec($ch);
//$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $content;

A: Passo 1
Nesse trecho
$campos = array("login"=>$jmUsuario->email,"classroom_id"=>$jmUsuario->email,"sign"=>$sign);
$parametros = json_encode($campos);

Remova essa linha
$parametros = json_encode($campos);

Passo 2
Na linhacurl_setopt($ch, CURLOPT_POSTFIELDS, $parametros);
Troque porcurl_setopt($ch, CURLOPT_POSTFIELDS, $campos);
Explicação:
CURLOPT_POSTFIELDS espera um array ou uma string em formato url encoded.
Obs:
Isso pode não ser a solução do problema pois não está claro na pergunta onde está o problema.
Apesar disso, é uma sugestão para corrigir um erro visível.
Um outro problema no código que postou está nesse trecho
curl_setopt($ch, CURLOPT_POST, 0);

Presumo que os dados devem ser enviados pelo método POST devido ao parâmetro CURLOPT_POSTFIELDS, portanto, sugiro que modifique para
curl_setopt($ch, CURLOPT_POST, true);

Caso necessite seguir um redirecionamento, defina os seguintes parâmetros:
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // tempo em segundos
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // em segundos
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // true: permite redirecionamento
curl_setopt($ch, CURLOPT_MAXREDIRS, 1); // quantidade limite de redirecionamentos permitidos

Para mais opções, consulte a lista de parâmetros na documentação: http://php.net/manual/en/function.curl-setopt.php


text:
Q: How to add a new nodelet to a ROS nodelet manager located in a different package I'm new to ROS (and CMake, especially) and I've been searching for answers to this question for awhile.
First, I'm using ROS1 Noetic on Ubuntu 20.04 LTS
I am using a LiDAR sensor on my project, and I am using a ROS driver package provided by the manufacturer. Their package is written using nodelets: one nodelet acts as the driver/publisher and a second nodelet acts as a subscriber that assembles ROS bags.  I've written a nodelet source file of my own that does some processing on the data published by the LiDAR driver, and I'd like to patch this nodelet into the driver's nodelet manager.  I'd like to put this nodelet (and the others I'll be writing) in their own package, while keeping the manufacturer-provided code in its own, separate package.
I made my package and linked the manufacturer's package as a dependency, wrote my nodelet source file in the same namespace as the manufacturer's nodelets (#include'ing the library from the manufacturer's ROS package), made my nodelets.xml file, edited my package.xml to export the nodelets.xml file, tried to write an appropriate CMakeLists.txt file, and then created a .launch file to launch the manufacturer's manager/nodelets followed by my own nodelet.
When I run catkin_make, everything builds without throwing any errors, but when I try to run everything I get the following messages in the terminal:
process[rosout-1]: started with pid [14738]

started core service [/rosout]

process[cepton_manager-2]: started with pid [14745]

process[cepton_driver-3]: started with pid [14747]

process[cepton_subscriber-4]: started with pid [14748]

process[cepton_pruner-5]: started with pid [14750]

[ INFO] [1648137638.259213475]: Loading nodelet /cepton_driver of type cepton_ros/DriverNodelet to manager cepton_manager with the following remappings:

[ INFO] [1648137638.262238546]: waitForService: Service [/cepton_manager/load_nodelet] has not been advertised, waiting...

process[cepton_rviz-6]: started with pid [14755]

[ INFO] [1648137638.289473532]: Loading nodelet /cepton_subscriber of type cepton_ros/SubscriberNodelet to manager cepton_manager with the following remappings:

[ INFO] [1648137638.293830600]: Initializing nodelet with 4 worker threads.

[ INFO] [1648137638.295997429]: waitForService: Service [/cepton_manager/load_nodelet] has not been advertised, waiting...

[ INFO] [1648137638.297265577]: Loading nodelet /cepton_pruner of type vt_cepton/PrunerNodelet to manager cepton_manager with the following remappings:

[ INFO] [1648137638.304628562]: waitForService: Service [/cepton_manager/load_nodelet] is now available.

[ INFO] [1648137638.318009289]: waitForService: Service [/cepton_manager/load_nodelet] is now available.

[ERROR] [1648137638.323951769]: Failed to load nodelet [/cepton_pruner] of type [vt_cepton/PrunerNodelet] even after refreshing the cache: Failed to load library /home/autodrive/catkin_ws/devel/lib//libvt_cepton.so. Make sure that you are calling the PLUGINLIB_EXPORT_CLASS macro in the library code, and that names are consistent between this macro and your XML. Error string: Could not load library (Poco exception = /home/autodrive/catkin_ws/devel/lib//libvt_cepton.so: undefined symbol: _ZN3pcl7PCLBaseIN10cepton_sdk4util11SensorPointEE13setInputCloudERKN5boost10shared_ptrIKNS_10PointCloudIS3_EEEE)

[ERROR] [1648137638.324030872]: The error before refreshing the cache was: Failed to load library /home/autodrive/catkin_ws/devel/lib//libvt_cepton.so. Make sure that you are calling the PLUGINLIB_EXPORT_CLASS macro in the library code, and that names are consistent between this macro and your XML. Error string: Could not load library (Poco exception = /home/autodrive/catkin_ws/devel/lib//libvt_cepton.so: undefined symbol: _ZN3pcl7PCLBaseIN10cepton_sdk4util11SensorPointEE13setInputCloudERKN5boost10shared_ptrIKNS_10PointCloudIS3_EEEE)

[FATAL] [1648137638.324638370]: Failed to load nodelet '/cepton_prunerof typevt_cepton/PrunerNodeletto managercepton_manager'

[ INFO] [1648137638.333213726]: [/cepton_driver] cepton_sdk 1.18.2

[cepton_pruner-5] process has died [pid 14750, exit code 255, cmd /opt/ros/noetic/lib/nodelet/nodelet load vt_cepton/PrunerNodelet cepton_manager __name:=cepton_pruner

As you can see, the manufacturer's manager and driver load as expected, but I have trouble attaching my nodelet to the manufacturer's manager.


text:
Q: Django get data of object from ManyToManyField form Hello i created this form :
class CartForm(ModelForm):
 class Meta:
     model = Cart
     fields =( 'products',)

from theses models :
class Product(models.Model):
 title = models.CharField("Titre", max_length=120)
 subtitle = models.CharField("Sous-titre", max_length=250)
 description = models.TextField("Description")
 picture = models.ImageField(upload_to='objects/')
 enabled = models.BooleanField("Activé")

class Cart(models.Model):
 products = models.ManyToManyField(Product)

and i want to display on my template an list of choice with their data
So i send form from views but i don't find any way to get the products description i only get their names !
here is my view :
def home(request):
 categories = Category.objects.annotate(test=Count('product')).filter(test__gt=0)
 # categories = Category.objects.order_by(
 #     'id')
 test = CartForm()
 return render(request, 'boutique.html', {"categories": categories, "test":test})

and what i tried in my template :
    {% for ee in test.products %}
        {{ ee.description }}
        <br />
    {% endfor %}

please help me
have a nice day

A: Ok so theres a couple issues here:
First of all you actually need to define what is gonna happen when you submit the form, so in your view do this:
views.py
def home(request):
 categories = Category.objects.annotate(test=Count('product')).filter(test__gt=0)
 if request.method == 'POST':
     test = CartForm(request.POST)
     if form.is_valid():
         cart = form.save(commit=False)
         for product in request.POST.getlist('products'):
             cart.add(product)
     else:
         pass
  else:
      form = CartForm()
 return render(request, 'boutique.html', {"categories": categories, "test": test})

then in your template you actually have to render the form (test):
boutique.html
<form method="post">
    {% csrf_token %}
    {{ test.as_p }}
    <button type="submit"> Add Items </button>
</form>

Now you should see the list of products in template.
edit
if you want to show a different model field in your form rewrite its __str__ method like this:
def __str__(self):
    return self.description # to show description


text:
Q: Lodash union of arrays of mongoose ObjectId I have 2 arrays that containing ObjectId items: array1 array2
I want to create a union between those 2 arrays. for that i'm running:
let res = _.union(array1, array2);

But res contains duplicates ObjectId.
How can i solve this?

A: You could try using _.uniqBy(res, 'ObjectId'); That should remove duplicate objectId in your new res array
let newRes = _.uniqBy(res, 'ObjectId');

A: If you're looking at two different arrays with strings of 'objectIDs' you can use concat and then uniq to remove the duplicates. Don't forget to run valueOf at the end of your Lodash chain to call it to execute.
Below is an illustrative example:

let array1 = ['42142141221421d', '9999'];

let array2 = ['s421421412412fef3', '42142141221421d', '1234'];

const res = _(array1)
       .concat(array2)
       .uniq()
       .valueOf();

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


text:
Q: How to create a Page View Controller like Instagram homepage that also scrolls Tab Bar? I want to create a home page like Instagram, that scrolls vertically (with a Navigation Controller, Tab Bar Items, ...) to another View Controller. For example when I swipe left from Instagram home page, it will scroll to direct messages with another Tab Bar Item and the Tab Bar also moves left and is replaced with a new Tab Bar in direct messages View Controller.

I tried to use UIPageViewController but because I use a Tab Bar, when I start scrolling, the Tab Bar remains in its place. How can I achieve the desired behavior?

A: Since you mentioned that the Tab Bar remains in place even when swiping horizontally, I believe your View Controller hierarchy looks something like this:
UITabBarController
└── UIPageViewController
    ├── UIViewController1
    ├── UIViewController2
    ├── .
    ├── .
    ├── .

But you need to put Tab Bar Controller inside the Page View Controller, so your View Controller hierarchy would become like this:
UIPageViewController
└── UITabBarController
    ├── UIViewController1
    ├── UIViewController2
    ├── .
    ├── .
    ├── .

A: You could try using a UIPageViewController as before, and having each of your pages be a UITabViewController with your views being nested in the tabviewcontroller.


text:
Q: Fundamental group of mapping cone of quotient map from suspension to reduced suspension Update:
Thanks to Paul Frost, I realized there were mistakes in the question and my former proof. I moved the former proof to my answer below and modified the question.

This is exercise 1.2.18(b) in page 55-56 of Hatcher's book Algebraic topology.
In this question: $X=\{0,1,\frac{1}{2}, \frac{1}{3},\cdots\}$, $SX$ is suspension and $\Sigma X$ is reduced suspension, where the suspension $SX$ is the quotient of $X\times I$ obtained by collapsing $X\times\{0\}$ to one point and $X\times\{1\}$ to another point and reduced suspension $\Sigma X$ is obtained from $SX$ by collapsing the segment $\color{blue}{\{0\}\times I}$.
Note: Reduced suspension depends on the choice of basepoint.
In this question, if we obtain reduced suspension from $SX$ by collapsing the segment $\{0\}\times I$, we get Hawaiian earring/The Shrinking Wedge of Circles in figure (4).
If we obtain reduced suspension from $SX$ by collapsing the segment $\{1\}\times I$, we get a space in figure (3) which is homotopy equivalent to $SX$.

Question:
Let $C$ be the mapping cone of the quotient map $SX→ΣX$.
Show that $π_1(C)$ is uncountable by constructing a homomorphism
from $π_1(C)$ onto $∏_∞ \mathbb Z/\bigoplus_∞ \mathbb Z$.

Thanks for your time and effort.

A: You seem to claim that $SX$ is homotopy equivalent to the second space in your picture (which I shall denote by $S'X \subset \mathbb R^2$). This is not true. The yellow circle does not belong to $S'X$, thus $S'X$ is not compact. If you have any map $f : SX \to S'X$, then its image is compact and therefore must be contained in some $S'_n = \bigcup_{i=1}^n A_i$. This is a finite wedge of circles. We have $f = i_n f_n$ where $f_n : SX \to S'_n$ is the restriction of $f$ and $i_n : S'_n \to S'X$ denotes inclusion. If $g : S'X \to SX$ would be a homotopy inverse of $f$, then the identity on $\pi_1(SX)$ would factor through $\pi_1(S'_n)$ which is false.
However, there is no reason to replace $SX$ by another space. By the way, note that $\Sigma X$ is known as the Hawaiian earring. In Hatcher's Example 1.25 it is denoted as "The Shrinking Wedge of Circles".
As basepoint for $SX$ choose the midpoint $x_0$ of the black line segment and as basepoint for $\Sigma X$ choose the cluster point $y_0$ of the circles $B_i$. We have obvious pointed retractions $r_i : SX \to A_i$ (which project $A_j$ to the black line segment for $j \ne i$) and $s_i : \Sigma X \to B_i$ (which map $B_j$ to $y_0$ for $j \ne i$). This gives us group homomorphisms
$$\phi : \pi_1(SX,x_0) \to \prod_{i=1}^\infty \pi_1(A_i,x_0) = \prod_{i=1}^\infty \mathbb Z, \phi(a) = ((r_1)_*(a), (r_2)_*(a),\ldots),$$
$$\psi : \pi_1(\Sigma X,y_0) \to \prod_{i=1}^\infty \pi_1(B_i,y_0) = \prod_{i=1}^\infty \mathbb Z, \psi(b) = ((s_1)_*(b), (s_2)_*(b),\ldots) .$$
It is easy to see that $\psi$ is surjective, but $\phi$ is not. In fact, $\text{im}(\phi) = \bigoplus_{i=1}^\infty \mathbb Z$. This is true because all but finitely many $(r_i)_*(a)$ must be zero (otherwise the path representing $a$ would run infinitely many times through both endpoints of the black line segment, thus would have infinite length).
Obviously we have $\psi \circ q_* = \phi$, where $q : SX \to \Sigma X$ is the quotient map.
Now let us apply van Kampen's theorem. Write $C = U_1 \cup U_2$, where $U_1$ is obtained from $C$ by removing the tip of mapping cone and $U_2$ by removing the base $\Sigma X$. Both $U_k$ are open in $C$. We have

*

*$U_1 \cap U_2 \approx SX \times (0,1) \simeq SX$ (thus $U_1 \cap U_2$ is path connected)

*$U_1 \simeq \Sigma X$ (in fact, $\Sigma X$ is a strong defornation retract of $U_1$)

*$U_2$ is contractible.
We conclude that $\Phi : \pi_1(U_1) * \pi_1(U_2) = \pi_1(\Sigma X) * 0 = \pi_1(\Sigma X) \to  \pi_1(C)$ is surjective. Its kernel $N$ is the normal subgroup generated by the words of the form $(i_1)_*(c)(i_2)_*^{-1}(c)$, where $i_k : U_1 \cap U_2 \to U_k$ denotes inclusion and $c  \in \pi_1(U_1 \cap U_2)$. Since $(i_2)_*^{-1}(c) = 0$, we see that $N$ is the normal closure of the image of the map $(i_1)_* : \pi_1(U_1 \cap U_2) \to \pi_1(U_1)$. But under the identifications $U_1 \cap U_2 \simeq SX$ and $U_1 \simeq \Sigma X$ we see that $(i_1)_*$ corresponds to $q_* : \pi_1(SX) \to \pi_1 (\Sigma X)$.
Hence $\pi_1(C) \approx \pi_1 (\Sigma X)/ N'$, where $N'$ is the normal closure of $\text{im}(q_*)$.
The surjective homomorphism $\psi' : \pi_1(\Sigma X)  \stackrel{\psi}{\rightarrow} \prod_{i=1}^\infty \mathbb Z \to \prod_{i=1}^\infty \mathbb Z / \bigoplus_{i=1}^\infty \mathbb Z$ has the property $\psi' \circ q_*  = 0$, thus $\text{im}(q_*) \subset \ker(\psi')$. Since $\ker(\psi')$ is a normal subgroup, we have $N' \subset \ker(\psi')$, thus $\psi'$ induces a surjective homomorphism $\pi_1(C) \approx \pi_1 (\Sigma X)/ N' \to \prod_{i=1}^\infty \mathbb Z / \bigoplus_{i=1}^\infty \mathbb Z$.

A: Your construction of $\varphi$ looks right to me (in the sense that I think it could appear in a full proof). I don't think you have sufficiently proven that it is well-defined. I think this is the tricky part you felt you were missing.
I think you could perhaps add a few more words as to why the paths you use to show $\varphi$ is surjective are not contractible.
Edit:
The question changed. I feel like it's a bit confused and it's not really at all clear to me that $\varphi$ is well-defined. I feel like there's too much if $x$ then $y$ otherwise $z$ (especially as sometimes this is used to split up cases and sometimes for an argument by contradiction). Perhaps a better way to structure this would be as follows:

*

*Define the function $\psi$ mapping $\pi_1(\Sigma X)$ to $\prod_\infty \Bbb Z$

*Show that it is a well-defined surjective homomorphism

*Let $r : \prod_\infty\Bbb Z\to  \prod_\infty\Bbb Z/\bigoplus_\infty\Bbb Z$ be the quotient map

*Prove that $r\psi$ may be extended to a well-defined homomorphism $\phi : \pi_1(C_q)\to  \prod_\infty\Bbb Z/\bigoplus_\infty\Bbb Z$.

*You get surjectivity from step 2

But actually I feel like you should be able to use some theorem for this instead. The theorem I am imagining is one which would say something like $\pi_1(C_q) = \pi_1(\Sigma X)/\pi_1(SX)$ and then you need the theorem from groups that a homomorphism $f: G \to H$ induces a homomorphism $G/N \to G/f(N)$. Maybe you don't have that theorem but do you have Seifert-van Kampen yet? Maybe you could use that to your advantage here.

Edit 2:
I looked up the exercise in Hatcher. The exercise is in the first block after the proof and statement of van Kampen's theorem (which I have perhaps confusingly referred to as Seifert-van Kampen). I think the exercise wants you to use the theorem. You should take one set to be $\Sigma X$ plus the mapping cylinder of $q,$ and the other to be $CSX$, so the intersection is $S X$. My guess is that the point of the exercise is practicing van Kampen's theorem (and I guess a bit about how it relates to mapping cones and these spaces).

A: Alternative method:
Let $U=C(SX)$, $V$ be mapping cylinder of $q$, $V=SX \times I \sqcup \Sigma X /\sim$, i.e. $(x,1)\sim q(x)$ for $x\in SX$.
Let $W$ to be space by gluing $U$ and $V$ along $SX$.
$V$ deformation retracts to $\Sigma X$, so $C_q=\Sigma X \cup_q C(SX) \simeq W$.
$\pi_1(U)=0$. Let $i_1: SX \hookrightarrow C(SX)=U$, $i_2: SX \hookrightarrow V$.
$i_{1*}=0$, $i_{2*}:\pi_1(SX)\to\pi_1(V)\cong\pi_1(\Sigma X)$.
From van Kampen's theorem, $\pi_1(W)\cong\pi_1(U)*\pi_1(V)/N$, $N$ is generated by $i_{1*}(w)i_{2*}(w^{-1})$ for all $w\in \pi_1(SX)$. $\pi_1(W)\cong \pi_1(\Sigma X)/\pi_1(SX)$.
Let $\rho$ be the surjective homomorphism $\pi_1(\Sigma X) \to \prod_\infty \mathbb Z$ given in page 49 of Hatcher.
$\color{red}{\text{$\rho$ maps $\pi_1(SX)$ to $\bigoplus_\infty \mathbb Z$}  \ (*) }$ , so $\rho$ induces a surjective homomorphism
$\pi_1(\Sigma X)/\pi_1(SX) \to \prod_\infty \mathbb Z/\bigoplus_\infty \mathbb Z$. $\quad\Box$
Claim $(*)$ in red is remained to check.
I tried to give an explicit expression of $\rho$ to prove claim $(*)$ in the question, but I couldn't fully prove the well-defineness of the $\rho$ I constructed.

My former proof (wrong):

$1$. Yellow circle doesn't belong to $SX$. It means the lower bound of circles in $SX$.
Circles in $\Sigma X$ have no such lower bound. Region containing "$\cdots$" means there're countably many circles in it.
From outside to inside, circles in $SX$ and $\Sigma X$ are denoted by $A_n$ and $B_n$ with common point $x_0$ and $y_0$.
Quotient map is $q:SX \to \Sigma X$, mapping cone $C_q=\Sigma X \cup_q CSX$.
$2$. Choose basepoint of loops at $x_0\sim y_0$. $A_i\sim B_i$, so loop around $A_i$ can be considered as loop around $B_i$.
For $[f]\in \pi_1(C_q)$, if $f$ wraps $a_n$ times around circle $B_n$ clockwise, let $\tilde f: I \to SX$ wrap $a_n$ times around circle $A_n$ clockwise the same ways as $f$. Note that $q \circ\tilde f=f$.
Define $\varphi: \pi_1(C_q)\to \prod_\infty \mathbb Z/\bigoplus_\infty \mathbb Z,\ [f]\mapsto \overline{(a_n)_{n=1}^{\infty}}$.
$3$. If $(a_n)_{n=1}^{\infty} \in \bigoplus_\infty \mathbb Z$, then only finite $a_n$ is nonzero and $\tilde f$ is continuous on $I$, so $\tilde f$ is indeed a loop in $C_q$.
$[\tilde f]=[q\circ \tilde f]=[f]$. Note that $A_n\subset SX \subset CSX$ is contractible, so $[\tilde f]=0=[f]$, $f$ is nullhomotopic. $\pi_1([f])=\overline 0$.
This is consistent with $\overline{(a_n)_{n=1}^{\infty}}=\overline 0$ in $\prod_\infty \mathbb Z/\bigoplus_\infty \mathbb Z$.
If $(a_n)_{n=1}^{\infty} \in \prod_\infty \mathbb Z - \bigoplus_\infty \mathbb Z$, then $\tilde f$ is not continuous at $1$, so it's not a loop in $SX$ and $\color{red}{\text{ $f$ isn't nullhomotopic}}$.
$3$. $\varphi: \pi_1(C_q)\to \prod_\infty \mathbb Z/\bigoplus_\infty \mathbb Z$ is well-defined.
If $[f]=[g]$ in $\pi_1(C_q)$, $f, g$ wraps $a_n, b_n$ times around circle $B_n$ clockwise, then $f\circ g^{-1}$ wraps $a_n - b_n$ times around circle $B_n$ clockwise.
$f\circ g$ is nullhomotopic, so $(a_n-b_n)_{n=1}^\infty\in \bigoplus_\infty \mathbb Z$.
$\varphi([f])=\overline{(a_n)_{n=1}^{\infty}}=\overline{(a_n-b_n+b_n)_{n=1}^{\infty}}=\overline{(a_n-b_n)_{n=1}^{\infty}}+\overline{(b_n)_{n=1}^{\infty}}=\overline{(b_n)_{n=1}^{\infty}}=\varphi([g])$.
$\varphi$ is a well-defined surjective homomorphism. $\quad\Box$


text:
Q: Displaying system information on Gnome 3 desktop I am looking for some extension which will display all system information such as CPU usage, temperature, Internet usage, running processes etc.
I would like to see all of the output continuously updated on my desktop. I run Ubuntu 12.04 64-bit with Gnome 3
I know there are Gnome 3 extensions, but most of them (at least what I checked) display only some information on the bar. I am looking for complete set of possible informations and displaying them as a desktop background
Does anyone know something like that?

A: This conky tutorial is pretty good: Install Conky Lua On Ubuntu. It's quoted here to avoid link rot:

First of all we need to install conky, you can do that by:
sudo apt-get install conky

Secondly download conky-lua from here
Then, go to the directory where you have downloaded the Conky-lua zip
  file and extract it. All files will be extracted in a folder called
  Conky-lua.

Go to the folder and pick a file and extract it depending upon your
  distribution. As I use Ubuntu desktop, I extracted the file Conky
  ubuntu-lua.tar.gz.
This will be extracted in a folder called Conky ubuntu-lua. Go to
  the directory, find the file conkyrc, and rename it to .conkyrc.
  Make sure you have put the dot(.) at the beginning of the file.

Now, move the renamed file .conkyrc to your home directory. Hence,
  we have put the dot(.) at the beginning, this file will not be
  visible. To make sure this file is moved to the home directory, go to
  View -> Show Hidden files in your file manager.
Then, create a new folder called .conky in the home directory, and
  copy the other 2 files to this folder (new-ubuntu-logo.png and
  clock_rings.lua).
Now we have to mention the actual path of clock_rings.lua file in
  the .conkyrc file. Open the file .conkyrc in any text editor,
nano ~/.conkyrc

Find the line and change the path to the new one in the home folder.:
lua_load /~.lua/scripts/clock_rings.lua

And, change it to:
lua_load ~/.conky/clock_rings.lua

Save and close the file. We're done. Open terminal and run conky using
  the following command:
conky -c ~/.conkyrc &

Now, look at your Ubuntu desktop. The conky-lua theme will be running
  and displaying all details such as date and time, usages of CPU, RAM,
  net, disk and swap etc.

(All images courtesy of https://www.unixmen.com)


text:
Q: No trait inferred from structs that implement a trait in Rust? I have 2 structs, both implement a trait:
pub trait TFilter {
    fn getText(&self) -> String;
}

pub struct CommentFilter {
    comment: String
}

impl TFilter for CommentFilter {
    fn getText(&self) -> String {
        return self.comment;
    }
}

impl CommentFilter {
    pub fn from_text(context: &Context, text: String) -> Self {
        return CommentFilter {
            comment: text
        }
    }
}

// ---

pub struct RegExpFilter {
    text: String
}

impl RegExpFilter {
    pub fn from_text(context: &Context, text: String) -> Self {
        return RegExpFilter {
            text
        }
    }
}

impl TFilter for RegExpFilter {
    fn getText(&self) -> String {
        return self.text
    }
}

But when trying to compile the code:
      let filter: dyn TFilter = if text.chars().nth(0).unwrap() == '!' {
                CommentFilter::from_text(context, text);
            } else {
                RegExpFilter::from_text(context, "test".to_string());
            };

i get an error:
error[E0308]: mismatched types
   --> src/filter.rs:113:20
    |
113 |               } else {
    |  ____________________^
114 | |                 RegExpFilter::from_text(context, "test".to_string());
115 | |             };
    | |_____________^ expected trait object `dyn filter::TFilter`, found `()`

What's wrong?
PS1. I found ; actually hurt, but now i'm getting:

expected trait object dyn filter::TFilter, found struct filter::CommentFilter

Can't it detect they actually implement the trait?
PS2. I had to explicitly specify : dyn TFilter as otherwise the compiler infers it from the first if branch and detected as CommentFilter (which obviously does not work for the negative branch).

A: Try without the semicolons:
      let filter: dyn TFilter = if text.chars().nth(0).unwrap() == '!' {
            CommentFilter::from_text(context, text)
        } else {
            RegExpFilter::from_text(context, "test".to_string())
        };

A: Since the compiler does not know the size of TFilter you need to store it on the heap wrapped in a Box like this:
      let filter: Box<dyn TFilter> = if text.chars().nth(0).unwrap() == '!' {
            Box::new(CommentFilter::from_text(context, text))
        } else {
            Box::new(RegExpFilter::from_text(context, "test".to_string()))
        };


text:
Q: Problems connecting Cloud Run Application to Cloud SQL using Spring boot I am trying to connect a Spring application (using Kotlin and Gradle) to a Google Cloud SQL instance and database. I am getting the error message
java.lang.RuntimeException: [<project-name>:europe-west1:<db-instance>] The Cloud SQL Instance does not exist or your account is not authorized to access it. Please verify the instance connection name and check the IAM permissions for project "<project-name>"

I have followed the guide on how to connect carefully, but to no avail.
Relevant files
src/main/resources/application.yml
server:
  port: ${PORT:8080}

spring:
  liquibase:
    change-log: classpath:liquibase/db.changelog.xml
    contexts: production

  cloud:
    appId: <project-id>
    gcp:
      sql:
        instance-connection-name: <instance-connection-name>
        database-name: <db-name>
  jpa:
    hibernate:
      dialect: org.hibernate.dialect.MySQL8Dialect
      default_schema: <schema>
      show_sql: true
      ddl-auto: none

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    continue-on-error: true
    initialization-mode: always
    url: jdbc:mysql:///<db-name>?cloudSqlInstance=<instance-connection-name>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=<user>&password=<password>
    username: <user>
    password: <password>

---
spring:
  config:
    activate:
      on-profile: dev

  jpa:
    hibernate:
      ddl-auto: create-drop
    spring.jpa.database-platform: org.hibernate.dialect.H2Dialect

  datasource:
    url: jdbc:h2:mem:mydb
    username: sa
    password: password
    driverClassName: org.h2.Driver

  cloud:
    gcp:
      sql:
        enabled: false

build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
        id("org.springframework.boot") version "2.6.5"
    id("io.spring.dependency-management") version "1.0.11.RELEASE"
    kotlin("jvm") version "1.6.10"
    kotlin("plugin.spring") version "1.6.10"
    kotlin("plugin.allopen") version "1.4.32"
    kotlin("plugin.jpa") version "1.4.32"
    kotlin("kapt") version "1.4.32"
}

allOpen {
    annotation("javax.persistence.Entity")
    annotation("javax.persistence.Embeddable")
    annotation("javax.persistence.MappedSuperclass")
}

group = "com.<company>"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17

repositories {
    mavenCentral()
}

dependencies {

    implementation("org.springframework.boot:spring-boot-starter-web:2.6.5")
    implementation("org.springframework.boot:spring-boot-starter-webflux:2.6.5")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa:2.6.5")
    implementation("org.springframework.cloud:spring-cloud-gcp-starter-sql-mysql:1.2.8.RELEASE")

    implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.10")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.10")

    implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.13.2")
    implementation("com.fasterxml.jackson.core:jackson-annotations:2.13.2")
    implementation("com.fasterxml.jackson.core:jackson-core:2.13.2")
    implementation("com.fasterxml.jackson.core:jackson-databind:2.13.2.2")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.2")
    implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.2")

    implementation("org.hibernate:hibernate-core:5.6.7.Final")
    implementation("javax.persistence:javax.persistence-api:2.2")

    implementation( "commons-codec:commons-codec:1.15")

    implementation("io.github.microutils:kotlin-logging-jvm:2.1.21")
    implementation("ch.qos.logback:logback-classic:1.2.11")

    implementation("com.google.cloud.sql:mysql-socket-factory-connector-j-8:1.4.4")
    runtimeOnly("com.h2database:h2:2.1.210")
    runtimeOnly("org.springframework.boot:spring-boot-devtools:2.6.5")

    testImplementation("org.springframework.boot:spring-boot-starter-test:2.6.5")
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "17"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

Dockerfile
FROM openjdk:17-alpine
ENV USER=appuser
# <placeholder> Replace context path for your own application
ENV JAVA_HOME=/opt/openjdk-17 \
    HOME=/home/$USER \
    CONTEXT_PATH=/aws-service-baseline

RUN adduser -S $USER
# <placeholder> Add additional packages for the docker container here
RUN apk add --no-cache su-exec

# <placeholder> Replace baseline.jar with your applications JAR file (defined in build.gradle.kts)
COPY Docker/runapp.sh build/libs/<application-name>-0.0.1-SNAPSHOT.jar $HOME/
RUN chmod 755 $HOME/*.sh && \
    chown -R $USER $HOME

WORKDIR /home/$USER
CMD [ "./runapp.sh"]

Docker/runapp.sh
#!/bin/sh
set -e

# The module to start.
# <placeholder> Replace this with your own modulename (from module-info)
APP_JAR="<application-name>-0.0.1-SNAPSHOT.jar"
JAVA_PARAMS="-XshowSettings:vm"

echo " --- RUNNING $(basename "$0") $(date -u "+%Y-%m-%d %H:%M:%S Z") --- "
set -x

/sbin/su-exec "$USER:1000" "$JAVA_HOME/bin/java" "$JAVA_PARAMS $JAVA_PARAMS_OVERRIDE" -jar -Dserver.port=$PORT "$APP_JAR"

GCP details
I have made sure the SQL instances connection is added to the Cloud Run Revisions. The IAM roles for the compute service account also seem to be right. See images
IAM: https://i.stack.imgur.com/yYaC5.png
Database: https://i.stack.imgur.com/NErad.png
Cloud Run connection https://i.stack.imgur.com/fKTSZ.png
Additional details
When running ./gradlew bootRun on my local machine (with GCP credentials present), the App works properly with an SQL connection. It also works after running ./gradle bootRun to build the JAR file and run the JAR directly. It does not work out of the box when running in Docker, but if I add the GCP credentials to the Docker container locally, it connects to the Database.
Does anyone have any suggestions on what might be wrong? Any help much appreciated!
I have tried connecting locally and locally in a Docker container.

A: Figured it out! Human error of course. The Cloud Run Service was initially configured with another Services Account, and not the default Compute Engine Service account.


text:
Q: Linq: Get rows where values exists in another table I have two tables in my database:
TableA:
Id, ColA, ColB, Value   IsSelectable
1   A     B     value1  False
2   C     D     value2  True
3   K     M     value3  True

TableB:
Id, ColA, ColB
1   A     B
2   K     M

Now I want to create a Linq query that select all rows from TableA that are: IsSelectable = true and where ColA equals ColA in TableB AND ColB equals ColB in TableB.
In above example I would like to return row # 3 as this is the only one that fullfills my requirements.
I have tried this:
from ta in _db.TableA
from tb in _db.TableB
where ta.IsSelectable == true
&& (ta.ColA == tb.ColA && ta.ColB == tb.ColB)
select ta;

Problem with above query is that the query times out if I tries to show its values in the debugger.
I have also tried to join the two tables where I join TableA to TableB. But when trying to select TableA from the joined result, I cannot create a new TableA record, as my Id is database created and has no setter.
How can I do this?

A: Try this
from ta in _db.TableA
from t in _db.TableB on new {a=ta.ColA,b=ta.ColB} equals new{a= t.ColA,b=t.ColB}
into tc from tb in tc
where ta.IsSelectable == true
select ta;


text:
Q: Difference between graph neural network and graph convolutional network Which characteristics my neural network (NN) model should have to be considered as a graph convolutional network (GCN) instead of a graph neural network (GNN)? I know that GCN is a variant of GNN, but what is the difference between these two types of NNs?

A: I think it's a reasonable claim that all graph convolutional networks are graph neural networks, since they operate on graphs, and are NNs. However, there are graph neural networks which don't use graph convolutions.
For example, graphRNN is a generative neural network for graphs where an RNN is given all the previous nodes and edges, and decides whether or not to add a new node/edges to the existing graph, or to terminate the generation process.


text:
Q: Jersey Client with Apache connector for pooling (performance) We have a jersey client, with the basic config:
public class HttpClient {

    private transient final WebTarget target;

    public HttpClient(final String host, final int port, final String path, final int requestTimeout) {
        final URI uri = UriBuilder.fromUri("http://" + host).port(port).build();
        final Client client = ClientBuilder.newClient();

        client.property(ClientProperties.READ_TIMEOUT, requestTimeout);
        target = client.target(uri).path(path);
    }

    public byte[] makeRequest(final byte[] request) throws HsmException {
        try {
            return target.request()
                    .accept(MediaType.APPLICATION_OCTET_STREAM)
                    .post(Entity.entity(request, MediaType.APPLICATION_OCTET_STREAM), byte[].class);
        }
        catch (Exception e) {
            // Box JAX-RS exceptions as they get weirdly handled by the outer Jersey layer.
            throw new Exception("Could not make request: " + e.getMessage(), e);
        }
    }

}

Now, with that client, we manage to make around 900 requests per second. So in my attempt to get better results I thought about implementing pooling, using Apache Http client with the jersey connector, like this:
public class HttpClient {
    private transient final WebTarget target;

    public HttpClient(final String host, final int port, final String path, final int requestTimeout) {
        final ClientConfig clientConfig = new ClientConfig();
        clientConfig.property(ClientProperties.READ_TIMEOUT, requestTimeout);
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 500);

        final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(150);
        connectionManager.setDefaultMaxPerRoute(40);
        connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost(host)), 80);

        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);

        final ApacheConnectorProvider connector = new ApacheConnectorProvider();
        clientConfig.connectorProvider(connector);

        final URI uri = UriBuilder.fromUri("http://" + host).port(port).build();
        final Client client = ClientBuilder.newClient(clientConfig);
        target = client.target(uri).path(path);
    }

    @Override
    public byte[] makeRequest(final byte[] request) throws HsmException {
        try {
            return target.request()
                    .accept(MediaType.APPLICATION_OCTET_STREAM)
                    .post(Entity.entity(command, MediaType.APPLICATION_OCTET_STREAM), byte[].class);
        }
        catch (Exception e) {
            // Box JAX-RS exceptions as they get weirdly handled by the outer Jersey layer.
            throw new Exception("Could not make request:" + e.getMessage(), e);
        }
    }
}

And the results are exactly the same, about 900 requests per second.
I am not being limited by CPU, ram, disk, etc. I can't find the bottleneck. I tested multiple values when setting the connection manager but with the exact same results.
Am I missing something? Are there any other parameters I am missing? Am I using this the wrong way?

A: You can try HTTP connection pooling with httpasyncclient instead.
The httpclient uses thread-blocking I/O for connection pool, which means that the thread responsible for sending the HTTP request is also responsible for handling the HTTP response as well. In the meantime, the thread remains blocked on the socket.
In contrast, the httpasyncclient is a fully asynchronous HTTP client side handler based on the Java NIO (non-blocking) I/O model which allows library users to stream message content from a non-blocking HTTP connection.


text:
Q: Why could not access Session using asp.net web api? In my ASP.NET Web API project, i could access Session object in local (both debug and release model).
But when i deploy it to the server, it doesn't work.
Global.asax
public override void Init()
{
    this.PostAuthenticateRequest +=MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

UserApiController.cs
    [HttpGet]
    public string GetVerificationCode(string mobileNumber)
    {
        if (!string.IsNullOrWhiteSpace(mobileNumber) &&
             Regex.Match(mobileNumber, @"^1\d{10}$", RegexOptions.IgnoreCase).Success)
        {
            string VerificationCode = "1234";
            if (HttpContext.Current.Session != null)
            {
                HttpContext.Current.Session["VerificationCode"] = VerificationCode;
            }
            return VerificationCode;
        }
        throw new ArgumentException("Phone number format is incorrect");
    }

    [HttpGet]
    public string GetSessionString()
    {
        if (HttpContext.Current.Session != null)
        {
            return HttpContext.Current.Session["VerificationCode"].ToString();
        }
        return string.Empty;
    }

Why it doesn't work?


text:
Q: Verify my proof: if $A \setminus B \cap C = ∅ $ and $x \in A$ and $x \in C$ then $x \in B$ I'm reading Velleman's book "How to Prove it" (3rd edition). Because I'm learning without help from a professional mathematician I need help from the community to verify my proof. The exercise is on page 112, number 4:

Theorem. Suppose that $A \setminus B$ is disjoint from $C$ and $x \in A$. Prove that if $x \in C$ then $x \in B$

Proof. Because $A \setminus B$ is disjoint from $C$, $A \setminus B \cap C = \varnothing$. Thus for any $y$, $y \in A \setminus B \land y \notin C$ (1) or $y \notin A \setminus B \land y \in C$ (2). Having the original premise $x \in C$, the second expression (2) must be true, so $x \notin A \setminus B$, which can be rewritten as $x \in A \rightarrow x \in B$ $\blacksquare $
A few remarks here :

*

*This exercise does not contain the solution at the end of the book

*In the proof, I'm using the premise $x \in A$, but it is generated from $x \notin A \setminus B$, and it is not from the original theorem and it is not clear for me why it is needed ?

*I want the proof to be not too terse and not too wordy, something in the middle

A: I would do it the following way. Assume that $x\in A$ and $x\in C$, plus $(A-B)\cap C=\varnothing$. You have to prove that $x\in B$, by contradiction you suppose that $x\notin B$. Since $x\in A$, so $x\in A-B$, and $x\in C$. So, $x\in (A-B)\cap C=\varnothing$, i.e. $x\in \varnothing$, we're done.

A: Comment about notation: Instead of "$A \setminus B \cap C$" I would write $(A \setminus B) \cap C$. (I'd say that $A \setminus B \cap C$ would be usually interpreted as $A \setminus (B \cap C)$. Similarly as $a-b\cdot c$ means $a-(b\cdot c)$ rather than $(a-b)\cdot c$.)
In your proof you claim that $(A \setminus B) \cap C = \emptyset$ means that for any $y$ one of the following two possibilities is true:

*

*$y \in A \setminus B \land y \notin C$ (1)

*$y \notin A \setminus B \land y \in C$ (2)

This isn't actually true. It is possible that there are some elements which are neither in $A\setminus B$ nor in $C$. (So the third option is that $y\notin A\setminus B$ and $y\notin C$. We can call it $(3)$, to be consistent with the notation you started using.)
As an example, take intervals on the real line $A=(0,1)$, $B=\emptyset$ and $C=(3,4)$. Clearly, $A\setminus B$ and $C$ are disjoint. But there are many elements such that $y\notin A\setminus B$ and $y\notin C$. For example, this is true for $y=2$.
Of course, in this problem you have the assumption that $x\in C$, which eliminates the possibilities (1) and (3).


text:
Q: Syntax error missing operator on inner join I have made the following query :
SELECT [tbl_Imp_tabel WBS WPE.Verantwrd], [tbl_Imp_tabel WBS WPE.WBS_Id], [tbl_Imp_tabel        WBS WPE.Koptekst], [tbl_Users.UserName], [tbl_Users.WPENaam]
FROM  [tbl_Imp_tabel WBS WPE]
INNER JOIN [tbl_Users]
ON tbl_Imp_tabel WBS WPE.Verantwrd = tbl_Users.WPENaam ;

Howver, my access tells me that i have a missing operator on the line :
ON tbl_Imp_tabel WBS WPE.Verantwrd = tbl_Users.WPENaam ;

Any idea how to solve this ?
Thanks in advance

A: You have missed square barckets around table name in ON clause
Try this
SELECT [tbl_Imp_tabel WBS WPE].[Verantwrd], [tbl_Imp_tabel WBS WPE].[WBS_Id], [tbl_Imp_tabel WBS WPE].[Koptekst], [tbl_Users.UserName], [tbl_Users.WPENaam]
FROM  [tbl_Imp_tabel WBS WPE]
INNER JOIN [tbl_Users]
ON [tbl_Imp_tabel WBS WPE].[Verantwrd] = tbl_Users.WPENaam ;

A: You have forgotten square brackets around table name [tbl_Imp_tabel WBS WPE.Verantwrd] in ON clause. Usage of [ ] in SQL
SELECT [tbl_Imp_tabel WBS WPE.Verantwrd], [tbl_Imp_tabel WBS WPE.WBS_Id], [tbl_Imp_tabel        WBS WPE.Koptekst], [tbl_Users.UserName], [tbl_Users.WPENaam]
FROM  [tbl_Imp_tabel WBS WPE]
INNER JOIN [tbl_Users]
ON [tbl_Imp_tabel WBS WPE.Verantwrd] = tbl_Users.WPENaam ;


text:
Q: Why does a voltage divider linearize the effects of a non-linear thermistor? I saw a design specification with an NTC thermistor in a voltage-divider configuration.

The design method said that we must have $$R_1=\sqrt{R_{NTC\min}R_{NTC\max}}$$ to produce a linear output voltage for a given range despite \$R_{NTC}\$ being highly non-linear (Why?)
Isn't the effect of \$R_1\$ to make the seen resistance or the Thevenin resistance to be close to \$R_1\$ if \$R_{NTC}\$ is sufficiently large or in other words $$
\frac{R_1 R_{NTC}}{R_1 + R_{NTC}}
$$ is not a linear equation nor does it linearize the highly non-linear thermistor even for a given range. So we still have a non-linear input voltage at the Op-amp
I can't see why the output voltage will be linear even for any value of \$R_1\$

A: No linearization takes place in the op-amp circuit, so you can ignore that in any analysis. They are just saying that to make the best of a bad bargain the series resistor should be the geometric mean of the end points of the range in resistance. Another way to look at it is that the \$\Delta V/\Delta T\$ is maximized at the temperature where the thermistor resistance equals the series resistor resistance. The output per degree decreases on either side of that value.
By adding series resistance to a bridge circuit it is possible to get an S-shaped error from linear that is fairly good over a relatively narrow range of temperatures, at a cost of complexity and output, however the fearsome nonlinearity of the thermistor wins out over a wider range, so schemes involving resistor networks with multiple thermistor elements are sometimes used.

simulate this circuit – Schematic created using CircuitLab
This works because the energizing voltage of the bridge proper varies in the desirable direction with the thermistor resistance (as the thermistor resistance increases at low temperatures, the energizing voltage goes up, increasing the output per degree). I played around with this a few days ago, mostly to see how easy it would be to do with modern tools (using python scripts and libraries and extended Steinhart-Hart equations). You can see one result here.
However, in 2021, a  more sensible approach in most cases is to provide an ADC with a lot of dynamic range and deal the the nonlinearity in the digital domain.

A: In fact it doesn't.
Typical NTC law is exponential, this turns into a cold to hot resistance ratio that may well be in the hundreds depending on temperature range considered.
No chance to get it done but some clever numerical algorithm later on, after the ADC.
On the other hand if temperature range is small choosing R1=R(NTC) Is done to have the highest sensitivity, voltage variation per degree.
So the design method you choose is just optimize at the geometric mean of resistance. This can prove good enough depending on results you're after.
Consider that any linear circuit you may think trying to linearize is equivalent to the voltage divider you are actually using, so choosing equivalent resistance seen (your R1) is the only degree of freedom.

Saying that the network is linear should be enough to prove that the NTC port can be modelled as its Thevenin voltage and resistance, while the voltage output to the measuring circuit is a linear combination of some offset and a fraction of the NTC voltage
$$V_\mathrm{out}=V_\mathrm{out,0}+\alpha \,V_\mathrm{Rt} $$
But I'd like to go through some details. Let's take any generic linear network including excitation, output nodes but the NTC Rt itself.

simulate this circuit – Schematic created using CircuitLab
It can always be modelled by (mutliport) Thevenin
$$\mathbf{V}=\mathbf{E}+\mathbf{R}\cdot\mathbf{I}$$
with V and I port voltage and current vectors, E the open circuit Thevenin voltage vector and R the resistances matrix.
Expanding the matrix notation we have:
$$\left\{ \begin{align}
V_1=&E_1+R_{11}I_1+R_{12}I_2 \\
V_2=&E_2+R_{21}I_1+R_{22}I_2
\end{align}\right. $$

Now the left port #1 can be analyzed, we can assume without any loss of generality (1) that I2=0 i.e. the measuring circuit is a high impedance one.
(1) If it were not, measuring system input resistance can always taken inside N and crunched into the resistance matrix.
So we have
$$ V_\mathrm{Rt}=V_1=E_1+R_{11}I_1 $$

simulate this circuit
That's clearly the classical Thevenin equivalent, whatever you have inside the blackbox network N1 the NTC just sees a voltage generator and resistance.

Let's now have a look to the output port 2 equation in the same premise I2=0
$$ V_{out}=V_2=E_2+R_{21}I_1 $$
I1 current can be found from port 1
$$ V_\mathrm{Rt}=E_1+R_{11}I_1\quad\quad\Rightarrow\quad\quad
I_1=\frac{V_\mathrm{Rt}-E_1}{R_{11}}$$
Which substituted above
$$ V_{out}=V_2=E_2+R_{21}\frac{V_\mathrm{Rt}-E_1}{R_{11}}=
\underbrace{E_2-\frac{R_{21}}{R_{11}}E_1}_{V_\mathrm{out,0}}+
\underbrace{\frac{R_{21}}{R_{11}}}_{\alpha}V_\mathrm{Rt}$$
$$V_\mathrm{out}=V_\mathrm{out,0}+\alpha \,V_\mathrm{Rt} $$

Put it simple, whatever linear network you invent to connect your NTC it all boils down to be equivalent to

simulate this circuit
Voltage and resistance drive with offset \$V_\mathrm{out,0} \$ and gain factor \$\alpha\$ between NTC voltage VRt and network output.


text:
Q: jquery function only works once through I have a gallery type page with thumbnails.  When you click a thumb it loads the images having to do with that thumb into a hidden div, when they're done loading then div then slides open.  If you click another thumb it closes the div, clears the contents, loads the new content and then opens it again.  When you load the page you can click one thumb, then another, but if you go back to the first thumb and click the div won't open again, not sure why.  Thanks for any help on this.
I have a jsbin of it set up here http://jsbin.com/epawub/12/edit
the javascript I have set up for the thumbs is as follows:
var imgCount = 0;
var image=$('#images');

$('#klossviolins').click(function() {
  console.log("Loading...");
  $('#images').slideUp(500, function() {
    $("#images").empty().ready(function(){
        $("<img>", {
            src: "http://www.klossal.com/images/klossviolins/home.jpg"
        }).appendTo("#images").load(onImage);
        $("<img>", {
            src: "http://www.klossal.com/images/klossviolins/services.jpg"
        }).appendTo("#images").load(onImage);
    });
  });
  $("#info_header").empty();
  $('#info_header').append("Kloss Violins Website");
});

$('#light_dance').click(function() {
  console.log("Loading...");
  $('#images').slideUp(500, function() {
    $("#images").empty().ready(function(){
        $("<img>", {
            src: "http://www.klossal.com/light_dance_1.jpg"
        }).appendTo("#images").load(onImage);
        $("<img>", {
            src: "http://www.klossal.com/light_dance_var.png"
        }).appendTo("#images").load(onImage);
        $("<img>", {
            src: "http://www.klossal.com/light_dance_2.jpg"
        }).appendTo("#images").load(onImage);
    });
  });
  $("#info_header").empty();
  $('#info_header').append("Dancing With Light Series");
});

function onImage(e)
{
    console.log("Image loaded");
    imgCount++;

    if (imgCount == image.children().length)
    {
        image.slideDown(500);
    }
}

A: You must bind to the load event before you set the image's src value, otherwise the load event will trigger before you bind to it if the image is cached.
$("<img>").load(onImage).attr("src","http://www.klossal.com/light_dance_1.jpg").appendTo("#images");
// repeat for all similar

Also, make sure you reset imgCount back to 0.
...
if (imgCount == image.children().length)
{
    image.slideDown(500);
    imgCount = 0;
    ...


text:
Q: Error could not convert string to float: '' I have a column which does not want to change from object to float. The data from the xlsx file is always presented the same (as a number), but somehow only this column is seen as object.
The numbers in the column represent percentage using point(.) as a decimal placement.
xls3[' Vesturland'] = xls3[' Vesturland'].astype(float)

does not work. There is no special characters to replace (eg.str.replace()), I have tried that as well.
I dare not to use
xls3[' Vesturland'] = pd.to_numeric(xls3[' Vesturland'])

because it changes all floats to NaN and the whole column is percentage values.
The only thing I can think of is that the number of decimals is not consistent, but that shouldn't really matter, or does it? I put a red arrow on the column I want to change to float.

I only get this error when I try to convert to float Error could not convert string to float: '' and searching for it on my specific problem has not given any results yet.

A: You have empty strings in your pd.Series, which cannot be readily converted to a float data type. What you can do is check for them and remove them. An example script is:
import pandas as pd

a=pd.DataFrame([['a','b','c'],['2.42','','3.285']]).T
a.columns=['names', 'nums']

a['nums']=a['nums'][a['nums']!=''].astype(float)

Note: if you try to run a['nums']=a['nums'].astype(float) before selecting non-empty strings the same error that you've mentioned will be thrown.

A: First use this line to obtain the current dtypes:
col_dtypes = dict([(k, v.name) for k, v in dict(df.dtypes).items()])

Like so:
xls3 = pd.read_csv('path/to/file')
col_dtypes = dict([(k, v.name) for k, v in dict(xls3.dtypes).items()])
print(col_dtypes)

Copy the value that is printed.
It should be like this:
{'Date': 'object', 'Karlar': 'float64', 'Konur': 'float64', ' Vesturland': 'object', ...}

Then, for the column which whose datatype you know isn't object, change it to the required type ('int32', 'int64', 'float32' or 'float64')
Example:
The datatypes might be detected as:
{'Date': 'object', 'Karlar': 'float64', 'Konur': 'float64', ' Vesturland': 'object', ...}

If we know  Vesturland is supposed to be Float, then we can edit this to be:
col_dtypes = {
    'Date': 'object', 'Karlar': 'float64', 'Konur': 'float64',
    ' Vesturland': 'float64', ...
}

Now, with this snippet you can find the non-numeric values:
def clean_non_numeric_values(series, col_type):
    illegal_value_pos = []
    for i in range(len(series)):
        try:
            if col_type == 'int64' or col_type == 'int32':
                val = int(series[i])
            elif col_type == 'float32' or col_type == 'float64':
                val = float(series[i])
        except:
            illegal_value_pos.append(i)
            # series[i] = None # We can set the illegal values to None
            # to remove them later using xls3.dropna()
    return series, illegal_value_pos

# Now we will manually replace the dtype of the column Vesturland like so:
col_dtypes = {
    'Date': 'object', 'Karlar': 'float64', 'Konur': 'float64',
    ' Vesturland': 'float64'
}

for col in list(xls3.columns):
    if col_dtypes[col] in ['int32', 'int64', 'float32', 'float64']:
        series, illegal_value_pos = (
            clean_non_numeric_values(series=xls3[col], col_type=col_dtypes[col])
        )
        xls3[col] = series
        print(illegal_value_pos)
        if illegal_value_pos:
            illegal_rows = xls3.iloc[illegal_value_pos]
            # This will print all the illegal values.
            print(illegal_rows[col])

Now you can use this information to remove the non-numeric values from the dataframe.
Warning: Since this uses a for loop, it is slow but it will help you to remove the values you don't want.

A: After much trial and error, I ended up opening the excel sheet, deleted about 10 rows below the last data input. Then I unfroze rows/column, read it into Jupyter Notebook again and now ALL OF THE DATA IS FLOAT. I don't know which did the trick, but this is resolved now.
Thank you all that helped me here for your time and your attempts to solve this.

A: len([x for x in xls3[' Vesturland'] if x == ' '])

sometimes it can be blank go to your CSV file open it from excel and check is ctrl+shift+l filter and blank space.

A: Could it be that you do for i in range 0,len(tablename)
and you need len(tablename)-1
because you start at 0?


text:
Q: when the model is too big in forge,it will flickering,how to solve it? I use forge in my project.But my model is so big that force can't work well.
When I move my model in a forge, it can not finish rendering right away.It will be flickering.This affects the normal work.
Such as this video:
problem video
1)I have tried  Model Consolidation, but this has no obvious effect.
[https://forge.autodesk.com/blog/forge-viewer-consolidated-geometry][2]
This is the code:
var initializerOptions = {
   env: 'AutodeskProduction',
   useConsolidation: true,
   consolidationMemoryLimit: 150 * 1024 * 1024 // 150MB - Optional, defaults to 100MB
}

Autodesk.Viewing.Initializer( initializerOptions, function() {
  // ...
});

2)I want to merge elements and reduce the number of patches in the model.
I think my model is too big, it has too many elements and patches. So it wants to reduce them.But I don't find any good idea to solve it.
I have tried 3d Max, Maya, and Navisworks to merge elements and reduce the number of patches.But none of them worked well.I haven't found a better way to reduce patches and merge elements.
Do you have a good way to solve the flickering problem?

A: The flickering issue you mentioned is not an issue but a side effect of the Progressive Rendering that the viewer is using. You cannot avoid it, this is how works Progressive Rendering. Consolidation will help on loading large scene, but not on the effect you're seeing. I am afraid there is no good answer on this case.


text:
Q: Android - Firebase - Failed to convert value of type java.util.HashMap to String Aim
Save data within the Group Chat node
Current Database Tree

Within the Group Chats node, the user's messages will be sent and stored within the user's selected group chat.
As shown in the database tree, the user has sent a message saying "Hello" and his name is retrieved from the Users node
Desired Database Tree

The ---Msg ID--- is automatically generated
The ---User ID--- is retreived from the Users node
Problem
The function to allow the user to send message Only Worked Once which was the FIRST time. The following times that the app was deployed, it crashed when the user logged in.
Error - Logcat

com.google.firebase.database.DatabaseException: Failed to convert
  value of type java.util.HashMap to String

ChatActivity Class - Send Chat Message function
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        jGroupChatName = getIntent().getExtras().get("groupChatName").toString();
        jUserName = getIntent().getExtras().get("groupUserName").toString();
        jUserNeighbourhood = getIntent().getExtras().get("groupUserHome").toString();

        jChatToolbar = (Toolbar) findViewById(R.id.allUSersToolBar);

        jFirebaseCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        /*UserID Start - I was trying to retrieve the current user ID and add it to the Group Chat node,
          under the selected Group Chat */
        assert jFirebaseCurrentUser != null;
        final String currentUserID = jFirebaseCurrentUser.getUid();
        jChatRoot = FirebaseDatabase.getInstance().getReference().child("Group Chats").child(jGroupChatName).child(currentUserID);
        /*UserID End*/

        jChatMessageText = (EditText) findViewById(R.id.chatMessageText);
        jChatSendTextBtn = (ImageButton) findViewById(R.id.chatSendTextBtn);

        jChatSendTextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Map<String, Object> groupMap = new HashMap<String, Object>();
                jGroupKey = jChatRoot.push().getKey();
                jChatRoot.updateChildren(groupMap);

                // Based on the UserID code at the top, the "currentUserID" is added as shown below
                // My intentions are to have the UserID saved under the name of the Group Chat
                // jGroupKey = (Name of selected Group Chat)

                DatabaseReference groupMessageRoot = jChatRoot.child(jGroupKey).child(currentUserID);
                Map<String, Object> groupMap2 = new HashMap<String, Object>();
                groupMap2.put("name", jUserName);
                groupMap2.put("msg", jChatMessageText.getText().toString());

                groupMessageRoot.updateChildren(groupMap2);
            }
        });
    }

Linked Question
Android - Firebase - Send Users to Chat Room
Future Implementations
In the future, I intend to allow the user to send pictures and video recordings by writing a code to allow the user to access their phone camera or gallery and send the pics and vids data into the Group Chats node, under the selected Group name. I would also like to retrieve data after sending, but of course, I will leave those in future questions if I am unable to solve them.

A: Branching of your desired database is unnecessary. You are creating an unnecessary level using UID of users. Instead, merge this layer down, i.e. combine uid, message and name. You can then use someRef.orderByKey("uid").equalTo("<user_uid>") in case you need specific user's records within that path, for example chat messages.
So, create a class called ChatMessage:
public class ChatMessage {

    private String uid;
    private String name;
    private String message;
    private Long creationTime;

    public ChatMessage() {
        // Default constructor required for calls to DataSnapshot.getValue(ChatMessage.class)
    }

    public ChatMessage(String uid, String name, String message) {
        this.uid = uid;
        this.name = name;
        this.message = message;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public java.util.Map<String, String> getCreationTime() {
        return ServerValue.TIMESTAMP;
    }

    @Exclude
    public Long getCreationTimeLong() {
        return creationTime;
    }

    public void setCreationTime(Long creationTime) {
        this.creationTime = creationTime;
    }
}

Then update your code as follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

    chatGroupName = getIntent().getStringExtra(CHAT_GROUP_NAME);
    userKey = getIntent().getStringExtra(USER_KEY);
    user = getIntent().getParcelableExtra(USER);

    jChatToolbar = (Toolbar) findViewById(R.id.allUSersToolBar);
    jChatMessageText = (EditText) findViewById(R.id.chatMessageText);
    jChatSendTextBtn = (ImageButton) findViewById(R.id.chatSendTextBtn);

    jChatSendTextBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
        }
    });
}

private void sendMessage() {
    String userMessage = jChatMessageText.getText().toString();
    chatGroupRef = FirebaseDatabase.getInstance().getReference().child("Group Chats").child(chatGroupName);

    if (!TextUtils.isEmpty(userMessage)) {
        String newChatMessageKey = chatGroupRef.push().getKey();
        ChatMessage newChatMessage = new ChatMessage(userKey, user.getName(), userMessage);
        chatGroupRef.child(newChatMessageKey).setValue(newChatMessage);
    }
}


text:
Q: How to store user input locally using JavaScript I'm creating a cross-platform app and I want the user bio to be stored locally and stay there after refresh and close/reopen.
Thanks

var newBio = document.getElementById("bio").value;
var storeBio = localStorage.setItem(newBio);
document.getElementById("bio").innerHTML = localStorage.getItem(storeBio);
<input id="bio" type="text" name="search" placeholder="Bio" onmouseout="showBotNav(); saveBio()">

A: Look at the the examle in MDN documentation or elsewhere if you don't know how to write something.
.getItem needs a name as an argument. And .setItem needs two (name and value) but you provided only one argument storeBio wich is incorrect( also because function localStorage.setItem
can't be a name).
In your html you declared saveBio function. Why not show us save and get functions as is?

function saveBio() {
  var newBio = document.getElementById("bio").value;
  localStorage.setItem('bio', newBio);
}

function getBio() {
  // why you were using (correct way) ".value" when setting bio
  // but here you are using .innerHTML ?
  document.getElementById("bio") //.innerHTML =
    .value = localStorage.getItem('bio')

  // by the way innerHTML is only present on elements with closing tag. Input element is not one of
}

// here you calling function when page is loaded
getBio()
<input id="bio" type="text" name="search" placeholder="Bio" onmouseout="showBotNav(); saveBio()">

The posted question indicates that you did not include enough effort to solve your problem. We are always glad to help and support new coders here on SO but you need to help yourself first.


text:
Q: how to sort prime factors into array and display in specific way using c code Hi im trying to create a code using c language where you enter in a number it checks for its prime factors and then prints these factors out.
only there is a specific way that i am required to print these numbers
The prime factors of 56 are:
{2,7}
this is the required output and i can only get to this:
The prime factors of 56 are:
2,7,
ive been suggested to store the outputs into an array and then manipulate the array to delete the comma at the end and add the {} but im not sure how to do this.
Here is my code for reference:
#include<stdio.h> int main(){

int i, j, number, p;
printf("Enter a Number to find Prime Factors:");
scanf("%d", &number);
    if(number < 2)
    {
        printf("Invalid input\n");
    }else {
printf("The prime factors of %d are:\n ", number);
for(i=2; i<=number; i++)
{
    /* Check 'i' for factor of num */
    if(number%i==0)
    {
        /* Check 'i' for Prime */
        p=1;
        for(j=2; j<=i/2; j++)
        {
            if(i%j==0)
            {
                p = 0;
                break;
            }
        }
        /* If 'i' is Prime number and factor of num */
        if(p==1)
        {
            printf("%d,", i);
        }
    }
}

A: First and foremost, you should indent your code consistently so that it is easy to read. In the following, I show you one way of doing what you want without using any intermediary array variables. The key points are that you need to distinguish the first number that you will output from the others, and you need to add curly braces unconditionally at the begin and the end.
#include<stdio.h>

int main() {

  int i, j, number, p;
  int first_factor = 1; /* Are we printing the first factor? */
  printf("Enter a Number to find Prime Factors:");
  scanf("%d", &number);

  if(number < 2)
  {
    printf("Invalid input\n");
  } else {
    /* I removed the line break in the printf below */
    printf("The prime factors of %d are: ", number);
    putchar('{'); /* Inconditionnaly prints '{' at the beginning of the answer */
    for(i=2; i<=number; i++)
    {
      /* Check 'i' for factor of num */
      if(number%i==0)
      {
        /* Check 'i' for Prime */
        p=1;
        for(j=2; j<=i/2; j++)
        {
          if(i%j==0)
          {
            p = 0;
            break;
          }
        }
        /* If 'i' is Prime number and factor of num */
        if(p==1)
        {
          if (first_factor == 1)
          {
            /* It is the first factor, prints without a comma */
            printf("%d", i);
            first_factor = 0; /* The other factors are not the first one */
          } else {
            printf(",%d", i);
          }
        }
      }
    }
    puts("}"); /* Inconditionnaly prints a '}' followed by a line-break */
  }
}


text:
Q: Scapy sniff cannot 'sniff' any packets I have a problem with sniff function from scapy library. For some unknown reasons, it cannot sniff any receiving packets anymore. I don't define any interface so I assume it should be able to sniff all incoming packets and it worked just fine for a week until yesterday. I tried to re-install the library and disable all the extensions on VSCode to see if it could help and yet nothing has solved the problem. I appreciate all the help!
from scapy.all import sniff

sniff(prn=lambda x:x.show(), timeout=5)


text:
Q: How to delete specific fragment from layout I have 4 fragment in home layout. I want to remove specific fragment when user press corresponding button. when i am doing this with popBackStack() it deleting recent fragment added by user. so how can i remove specific fragment from screen.
I am adding Fragment on Button Click, i have same 3 more add buttons.
addFragment_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            fm.beginTransaction()
                    .add(R.id.Fragment_container_1, new Fragment_1(), "Frag 1")
                    .addToBackStack("Frag 1")
                    .commit();
        }
    });

Then i want to remove this fragment with other button click. also add 3 more remove button.
 removeFragment_1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getSupportFragmentManager().popBackStack();
        }
    });

I have 4 add button and 4 remove button. when i add all 4 fragment on screen and then press the 1st remove button it remove 4th fragment then 3 > 2>1 and all 4 remove Button doing the same. I want 1 remove button delete only one corresponding fragment.
I also try popBackStack ("Frag 1", 0) it remove all 3 fragment except fragment 1, and when i try popBackStack("Frag 1", FragmentManager.POP_BACK_STACK_INCLUSIVE) it remove all 4 fragment.
I not that good in English, I want some detailed answer. thanks

A: Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
getSupportFragmentManager().beginTransaction().remove(fragment).commit();

This must work.


text:
Q: nautilus items aren't snapped to grid Recently I did a nautilus upgrade and it became a pile of mess:

I tried downgrading but that didn't work.
Nautilus version 3.26.0, using GNOME-shell.
Update1: Seems like pcmanfm-gtk3 worked fine. nemo didn't, however.


text:
Q: Shooting prefab according to cannon angle with projection This code shoots at the mouse pointer but goes directly, not by projection. I need it to be like the picture below.
var prefab : GameObject;
function Update () {
    if (Input.GetMouseButtonDown(0)) {
        var pos = Input.mousePosition;
        pos.z = transform.position.z - Camera.main.transform.position.z;
        pos = Camera.main.ScreenToWorldPoint(pos);
        var q = Quaternion.FromToRotation(Vector3.up, pos - transform.position);
        var go = Instantiate(prefab, transform.position, q);
        go.rigidbody2D.AddForce(go.transform.up * 20000.0);
    }
}


text:
Q: Scons command with time limit I want to limit the execution time of a program I am running under Linux. I put in my scons script a line like:
Command("com","","ulimit -t 1; myprogram")

and tested it with an infinite loop program: it did not work and the program ran forever.
Am I missing something?
-- tsf

A: ulimit -t 1 means that the limit is set to 1 second of CPU time. If your infinite loop program uses any sort of sleep in its inner loop then it will use practically no CPU time. This means it will not get killed in 1 second of real, on the clock time. In fact it may take minutes or hours to use up its 1 second allocation.
What happens if you run the command outside of SCons? Perhaps you don't have permission to change the limit at all...
ulimit -t 1; ./myprogram

For example, it may say the following if the limit is already set to 0:
bash: ulimit: cpu time: cannot modify limit: Operation not permitted

Edit: it seems that the -t option is broken on Ubuntu 9.04. A fix has been committed 05 June 2009, but it may take a while to trickle into the updates - it may not be fixed until 9.10.
As an historical note, this problem no longer exists in Ubuntu 10.04.

A: You can also use this script:
(taken from http://newsgroups.derkeiler.com/Archive/Comp/comp.sys.mac.system/2005-12/msg00247.html)
#!/bin/sh
# timeout script
#
usage()
{
echo "usage: timeout seconds command args ..."
exit 1
}

[[ $# -lt 2 ]] && usage
seconds=$1; shift

timeout()
{
sleep $seconds
kill -9 $pid >/dev/null 2>/dev/null
}

eval "$@" &
pid=$!
timeout &
wait $pid
.