text:
Q: Android's expanded BottomSheetDialogFragment offset distance to start collapsing I use BottomSheetDialogFragment expanded to full screen. Does anyone know how to make it get back expanded if a user has dragged & dropped it before a predefined distance reached? So I mean a BottomSheet should restore full expanded state if it hasn't been dragged over the long enough distance. Now it seems the default distance is 0 and the expanded BottomSheet can be closed occasionally on internal scroll in some cases.

A: Eventually I've found the following solution:
open class CustomBottomSheetBehavior<V : View?>(context: Context, attrs: AttributeSet?) : BottomSheetBehavior<V>(context, attrs) {

    var offsetToCollapse: Int = 220 // this is bottom sheet's collapsing threshold offset

    private val lastNestedScrollDyField by lazy { ReflectionUtils.getField(BottomSheetBehavior::class.java, "lastNestedScrollDy") }

    override fun shouldHide(child: View, yvel: Float): Boolean {
        if (0 < offsetToCollapse && offsetToCollapse > child.top) {
            ReflectionUtils.setFieldValue(this, lastNestedScrollDyField, 0)
            return false
        }
        return super.shouldHide(child, yvel)
    }
}

object ReflectionUtils {

    fun <T> getField(clazz: Class<T>?, fieldName: String?): Field? {
        if (clazz == null || fieldName == null) return null
        try {
            return clazz.getDeclaredField(fieldName)
        } catch (e: NoSuchFieldException) {
            Timber.e(e)
        }
        return null
    }

    fun setFieldValue(any: Any?, field: Field?, value: Any?) {
        if (any == null || field == null) return
        try {
            field.isAccessible = true
            field[any] = value
        } catch (e: java.lang.Exception) {
            Timber.e(e)
        }
    }
}

And don't forget to put this into proguard-rules.pro:
-keepclassmembers class com.google.android.material.bottomsheet.BottomSheetBehavior {
    private <fields>;
}


text:
Q: Need help in signing an Android application in Android Studio I'm having an incredibly difficult time in Android Studio with signing my app.  I have tried a half dozen times, creating new certificates, to no avail.
The output from jarfile -verify is:
This jar contains entries whose certificate chain is invalid. Reason: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
This jar contains entries whose signer certificate is self-signed.
This jar contains signatures that do not include a timestamp. Without a timestamp, users may not be able to validate this jar after any of the signer certificates expire (as early as 2048-03-27).
How can I correct this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Writing to flash drive becomes very slow after 10% completion I have a new 32GB Kingston flash drive. When writing files the transfer speed reduces to 1-3MBps after copying approx 10% of data, while the initial transfer speed was 50MBps+. Sometimes it retains the high speed if I pause the writing and resume.
When observing with flash tool 'HD_Speed', I can see that during the write the 'block size' changes very frequently and whenever it happens the speed goes down.
Any ideas? Is this because of a problem with the drive?
I had noticed it when the drive was new, now I have partitioned it but the problem still exists.
I have tried formatting the partitions with different combinations of Fat32/NTFS and different block sizes from 512 bytes to 4196 bytes.


text:
Q: Format continously updating output to variable then query string A command I have 'ibeacon scan' gives me the output of this:
ibeacon scan...
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 1 4 -71 -69
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 6 2 -71 -63
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 1 4 -71 -69
3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6 5 7 -71 -64

I need each of these values to be sent by query string like.
UUID=3F234454-CFD-4A0FF-ADF2-F4911BA9FFA6&Major=1&Minor=4&Power=-71&RSSI=-63

I am assuming I need to use a delimiter to separate the input individual.
for line in fileinput.input():
   string = line
   string2 = string.split(" ")

Is this an efficient way to do this? How do I get this output sent by query string?

A: import fileinput

pattern = 'UUID={}&Major={}&Minor={}&Power={}&RSSI={}'

for line in fileinput.input():
  query = pattern.format(*line.strip().split(' '))
  # now do something with query


text:
Q: Insert variable in mysql I'm trying to send get the restaurants who's city is Lahore, Rwp etc(what the user will enter into the form.
But I'm not getting anything.
If I hard code in the query and enter the city name myself then it works else it doesn't return anything.
Same problem I have too when I try to add anything.
Basically I need help in using variables in mysql query.
What am I doing wrong?
public ResultSet getRestaurants(String city){
    Statement statement;
    try {
        statement = con.createStatement();
        String query = "select * from restaurantinfo WHERE city = '"+city+"'";
        ResultSet rs = statement.executeQuery(query);
        return rs;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}

THIS IS HANDLING RESULT SET. I know there are errors. I will fix them. I'm concerned with showing the restaurants..

   <%
 DbConnection dbc = new DbConnection();
 String city = request.getParameter("city");
 ResultSet rs = dbc.getRestaurants(city);

 %>
        <%
        while(rs.next()){
  %>

    <form id="filtercousine">

 Filter by Cuisines

                <input id="fastfood" type="checkbox" style="" name="fastfood" value="fastfood">Fast Food

                <input id="pakistani" type="checkbox" name="gender" value="Pakistani">Pakistani

            </form>

 <input type="submit" id="menu" value="Go to Menu" class="main-button" style="float:right; margin-right:6px;">
<%= rs.getString("name") %>

 <%= rs.getString("cousines") %>

 Delivery:

Free

    <%
 }
 %>

This is my database picture
View

A: First off - it seems odd that you pass along the ResultSet instead of directly handling that. Please also share the code handling the ResultSet - maybe the error is in that part.
For your method: Please consider this variant using a PreparedStatement instead:
public ResultSet getRestaurants(String city){
    try {
        System.out.println("CITY: " + city);
        PreparedStatement ps = con.prepareStatement(
             "select * from restaurantinfo WHERE city = ?");
        //Set first ? with value of city
        ps.setString(1, city);
        //return resultset
        return statement.executeQuery(query);
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

A: Thanks a lot @jan for your help!
Btw I got it solved by changing the name to "cityname" I don't know why it worked..
And yes the other database also worked by adding a name attribute.
For this i changed city to cityname. Strange but it worked. I think id and name should be different maybe. And of course i had to change in the request parameter as well.
<input id="city"  type="text" name="cityname" />


text:
Q: Android Factory Reset Programmatically I tried to perform a factory reset in Android using the RecoverySystem class, but I get permission errors, which I can not overwrite because they are system permissions. I want to know if there is another way to perform a factory reset?

A: you have to use DeviceAdministration (API 2.2 or above)
DevicePolicyManager mDPM;
mDPM.wipeData(0);
See:
http://developer.android.com/guide/topics/admin/device-admin.html

A: This works on a many different devices I have tried. (more than 20)
Context foreignContext = createPackageContext("com.android.settings", Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
Class<?> yourClass = foreignContext.getClassLoader().loadClass("com.android.settings.MasterClear");

Intent intent = new Intent(foreignContext, yourClass);
startActivity(intent);

A: After Android 8.0, you can send am broadcast to trigger the factory reset process if you can get root permission:
am broadcast -p "android" --receiver-foreground -a android.intent.action.FACTORY_RESET

A: Third party applications most DEFINITELY can do this.
On 2.2+ devices (including latest 4.x) you would have to use the DevicePolicyManager and include permissions in the AndroidManifest.xml. For older devices you can use foreign context loader as described in other answer.
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;

  DevicePolicyManager mDPM;
  ComponentName mDeviceAdmin;

On Create determine there Android version and get handle on objects
    currentAPIVersion = Build.VERSION.SDK_INT;

    if (currentAPIVersion >= android.os.Build.VERSION_CODES.FROYO) {
        //2.2+
        mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
        mDeviceAdmin = new ComponentName(this, WipeDataReceiver.class);
    }

The WipeDataReceiver class was a class to implement DeviceAdminReceiver, but did not have any overrides or code updates.
    public static class WipeDataReceiver extends DeviceAdminReceiver {

    }

On Resume, initially the will have to confirm Factory Reset. when the Activity returns result it will perform wipeData. If it's Froyo or less, you can jump the stock factory reset activity.
if (currentAPIVersion >= android.os.Build.VERSION_CODES.FROYO) {
    // 2.2+
    if (!mDPM.isAdminActive(mDeviceAdmin)) {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdmin);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Process will remove user installed applications, settings, wallpaper and sound settings. Are you sure you want to wipe device?");
        startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
    } else {
        // device administrator, can do security operations
        mDPM.wipeData(0);
    }

} else {
    // 2.1
    try {
        Context foreignContext = this.createPackageContext("com.android.settings", Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
        Class<?> yourClass = foreignContext.getClassLoader().loadClass("com.android.settings.MasterClear");
        Intent i = new Intent(foreignContext, yourClass);
        this.startActivityForResult(i, REQUEST_CODE_ENABLE_ADMIN);
    } catch (ClassNotFoundException e) {

    }

}

A: @TapanHP, You can use any ID just to handle the activity result callback.
int REQUEST_CODE_ENABLE_ADMIN =1234;

A: It helps me
 private void resetEverything() {
    Intent intent = new Intent(Intent.ACTION_FACTORY_RESET);
    intent.setPackage("android");
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    intent.putExtra(Intent.EXTRA_REASON, "MasterClearConfirm");
    intent.putExtra(Intent.EXTRA_WIPE_ESIMS, shouldResetEsim());
    requireActivity().sendBroadcast(intent);
}

private boolean shouldResetEsim() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
            requireContext());
    return sharedPreferences.getBoolean(
            requireContext().getString(R.string.reset_esim), false);
}

create preference_keys.xml in /values
<resources>
<string name="reset_esim" translatable="false">reset_esim</string>

A: I suggest you send the user to the proper settings activity and let them do it themselves.
See this tutorial and use settings activity android.provider.Settings.ACTION_PRIVACY_SETTINGS


text:
Q: SQL error with update I have problem with  updating. What's wrong?
Code compiles, but when i click button, the line --> cmd.ExecuteNonQuery(); didn't work.
HERE ERROR

Additional information: The parameterized query '(@nmo int,@rezerwo int)UPDATE oferty SET oferty.miejsca = @nmo ' expects the parameter '@rezerwo', which was not supplied.

public partial class oferty1 : System.Web.UI.Page
    SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\ddd\Documents\Visual Studio 2013\Projects\sV1\stopowiczeV1\App_Data\ofety-sV1.mdf;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
    SqlCommand cmd = new SqlCommand();

    protected void Page_Load(object sender, EventArgs e)
cmd.Connection = cn;

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        var g = GridView1.SelectedRow;
        string rezerw = GridView1.DataKeys[g.DataItemIndex]["Idoferty"].ToString();

        m = GridView1.SelectedRow.Cells[5].Text;
        int nmo = Convert.ToInt32(m);
        int rezerwo = Convert.ToInt32(rezerw);
        if (GridView1.SelectedRow.Cells[5].Text != "" & GridView1.SelectedRow.Cells[0].Text != "")
        {
            cn.Open();
            nmo--;
            cmd = cn.CreateCommand();
            cmd.CommandText = ("UPDATE oferty SET oferty.miejsca = @nmo WHERE oferty.idoferty = @rezerwo");
            cmd.Parameters.Add(new SqlParameter("@nmo", nmo));
            cmd.Parameters.Add(new SqlParameter("@rezerwo", rezerwo));
            string snmo = Convert.ToString(nmo);
            td.miejsca = snmo;
            cmd.ExecuteNonQuery();
            cn.Close();
        }

        db.rezerwacjes.InsertOnSubmit(tc);
        db.SubmitChanges();
    }

A: Constructor of SqlParamter may have interpreted second parameter incorrectly (SqlDbType instead of actual value).
Instead of
cmd.Parameters.Add(new SqlParameter("@nmo", nmo));
cmd.Parameters.Add(new SqlParameter("@rezerwo", rezerwo));

Try
cmd.Parameters.AddWithValue("@nmo", nmo);
cmd.Parameters.AddWithValue("@rezerwo", rezerwo);

Another point. By default command type could be stored procedure, try adding this to your code:
cmd.CommandType = CommandType.Text;


text:
Q: NoMethodError in Pages#welcome after installing the bootstrap gem After I installed the bootstrap gem and run the rails server again I get this error:
NoMethodError in Pages#welcome
undefined method `environment' for nil:NilClass
  (in /Users/neilpatel/Desktop/Rails/prospects/app/assets/stylesheets/custom.css.scss)

custom.css.scss
@import "bootstrap";

app/views/layouts/application.html.erb
<!DOCTYPE html>

<html>
    <head>
      <title>Prospects</title>

      <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
      <%= javascript_include_tag "application", "data-turbolinks-track" => true %>

      <%= csrf_meta_tags %>
    </head>

    <body>
        <%= link_to "Home", "/" %>
        <%= link_to "About", "/about" %>

     <%= yield %>
    </body>
</html>

log/development.log
Processing by PagesController#welcome as HTML
  Rendered pages/welcome.html.erb within layouts/application (0.1ms)
Completed 500 Internal Server Error in 15ms

ActionView::Template::Error (undefined method `environment' for nil:NilClass
  (in /Users/neilpatel/Desktop/Rails/prospects/app/assets/stylesheets/custom.css.scss)):
    4:  <head>
    5:    <title>Prospects</title>
    6:
    7:    <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
    8:    <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
    9:
   10:    <%= csrf_meta_tags %>
  app/views/layouts/application.html.erb:7:in `_app_views_layouts_application_html_erb___3923576615849785590_70354614228980'

Gemfile
source 'https://rubygems.org'

gem 'rails', '4.0.0.rc1'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.0.rc1'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.0.1'
gem 'bootstrap-sass', '~> 3.1.1'

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_tree .

updated the gemfile
ran bundle update
'ran bundle update Bundler could not find compatible versions for gem "railties":
  In Gemfile:
    sass-rails (~> 4.0.2) ruby depends on
      railties (< 5.0, >= 4.0.0) ruby

    rails (= 4.0.0.rc1) ruby depends on
      railties (4.0.0.rc1)

A: This is an issue with how the sass-rails gem integrates with the sprockets gem which surfaced after the Sprockets v2.11.1 release (see here and here).
To fix it change the Gemfile:
gem 'sass-rails', '~> 4.0.2'

and run bundle update.
Note: You should also update your Rails version. The most recent version is v4.0.4. To do so, change your Gemfile to
gem 'rails', '~> 4.0.0'

and again, run bundle update.


text:
Q: Technique for finding cardinalites in combinatorics In combinatorics I see the following technique used a lot:
Let A and B be sets.
We try to find a function $f:A→B$ such that all the fibers of the elements of $B$ under $f$ have the same cardinality $\kappa$.
If we manage to do that, we conclude that $|A|=\kappa|B|$.
Example:
Find the number of subsets of $\{1,2,3,4\}$ whose cardinality is $2$.
Let A be the set of ordered pairs that have two distinct elements from $\{1,2,3,4\}$.
Let B be the set of subsets of $\{1,2,3,4\}$ whose cardinality is $2$.
Let $f:A→B$, $f(〈x,y〉)=\{x,y\}$.
The fiber of each $\{x,y\}∈B$ under $f$ has exactly $2$ elements: $〈x,y〉$ and $〈y,x〉$.
From that, we conclude that $|A|=2|B|$, and we know that
$|A|=4⋅3=12$, so we get $|B|=6$.
My questions:
Is there a name for this technique? Is there a name for this type of function?

A: The method is called overcounting. I sometimes hear $f$ described as a $\kappa$-to-one function, in analogy with a bijection being one-to-one.


text:
Q: how to set a parameter in icCube reporting that is based on other parameters? I have a server function (MDX++) months(value M, value H).
The icCube dashboard contains two events, attached to two filters (LOVs): @{selM} and @{selH}.
How can I assign the result of the function months(@{selM}, @{selH} to a new event called @{selPeriod} that is updated each time one of the LOVs changes?

A: It's possible, such event could be generated by the cusom mdx filter that based on the manual query. You can hide somehow this filter from the result UI as it will be used only in the automatic mode.
Filter1 -> generates @{selM}
Filter2 -> generates @{selH}
Filter3 -> hidden, generates @{selPeriod}

For the Filter3 you need to switch the data configuration to MDX and put the following request:
WITH
MEMBER ic3Name AS months(@{selM}, @{selH})  // event caption(your function)
MEMBER ic3UName AS months(@{selM}, @{selH}) // event value(your function)
MEMBER ic3PName AS NULL
MEMBER ic3Measure AS 0
MEMBER ic3IsSelected AS true // true to throw the event automatically
MEMBER ic3FilterName as [Measures].[ic3Name]
MEMBER ic3Key as 0
SELECT
{[Measures].[ic3Name],[Measures].[ic3UName],[Measures].[ic3PName],[Measures].[ic3Measure],[Measures].[ic3IsSelected],[Measures].[ic3FilterName],[Measures].[ic3Key]} ON 0,
TopCount([Calendar].[Year], 1) on 1 // any non empty level, to have 1 row in the response
FROM [Sales] // any cube


text:
Q: XSLT 1.0 - Sum column based on conditions from 2 nodes I have 2 data sources (Request and Actual). Below is a sample of my xml:
<dsQuery Response>
  <Request>
    <Rows>
      <Row>
        <TravelDate>2013-10-05T05:00:00Z</TravelDate>
        <ID>1</ID>
       <Cost>1000</Cost>
     </Row>
     <Row>
        <TravelDate>2013-12-31T05:00:00Z</TravelDate>
        <ID>2</ID
        <Cost>2500</Cost>
     </Row>
     <Row>
      <TravelDate>2014-01-13T06:00:00Z</TravelDate>
      <ID>3</ID>
      <Cost>1300</Cost>
     </Row>
   <Row>
      <TravelDate>2014-02-01T06:00:00Z</TravelDate>
      <ID>4</ID>
      <Cost>2300</Cost>
    </Row>
    <Row>
      <TravelDate>2014-08-01T06:00:00Z</TravelDate>
      <ID>5</ID>
      <Cost>2000</Cost>
    </Row>
    </Rows>
  </Request>
  <Actual>
    <Rows>
      <Row>
        <ID>10</ID>
        <FormID>2</FormID>
        <CheckDate>2014-01-01T12:00:00Z</CheckDate>
      </Row>
      <Row>
        <ID>11</ID>
        <FormID>3</FormID>
        <CheckDate>2014-01-31T12:00:00Z</CheckDate>
    </Row>
    <Row>
      <ID>12</ID>
      <FormID>4</FormID>
      <CheckDate>2014-02-15T12:00:00Z</CheckDate>
    </Row>
  </Rows>
</Actual>
</dsQuery Response>

I need to sum the Cost column if the year for TravelDate=This year OR if the year of the CheckDate = This Year.
In the scenario above Request ID 2-5 meet the criteria.  The total should be 8100.  I have tried several ways to get the sum and none are working.  Any help is appreciated.

A: You could use a xsl:variable to hold your filtered Row elements and sum them:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
    <xsl:template match="/dsQueryResponse">

        <xsl:variable name="ThisYear" select="2014" />
        <xsl:variable name="Rows">
            <xsl:for-each select="//Cost">
                <xsl:variable name="ID" select="../ID" />
                <xsl:if test="
                    starts-with(../TravelDate, $ThisYear) or
                    (
                        /*/Actual/*/*[FormID = $ID and
                        starts-with(CheckDate, $ThisYear) ]
                    )">
                    <xsl:copy-of select=".." />
                </xsl:if>
            </xsl:for-each>
        </xsl:variable>

        <xsl:value-of select="sum($Rows//Cost)" />

    </xsl:template>
</xsl:stylesheet>

A: This will output <sum>5600</sum>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:param name="year" select="string('2014')"/>

   <xsl:template match="/">
       <sum>
         <xsl:value-of select="sum(//Request/Rows/Row[substring-before(TravelDate/text(),'-')=$year]/Cost)
                     + sum(//Actual/Rows/Row[substring-before(CheckDate,'-')=$year]/Cost)"/>
       </sum>

   </xsl:template>
</xsl:stylesheet>

A: You are asking for a XSLT 1.0 solution, but there is no "this year" in XSLT 1.0; you will need to use an EXSLT extension function or pass the current date/year as a parameter at runtime.
Other than that. I suggest you use a key to get the data from the "related" actual checkdate:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:date="http://exslt.org/dates-and-times"
extension-element-prefixes="date">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:param name="thisYear" select="substring(date:date-time(), 1, 4)" />

<xsl:key name="check" match="CheckDate" use="../FormID" />

<xsl:template match="/">
    <sum>
        <xsl:value-of select="sum(dsQueryResponse/Request/Rows/Row[substring(TravelDate, 1, 4)=$thisYear or substring(key('check',ID) , 1, 4)=$thisYear]/Cost)"/>
    </sum>
</xsl:template>

</xsl:stylesheet>

When applied to a corrected example input of:
<dsQueryResponse>
  <Request>
    <Rows>
      <Row>
        <TravelDate>2013-10-05T05:00:00Z</TravelDate>
        <ID>1</ID>
       <Cost>1000</Cost>
     </Row>
     <Row>
        <TravelDate>2013-12-31T05:00:00Z</TravelDate>
        <ID>2</ID>
        <Cost>2500</Cost>
     </Row>
     <Row>
      <TravelDate>2014-01-13T06:00:00Z</TravelDate>
      <ID>3</ID>
      <Cost>1300</Cost>
     </Row>
   <Row>
      <TravelDate>2014-02-01T06:00:00Z</TravelDate>
      <ID>4</ID>
      <Cost>2300</Cost>
    </Row>
    <Row>
      <TravelDate>2014-08-01T06:00:00Z</TravelDate>
      <ID>5</ID>
      <Cost>2000</Cost>
    </Row>
    </Rows>
  </Request>
  <Actual>
    <Rows>
      <Row>
        <ID>10</ID>
        <FormID>2</FormID>
        <CheckDate>2014-01-01T12:00:00Z</CheckDate>
      </Row>
      <Row>
        <ID>11</ID>
        <FormID>3</FormID>
        <CheckDate>2014-01-31T12:00:00Z</CheckDate>
    </Row>
    <Row>
      <ID>12</ID>
      <FormID>4</FormID>
      <CheckDate>2014-02-15T12:00:00Z</CheckDate>
    </Row>
  </Rows>
</Actual>
</dsQueryResponse>

the result is:
<?xml version="1.0" encoding="UTF-8"?>
<sum>8100</sum>


text:
Q: How to totally remove Ubuntu? I've got Ubuntu on my laptop and I want to completely remove it so I have no OS on it. Google provides no answers which would be relative, they are only like "How to delete Ubuntu if you have Windows/and then install Windows".My Ubuntu is 20.04, as I remember. If possible, tell me the detailed steps. Thanks in advance!Additional: The possible way is to format disk, but I have no idea how to do it because Ubuntu don't let me to.

A: *

*Boot your system using an Ubuntu liveCD / liveUSB image or installation media.

*Rather than launching the Ubuntu installer, instead launch fdisk or another partition editor such as parted in your preferred a Terminal program to alter the partition table of the disk in question (e. g. sudo fdisk /dev/sda).  If you're unclear how to use the partition editor, in another Terminal window  consult the manual with man.

*Delete all partitions from the hard disk in question (e. g. /dev/sda).  Be certain you're operating on the correct medium.

*Write the changes to the disk.

*If you also want to wipe the boot sector, run the following command:

$ sudo dd if=/dev/zero of=/dev/sda bs=512 count=1

Be advised this will remove all partition information, but is not a "disk wipe" or "secure delete".  If you want to truly be certain that data can not be recovered, the most effective tool to use is a hammer.

A: I assume you have only one drive in your laptop. Just execute
sudo dd if=/dev/zero of=/dev/sda bs=128M

and wait. It will delete everything on the first drive (including other operating systems and user-data). The system will crash sooner or later, so this is not a perfectly safe method in sense of data security.


text:
Q: Team Services - Jenkins build server Currently in our business we use Team Services in the cloud with a single self hosted build agent which runs locally on a server in our office.
As we are expanding and taking on more work there is an increase in the number of queued builds. As a result we are considering adding additional build agents to cope with the load.
Unfortunately adding additional agents costs money and its often difficult to for us to justify the cost. Essentially I'm interested in whether or not there are any free alternatives to the TFS build agent. I'm still looking to keep Team Services but somehow integrate the builds locally for free.
A colleague of mine has mention Jenkins as a build server but I have little experience with this application and I'm not sure if an agent is still required from Team Service's point of view.
I'd be grateful if you could let me know if you're in or were in a similar situation and what your views or solution was.

A: Well I have been using Jenkins for a long time, but our shop is a Java shop. If you are currently using TFS then you are probably using the Microsoft stack. So long as there is a command-line compiler available you can use Jenkins.
Jenkins home turf is building Java code (retrieved from Git, SVN or CVS) and saving the compiled results into a Nexus repository. However it is easy to create jobs that have no Java component. A job is simply a command line script. If you are familiar with Linux, it is like having cron jobs with a capable management interface on top. You can easily set up a Jenkins job that collects a bunch of parameters on screen, then runs your script with the collected parameters. Some of the tasks we use Jenkins for are:

*

*Compiling and releasing Java code

*Assembling and releasing batch process code (.zip files) that often have no Java component at all.

*Deploying code to various execution environments (the job retrieves the code from Nexus, SSH's to the server, copies the code to the right place and bounces the server)

*Running nightly batch jobs. This has nothing to do with code building but works very well.

Jenkins will provide a nice interface for monitoring build progress, and keeps all the console output in easy to access files. It also supports jobs running in parallel ("flows").
One quirk is that everything is a "build" in Jenkins terminology. It looks a bit strange to see "build failed" messages when a deployment job fails.
I suspect there are some third-party plugins available that may make using the Microsoft stack less painful.
So in short, it will do the job nicely, but you will need to do some work to write your jobs. Why not download and install it, and give it a try?

A: It's now becoming a distant memory...A few years back I worked with TFS, C# and C++ for commercial products. The main take away from that was that MSBUILD was our friend. It was the execution engine that TFS Build used to do the build steps. Once we figured out how to get our builds to run from MSBUILD command line, with a bit of script around them, we never depended on TFS build agents or Visual Studio for builds again.
At that time licensing was no problem. Our MSDN licenses covered everything needed Any of this may have changed in recent years. The C# compiler was included in .Net Framework and didn't even require visual studio. Some Microsoft technologies beyond straight C# had more dependencies and complexity.
There is an MSBUILD plugin for Jenkins. https://wiki.jenkins-ci.org/display/JENKINS/MSBuild+Plugin
I have never used that. But it seems worth a look.
Having used Jenkins with Java (Maven and Gradle instead of MSBUILD) and iOS XCode projects, I find it simpler to deal with than TFS. It's worth a look. With luck maybe the plug-in works well and no scripting needed. If I were working with C# again, I would give it a try.


text:
Q: GridView SelectCommand missing WHERE at runtime I've got a GridView.  My SelectCommand in the code works if I copy and paste it into SQL Server Management Studio.  It executes fine.
If I run the page and click Edit for any row I get the error:

"Incorrect syntax near the keyword 'IS'."

I've tried to see what's going on using SQL Server Profiler.  Here's what the SelectCommand looks like and what SQL is receiving...
SelectCommand from supplies.ascx
SELECT some stuff FROM here WHERE (this IS NULL) and (that=1) ORDER BY this DESC

SQL Server Profiler reports
SELECT some stuff FROM here (this IS NULL) and (that=1) ORDER BY this DESC

I didn't put any code here because I'm not really sure what would be relevant and didn't want to load up the post with unnecessary lines of code.  Please let me know what you'd like to see to help.
Requested code below.  I didn't put everything from the GridView in...It's pretty big.  If needed though I can update.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="fldSupReqID"
                DataSourceID="SqlDataSource1"
                EmptyDataText="There are no data records to display." AllowSorting="True"
                CellPadding="4" ForeColor="#333333" Font-Size="10px">
                <RowStyle BackColor="#EFF3FB" />

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
                DeleteCommand="DELETE FROM [tblSupplyRequests] WHERE [fldSupReqID] = @fldSupReqID"
                InsertCommand="INSERT INTO [tblSupplyRequests] ([fldManufacturerID], [fldItemID], [fldFeeTypeID], [fldRequestDate], [fldStamp], [fldAddedByUser], [fldBID]) VALUES (@fldManufacturerID, @fldItemID, @fldFeeTypeID, @fldRequestDate, @fldStamp, @fldAddedByUser, @fldBID)"

                ProviderName="<%$ ConnectionStrings:myConnectionString.ProviderName %>" SelectCommand="SELECT tblSupplyRequests.fldSupReqID, tblSupplyRequests.fldOrderToShipDate, tblSupplyRequests.fldBID AS BID, tblMerchantIDs.fldMerchantID AS MerchantID, salescontactinfo.sname_of_business AS [Merchant Name], salescontactinfo.scontactname1 AS Contact, salescontactinfo.scontactn1phone1 AS Phone, tblSupplyRequests.fldRequestDate, tblSupplyRequests.fldAddedByUser AS RequestedBy, INVtblManufacturers.fldManufacturerName AS [Term Manuf], INVtblInventoryItems_1.fldItemName AS [Term Model], INVtblInventoryTypes.fldInventoryTypename AS [Item Type], tblSupplyRequests.fldNumItemsRequested AS [Num Items], tblSupplyRequests.fldPaperItemID, tblSupplyRequests.fldPerItemCost, INVtblInventoryItems.fldMiscDesc, tblSupplyRequests.fldPersonCalling, tblSupplyRequests.fldTitlePersonCalling, tblSupplyRequests.fldNotes, salescontactinfo.sstate, tblSupplyRequests.fldManufacturerID, tblSupplyRequests.fldItemID, tblSupplyRequests.fldStamp, tblSupplyRequests.fldOrderToShipDate AS Expr1, tblSupplyRequests.fldOrderToShipBy FROM INVtblInventoryItems INNER JOIN tblSupplyRequests INNER JOIN salescontactinfo ON tblSupplyRequests.fldBID = salescontactinfo.sbusinessid LEFT OUTER JOIN tblMerchantIDs ON salescontactinfo.sbusinessid = tblMerchantIDs.fldBID LEFT OUTER JOIN INVtblManufacturers ON tblSupplyRequests.fldManufacturerID = INVtblManufacturers.fldManufacturerID ON INVtblInventoryItems.fldItemID = tblSupplyRequests.fldPaperItemID LEFT OUTER JOIN INVtblInventoryTypes ON tblSupplyRequests.fldInventoryTypeID = INVtblInventoryTypes.fldInventoryTypeID LEFT OUTER JOIN INVtblInventoryItems AS INVtblInventoryItems_1 ON tblSupplyRequests.fldItemID = INVtblInventoryItems_1.fldItemID WHERE (tblSupplyRequests.fldOrderToShipDate IS NULL) AND (tblMerchantIDs.fldMIDStatusID=1) ORDER BY tblSupplyRequests.fldRequestDate DESC"

                UpdateCommand="UPDATE tblSupplyRequests SET fldOrderToShipDate=@fldOrderToShipDate, fldNotes = @fldNotes, fldTitlePersonCalling = @fldTitlePersonCalling, fldPersonCalling = @fldPersonCalling, fldRequestDate = @fldRequestDate WHERE (fldSupReqID = @fldSupReqID)">
                <DeleteParameters>
                    <asp:Parameter Name="fldSupReqID" Type="Int32" />
                </DeleteParameters>
                <InsertParameters>
                    <asp:Parameter Name="fldManufacturerID" Type="Int32" />
                    <asp:Parameter Name="fldItemID" Type="Int32" />
                    <asp:Parameter Name="fldFeeTypeID" Type="Int32" />
                    <asp:Parameter Name="fldRequestDate" Type="DateTime" />
                    <asp:Parameter Name="fldStamp" Type="DateTime" />
                    <asp:Parameter Name="fldAddedByUser" Type="String" />
                    <asp:Parameter Name="fldBID" Type="Int32" />
                </InsertParameters>
                <UpdateParameters>
                    <asp:Parameter Name="fldOrderToShipDate" Type="DateTime" />
                    <asp:Parameter Name="fldNotes" Type="String" />
                    <asp:Parameter Name="fldTitlePersonCalling" Type="String" />
                    <asp:Parameter Name="fldPersonCalling" Type="String" />
                    <asp:Parameter Name="fldRequestDate" Type="DateTime" />
                    <asp:Parameter Name="fldSupReqID" Type="Int32" />
                </UpdateParameters>
            </asp:SqlDataSource>

And here's what SQL Server Profiler catches...
SELECT tblSupplyRequests.fldSupReqID, tblSupplyRequests.fldOrderToShipDate, tblSupplyRequests.fldBID AS BID, tblMerchantIDs.fldMerchantID AS MerchantID, salescontactinfo.sname_of_business AS [Merchant Name], salescontactinfo.scontactname1 AS Contact, salescontactinfo.scontactn1phone1 AS Phone, tblSupplyRequests.fldRequestDate, tblSupplyRequests.fldAddedByUser AS RequestedBy, INVtblManufacturers.fldManufacturerName AS [Term Manuf], INVtblInventoryItems_1.fldItemName AS [Term Model], INVtblInventoryTypes.fldInventoryTypename AS [Item Type], tblSupplyRequests.fldNumItemsRequested AS [Num Items], tblSupplyRequests.fldPaperItemID, tblSupplyRequests.fldPerItemCost, INVtblInventoryItems.fldMiscDesc, tblSupplyRequests.fldPersonCalling, tblSupplyRequests.fldTitlePersonCalling, tblSupplyRequests.fldNotes, salescontactinfo.sstate, tblSupplyRequests.fldManufacturerID, tblSupplyRequests.fldItemID, tblSupplyRequests.fldStamp, tblSupplyRequests.fldOrderToShipDate AS Expr1, tblSupplyRequests.fldOrderToShipBy FROM INVtblInventoryItems INNER JOIN tblSupplyRequests INNER JOIN salescontactinfo ON tblSupplyRequests.fldBID = salescontactinfo.sbusinessid LEFT OUTER JOIN tblMerchantIDs ON salescontactinfo.sbusinessid = tblMerchantIDs.fldBID LEFT OUTER JOIN INVtblManufacturers ON tblSupplyRequests.fldManufacturerID = INVtblManufacturers.fldManufacturerID ON INVtblInventoryItems.fldItemID = tblSupplyRequests.fldPaperItemID LEFT OUTER JOIN INVtblInventoryTypes ON tblSupplyRequests.fldInventoryTypeID = INVtblInventoryTypes.fldInventoryTypeID LEFT OUTER JOIN INVtblInventoryItems AS INVtblInventoryItems_1 ON tblSupplyRequests.fldItemID = INVtblInventoryItems_1.fldItemID  (tblSupplyRequests.fldOrderToShipDate IS NULL) AND (tblMerchantIDs.fldMIDStatusID=1) ORDER BY tblSupplyRequests.fldRequestDate DESC

A: I hate to say this, but it could just be that ASP.NET is parsing the query incorrectly because of all the nested INNER JOINs that precede it all on one line.  I wonder if formatting your SQL would help at all?  There is a very cool tool online for neatly formatting your SQL statements.
Here's the formatted version of your SQLDataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>"
    DeleteCommand=" DELETE FROM [tblSupplyRequests]
                    WHERE  [fldSupReqID] = @fldSupReqID"
    InsertCommand=" INSERT INTO [tblSupplyRequests] ([fldManufacturerID],[fldItemID],[fldFeeTypeID],[fldRequestDate],[fldStamp],[fldAddedByUser],[fldBID])
                    VALUES (@fldManufacturerID,@fldItemID,@fldFeeTypeID,@fldRequestDate,@fldStamp,@fldAddedByUser,@fldBID)"
    ProviderName="<%$ ConnectionStrings:myConnectionString.ProviderName %>"
    SelectCommand=" SELECT tblsupplyrequests.fldsupreqid,
                           tblsupplyrequests.fldordertoshipdate,
                           tblsupplyrequests.fldbid                  AS bid,
                           tblmerchantids.fldmerchantid              AS merchantid,
                           salescontactinfo.sname_of_business        AS [Merchant Name],
                           salescontactinfo.scontactname1            AS contact,
                           salescontactinfo.scontactn1phone1         AS phone,
                           tblsupplyrequests.fldrequestdate,
                           tblsupplyrequests.fldaddedbyuser          AS requestedby,
                           invtblmanufacturers.fldmanufacturername   AS [Term Manuf],
                           invtblinventoryitems_1.flditemname        AS [Term Model],
                           invtblinventorytypes.fldinventorytypename AS [Item Type],
                           tblsupplyrequests.fldnumitemsrequested    AS [Num Items],
                           tblsupplyrequests.fldpaperitemid,
                           tblsupplyrequests.fldperitemcost,
                           invtblinventoryitems.fldmiscdesc,
                           tblsupplyrequests.fldpersoncalling,
                           tblsupplyrequests.fldtitlepersoncalling,
                           tblsupplyrequests.fldnotes,
                           salescontactinfo.sstate,
                           tblsupplyrequests.fldmanufacturerid,
                           tblsupplyrequests.flditemid,
                           tblsupplyrequests.fldstamp,
                           tblsupplyrequests.fldordertoshipdate      AS expr1,
                           tblsupplyrequests.fldordertoshipby
                    FROM   invtblinventoryitems
                           INNER JOIN tblsupplyrequests
                                      INNER JOIN salescontactinfo
                                        ON tblsupplyrequests.fldbid = salescontactinfo.sbusinessid
                                      LEFT OUTER JOIN tblmerchantids
                                        ON salescontactinfo.sbusinessid = tblmerchantids.fldbid
                                      LEFT OUTER JOIN invtblmanufacturers
                                        ON tblsupplyrequests.fldmanufacturerid = invtblmanufacturers.fldmanufacturerid
                             ON invtblinventoryitems.flditemid = tblsupplyrequests.fldpaperitemid
                           LEFT OUTER JOIN invtblinventorytypes
                             ON tblsupplyrequests.fldinventorytypeid = invtblinventorytypes.fldinventorytypeid
                           LEFT OUTER JOIN invtblinventoryitems AS invtblinventoryitems_1
                             ON tblsupplyrequests.flditemid = invtblinventoryitems_1.flditemid
                    WHERE  ( tblsupplyrequests.fldordertoshipdate IS NULL )
                           AND ( tblmerchantids.fldmidstatusid = 1 )
                    ORDER  BY tblsupplyrequests.fldrequestdate DESC"
    UpdateCommand=" UPDATE tblsupplyrequests
                    SET    fldordertoshipdate = @fldOrderToShipDate,
                           fldnotes = @fldNotes,
                           fldtitlepersoncalling = @fldTitlePersonCalling,
                           fldpersoncalling = @fldPersonCalling,
                           fldrequestdate = @fldRequestDate
                    WHERE  ( fldsupreqid = @fldSupReqID )" >
    <DeleteParameters>
        <asp:Parameter Name="fldSupReqID" Type="Int32" />
    </DeleteParameters>
    <InsertParameters>
        <asp:Parameter Name="fldManufacturerID" Type="Int32" />
        <asp:Parameter Name="fldItemID" Type="Int32" />
        <asp:Parameter Name="fldFeeTypeID" Type="Int32" />
        <asp:Parameter Name="fldRequestDate" Type="DateTime" />
        <asp:Parameter Name="fldStamp" Type="DateTime" />
        <asp:Parameter Name="fldAddedByUser" Type="String" />
        <asp:Parameter Name="fldBID" Type="Int32" />
    </InsertParameters>
    <UpdateParameters>
        <asp:Parameter Name="fldOrderToShipDate" Type="DateTime" />
        <asp:Parameter Name="fldNotes" Type="String" />
        <asp:Parameter Name="fldTitlePersonCalling" Type="String" />
        <asp:Parameter Name="fldPersonCalling" Type="String" />
        <asp:Parameter Name="fldRequestDate" Type="DateTime" />
        <asp:Parameter Name="fldSupReqID" Type="Int32" />
    </UpdateParameters>
</asp:SqlDataSource>

Note: if your queries in the SQLDataSource are getting this complex, you may want to consider moving this logic into a class / data access layer for future maintainability.  Having said that, I understand that sometimes you are stuck with what you have for the time-being =)  Good luck!


text:
Q: Which of these is grammatically correct? "lay foundation to" or "lay foundation for"? The last line in one my admission letters is "...and also to lay foundation to my long term career goals."
Is it more correct for me to write "lay foundation for" ?

A: The answer is "to lay the foundation for".


text:
Q: Rails 7, React & Esbuild - Static assets not served in production I have created a simple new Rails 7 project from scratch with Esbuild and React to get to know these, and they indeed feel like a step up from Webpack, except I can't manage to have my static files (ie image) served in production.
I have an Esbuild config file:
// esbuild.config.js

const path = require('path');

require("esbuild").build({
  entryPoints: ["application.jsx"],
  bundle: true,
  outdir: path.join(process.cwd(), "app/assets/builds"),
  absWorkingDir: path.join(process.cwd(), "app/javascript"),
  publicPath: "assets",
  sourcemap: true,
  watch: process.argv.includes('--watch'),
  plugins: [],
  loader: {
    '.js': 'jsx',
    '.jpg': 'file',
    '.png': 'file',
    '.MOV': 'file'
  },
}).catch(() => process.exit(1));

I store my images in the app/javascript/images/ folder, and import and use them in a React component like that (for example):
import MyImage from "./images/myimage.jpg"
import styled from "styled-components";
//...

const SomeStyledComponent = styled.div`
    background-image: url(${MyImage});
`

In development, everything works fine, Esbuild copies the images in the app/assets/builds/ folder, fingerprints them, and prepends all the images url with the publicPath property of my Esbuild config. The above image for example then has the relative url assets/myimage-FINGERPRINT.jpg which is served correctly in development.
Then things get complicated in production (production here being just a Docker container built for production - I don't add the Dockerfile to keep things simple as I don't think it would help, but happy to provide it of course).
In my production.rb I have added the following:
config.public_file_server.enabled = true

(which will be replaced by an environment variable later)
The assets precompiling succeeds, and my images are in the app/public/assets/ folder, fingerprinted once more by Sprockets this time (from what I understand), but now I get 404. I have tried changing Esbuild publicPath and have tried to get the images directly in my browser, but whatever I try (assets, public, public/assets), nothing work and I am running out of ideas.
I have temporary fix which is to change the loader for images to dataurl, but that does not feel like a good practice, as my compiled javascript is going to explode.
Thank you for your help!

A: I ran into a similar issue, and by looking at the answers to https://github.com/rails/jsbundling-rails/issues/76 and this PR: https://github.com/rails/sprockets/pull/726/files
I was able to figure out the proper setup that works.
in the build options, I changed
publicPath: "assets",

to
publicPath: "/assets",

(included the leading /, which was missing before and causing the wrong path to be used)
and then added the following option
assetNames: "[name]-[hash].digested",

which, as you might be able to tell from the linked PR, would prevent Sprockets from adding an additional layer of fingerprinting.
I hope that helps.


text:
Q: NetBeans platform default TopComponent positioning as anonymousMode_1 how do i set default position of two TopComponents in 'editor' mode not in tabs, like this:

but one next to each other; like this:

?

A: The key to solving this problem was in creating two new different modes with the same desired kind of "editor", same vertical and horizontal "weights", but different horizontal "numbers". Here is how:
Mp3PaneLeft.wsmode
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mode PUBLIC "-//NetBeans//DTD Mode Properties 2.3//EN" "http://www.netbeans.org/dtds/mode-properties2_3.dtd">
<mode version="2.3">
    <name  unique="Mp3PaneLeft" />
    <kind  type="editor" />
    <state type="joined" />
    <constraints>
        <path orientation="vertical" number="20" weight="0.2"/>
        <path orientation="horizontal" number="20" weight="0.5"/>
    </constraints>
    <empty-behavior permanent="true" />
</mode>

Mp3PaneRight.wsmode
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mode PUBLIC "-//NetBeans//DTD Mode Properties 2.3//EN" "http://www.netbeans.org/dtds/mode-properties2_3.dtd">
<mode version="2.3">
    <name  unique="Mp3PaneRight" />
    <kind  type="editor" />
    <state type="joined" />
    <constraints>
        <path orientation="vertical" number="20" weight="0.2"/>
        <path orientation="horizontal" number="40" weight="0.5"/>
    </constraints>
    <empty-behavior permanent="true" />
</mode>

And here is registration of two .wsmodes in the layer.xml:
layer.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.2//EN" "http://www.netbeans.org/dtds/filesystem-1_2.dtd">
<filesystem>
    <folder name="Windows2">
        <folder name="Modes">
            <file name="Mp3PaneLeft.wsmode" url="Mp3PaneLeft.wsmode"/>
            <file name="Mp3PaneRight.wsmode" url="Mp3PaneRight.wsmode"/>
        </folder>
    </folder>
</filesystem>

Now it is possible to use
@TopComponent.Registration(mode = "Mp3PaneLeft", openAtStartup = true, position = 10)

and
@TopComponent.Registration(mode = "Mp3PaneRight", openAtStartup = true,position = 20)

annotations for left and right TopComponent panes respectively.
Also do not forget to clean-build your porject each time you changing this defaults - they're persistently getting overridden by user re-positioning of TopComponents easily.


text:
Q: MDI model or Dock Windows? In the QT application we develop we need to display several 'Viewer windows' (to display data in XY plane, YX plane, XZ plane and in 3D).
We were hoping to use MDI application model, but later the client asked for a requirement to drag and view 'Viewer windows' in multiple desktops (using multiple monitors).
This can not be done using MDI window model, because we cannot move MDI window outside the Main Application Window.
Only possible way is to use Dock windows because they can be undocked from Main Application Window and move into other desktops, but Dock windows primary used for tool-palettes or utility windows.
(http://doc.qt.nokia.com/4.6/qdockwidget.html#details)
Is it a good practice to use Dock window for our requirement?

A: I would not use the QDockWindow since it seems you will not use the client area. In addition, you don't want docking to the MainWindow borders but just added the widget to the MainWindow.
I think you can try to use multiple QWidget with a QGridLayout. When dragging QWidget outside of the MainWindow, just remove QWidget from the layout. When dragging inside the MainWindow add the QWidget to the right place in the QGridLayout. With this method you can too switch widget's places into the Main Window.
I don't know if it is clear enough but I'm thinking to the same way it is done in QtDesigner when dragging new elements into a layout. When dragging widgets you can see the place where it will be added when releasing the mouse button.
In my mind this method can be the one you are searching for.
Hope that helps


text:
Q: Having issue with special characters when converting files from BQ to GCS CSV using BigQueryToCloudStorageOperator Airflow We have created and airflow dag where we are reading a BigQuery table using a sql query and storing it into a transient table, then using the BigQueryToCloudStorageOperator Airflow operator converting it to a CSV file. We are having an issue with the special characters which are being converting it to junk in the file. eg :-hermès is being converted to hermès. I cannot find any options to provide encoding types while using BigQueryToCloudStorageOperator. Need a solution for this.
Thanks for the help


text:
Q: Issue with validation message of associated model I have two models Student and Image. A student may have multiple images, maximum 4 images.
In my Student model I have added
has_many :images, dependent: :destroy

Image model
mount_uploader :image, PhotoUploader

belongs_to :student, foreign_key: 'student_id'

validate do |record|
  record.validate_image_number
end

def validate_image_number
  return unless self.student
  if self.student.images(:reload).count >= 4
    errors.add(:base, 'Image limit exceeded')
  end
end

StudentController.rb
Student.transaction do
  @student.save!

  if params[:images].present?
    params[:images]['image'].each do |a|
      @image = @student.images.create!(image: a)
    end
  end
end
return render json: { 'status': 'success'}
rescue => e
  puts e
  if @student
    return render json: {'errors': @student.errors}, statuts: 422
  else
    return render json: { 'status': 'failure'}
  end

I am now getting student.errors as {}, if I upload more than 4 images, but the exception message is 'Image limit exceeded'. How can I add the error message of Image model in Student error list


text:
Q: Cassandra memory consumption I have installed cassandra in ubuntu system. cassandra version is 3.11.3
I wanted to check how much total amount of memory cassandra database is using. Other than top command kindly suggest some command or any other way using which i can come to know what total amount of memory is used by just the cassandra database in ubuntu.

A: Cassandra provides a command line interface for management. You can use nodetool info command to get information about how much Heap and Off Heap Memory is used.
It's also worth mentioning that Cassandra also takes heavy usage of page cache. Note that page cache isn't really occupied memory, you can read more about page cache with a simple web search. Execute the following command to see the current page cache on your machine (-m for megabytes): free -m

A: yes Cassandra provides a command line interface for management. You can use nodetool -u username -pw ********** info (if jmx is enabled ) command to get information about how much Heap and Off Heap Memory is used.
https://docs.datastax.com/en/cassandra/3.0/cassandra/tools/toolsInfo.html#toolsInfo__description


text:
Q: Proof of this theorem: $ tr(A^-)=\sum_{i=1}^r \lambda_i^{-1} $ If $A$ is an $n\times n$ symmetric matrix with $r$ nonzero characteristic roots $ \lambda_1,\lambda_2,...,\lambda_r$ then
$$ {\rm tr}(A^-)=\sum_{i=1}^r \lambda_i^{-1}. $$
Note:  $A^-$ is generalized inverse of $A$.

A: I assume "generalized inverse" is the Moore-Penrose pseudoinverse.
Both sides are invariant under unitary transformations, and they are equal for diagonal matrices.


text:
Q: How to solve this integral and have a result in term of arccos? This is the integral in order to made some approximation after the result. I need the result in term of $\arccos$. $$ \int_l^k\! \sqrt{\frac{R}{r} -1} \:\mathrm{d}r = \cos^{-1} (...). $$

A: Here's my suggestion. The minus sign suggests that the integrand would be the leg of some right triangle, where the other leg is $1$. Then the hypotenuse is $\sqrt{R/r}$. So we wind up with
$$\sqrt{R/r-1}=\tan(\theta) \\
r=R \cos(\theta)^2 \\
dr=-2R \cos(\theta) \sin(\theta) d \theta.$$
So your integral (limits aside for now) becomes
$$\int -2R \tan(\theta) \cos(\theta) \sin(\theta) d \theta = \int -2R \sin(\theta)^2 d \theta.$$
This should be easy to recognize; with power reduction you get
$$-R\theta + \frac{R\sin(2 \theta)}{2} + C = -R \theta + R \sin(\theta) \cos(\theta) + C.$$
Use the diagram I described in the first paragraph to simplify:
$$-R\arccos(\sqrt{r/R})+R\frac{\sqrt{R/r-1}}{\sqrt{R/r}}\frac{1}{\sqrt{R/r}} + C = -R \arccos(\sqrt{r/R})+r\sqrt{R/r-1} + C$$
Now you insert your limits. (I assume that $k,l \in [0,R]$.)
Also please check my work, because my answer seems quite different from Wolfram Alpha's answer.

A: Here are some hints to help you on your way. To get more help you should show more of your own effort.
First, find any indefinite integral of $\sqrt{\frac Rr-1}$. You will probably get an answer that has an arctangent in it. Let's say that the answer is
$$I=v+c\tan^{-1}(u)$$
where $u$ and $v$ are functions of $r$ and $c$ is a constant.
Then use the standard right triangle diagram to convert an arctangent to an arccosine. You will get:
$$\theta=\tan^{-1}(u)\quad\implies\quad\theta=\cos^{-1}\left( \frac 1{\sqrt{1+u^2}} \right)$$

Therefore you can convert your integral answer to
$$I=v+c\cos^{-1}\left( \frac 1{\sqrt{1+u^2}} \right)$$
Is that clear?

The problem with that answer is that it uses the arccosine function but is not in its entirety an arccosine. If your answer to your definite integral is in the appropriate range, you could always use this trivial answer:
$$I=\cos^{-1}\left(\cos(I)\right)$$
If your answer to your definite integral is not in the appropriate range then there is no answer to your question.


text:
Q: What is "enlightening" in the sentence? "Education is enlightening". What is "enlightening" in the sentence, gerund or participle? I think it's participle, because it's the second verb in the sentence which is continuous form.

A: Enlightening could be either a gerund or a participle, depending on the context. If used as an adjective, it is a participle; if used as a noun, it is a gerund, as my English teacher has taught. In the sentence, "Education is enlightening," the word "enlightening" is functioning as a predicate nominative, renaming education. In this instance, "enlightening" is a gerund.


text:
Q: How do I estimate when an upstream bugfix will reach my current install? Let's take this bug for example, of which the following fix exists upstream on the focal branch.
My current system is running bionic (Ubuntu 18.04.5 LTS) with kernel 5.4.0-47-generic (as installed by linux-image-generic-hwe-18.04)and I would like to get a rough idea of when this fix will be backported to my current system.
I'm going to wildly make the following uninformed guess...  I figured there are 2 ways a kernel bug fix reaches my system.
If the fix is included in an ABI bump a patch, which means it will be available once kernel 5.4.0-x-generic(where x > 47) becomes available in my package manager via an update to linux-image-generic-hwe-18.04.  Looking at the changelog for said package, it seems this happens roughly 2 weeks - 1 month (is this even correct??).
If the fix is not included in an ABI bump a patch, that means it will only be available on the next kernel release, i.e. 5.y.0-generic (where y > 4).  This means that it will only be available when Ubuntu 18.04.6 comes out (tentatively February 2021).
So how do I know which pathway a bug fix will follow?  Do my estimates make sense?  What is the correct way of estimating how long I'll have to live with a bug provided a fix is available upstream?

A: Short version
I think this particular fix should be arriving tomorrow or the day after.
Long Version
So I can help answer the general case for Ubuntu packages but it gets a little more murky for the kernel and doubly so for backported HWE kernels.  I've just gone through this process for two bugs I submitted, one for Open vSwitch and the other for GRUB.
If you find/fix a bug in an Ubuntu package, the default is to only fix it in the next major Ubuntu version (e.g. I found a bug in Focal's GRUB, it was only fixed in Groovy).  If the problem truly is a bug vs asking for additional functionality, you can submit it for a Stable Release Update (SRU) which then will applied to currently supported Ubuntu versions.  If the SRU is accepted, it goes into the "proposed" repository for 7 days during which time at least 1 person has to mark it as a successful fix and it has to pass automated testing.  After 7 days, it then goes into the live "updates" repository.
Looking at your referenced fix, it references bug #1892417 which was successfully submitted for a SRU.  If we look at the Focal proposed version we see that the code related to bug #1892417 is included.  It also appears looking at the package's metadata that this build took place on 10 September so I believe that it should be hitting the updates repository in the next day (assuming no problems).
What I cannot tell you is, in general, the frequency of kernel releases as there is a lot of churn there. They may do releases every 14 days, once a month, or as needed.  I also do not know when the updated Focal kernel gets backported to Bionic's HWE kernel.  Comparing the release dates for 5.4.0-47.51, this last step looks instantaneous.


text:
Q: Getting Oauth token in app engine endpoints I am looking for a way of obtaining the OAuth2 token from an app engine java endpoint.
I am aware of doing this, for example:
@ApiMethod(name = "getMyResponse", path = "getMyResponse", httpMethod = ApiMethod.HttpMethod.GET)
public MyResponse getMyResponse(final User user, HttpServletRequest request)
        throws UserUnauthorizedException {
    String authorizationHeader = request.getHeader("Authorization");
    String token = authorizationHeader.substring(7);
    //do something with the token here
}

However, i am looking for something a bit more "civilized", than parsing strings from the HTTP header (like using some API, for example). Any ideas?

A: If all you need to do is get the token, but that seems uncivilized, then I'd suggest writing it yourself. Any API you could possibly use would only add weight to your codebase. I would simply write a helper function like :
private static String getToken (HttpServletRequest req){
   String authorizationHeader = req.getHeader("Authorization");
   String token = authorizationHeader.substring(7);
   return token;
}

and then in your code just reference
String token = getToken(request);

and your code is now civilized.


text:
Q: SELECT DATA from many to many tables without repetead i have this project where i need to show this table on a webpage:
Result Table (one Bill can have one or many PurchaseOrder)

BILLID
DESCRIPTION
PO
PO_DESCRIPTION
HES

1
BILLING1
1001,1002
TEST1,TEST2
ABC,DFG

2
BILLING2
1003
TEST3
HIJ

Which its created based on 4 tables:
BillingTable

BILLID
DESCRIPTION
CREATEDAT

1
BILLING1
2022-01-03

2
BILLING2
2022-01-14

BillingPos Table (it had a relationship with BillingTable (many-to-one) and with HesTable (one to many)

ID
FK_BILLID
FK_HES_ID
CREATEDAT

1
1
1
2022-01-03

2
1
2
2022-01-03

3
2
3
2022-01-14

Hes Table: it have a relationship with PurchaseOrder Table

ID
HES_ID
FK_PO_ID
CREATEDAT

1
ABC
1
2022-01-01

2
DFG
2
2022-01-01

3
HIJ
3
2022-01-01

PurchaseOrder Table

ID
PURCHASEORDER
DESCRIPTION
CREATEDAT

1
1001
TEST1
2022-01-01

2
1002
TEST2
2022-01-01

3
1003
TEST3
2022-01-01

I Know i have to use GROUP_CONCAT to concatenate the POs, Description and HES in one row for the billing id but i can´t figure it out

A: Consider:
SELECT Billing.BillID, Billing.Description, Group_Concat(PurchaseOrder) AS PO,
Group_Concat(PurchaseOrder.Description) AS PO_Description, Group_Concat(HES_ID) AS HES
FROM Billing INNER JOIN (PurchaseOrder
INNER JOIN (HES INNER JOIN BillingPos
ON HES.ID = BillingPos.FK_HES_ID)
ON PurchaseOrder.ID = HES.FK_PO_ID)
ON Billing.BillID = BillingPos.FK_BilledID
GROUP BY BillID, Billing.Description;


text:
Q: SelectDateWidget - passing date range I am using SelectDateWidget and want to pass in a date range based on max and min date values from my database.
oldest = Item.objects.all().aggregate(Min('date'))['date__min']
start_year = Item.objects.get(date=oldest).date.year  # 2012

newest = Item.objects.all().aggregate(Max('date'))['date__max']
end_year = Item.objects.get(date=newest).date.year  # 2013

class MyForm(forms.Form):
    date_range = forms.DateField(widget=SelectDateWidget(years=range(start_year, end_year)))

The above shows the start_year only. This is the only choice to select.
This one below works well, and them both seem about the same to me.
date_range = forms.DateField(widget=SelectDateWidget(years=range(2008, 2013)))

Any suggestions please?

A: Your perception of the range function is off (the last argument of the range is not included in the list itself, its the limiter)
>> range(2012, 2013)
.. [2012]

You require an offset if you want to include 2013, e.g.
>> range(2012, 2014)
.. [2012, 2013]


text:
Q: Why does mass (gas) transfer between binary stars cause them to move apart? Some binaries, like Algol binaries, move monotonically apart from each other as one steals gas from the other.
Why?
On a naive level, shouldn't friction and such cause the two stars to move (rotate?, revolve?, etc.) more slowly, and lose velocity, and move closer to each other?  To a potential merger?

A: The angular momentum of a star in orbit is $m r^2 \omega$. Thus the total angular momentum of a binary system is constant (if no mass is lost from the system) and given by $$ J = (m_1 a_1^2 + m_2 a_2^2) \omega,$$
where $a = a_1 + a_2$ is the separation, $m_1 a_1 = m_2 a_2$, the total mass $m = m_1+m_2$ and (from Kepler's 3rd law) $a^3 \omega^2$ is constant (call it $\alpha$), if the mass lost by one star is accreted by the other.
Thus
$$ J = m_1 a_1 a \omega = m_1 a_1 a^{-1/2} \sqrt{\alpha}$$
and
$$ ma_1 = m_1 a_1 + m_2 a_1 = m_2 a$$
thus
$$J m\alpha^{-1/2} = m_1 m_2 \sqrt{a}$$
The LHS of the above expression is a constant, so the ratio of final to initial separation after any conservative mass loss is
$$\frac{a_f}{a_i} =\left(\frac{m_{1,i} m_{2,i}}{m_{1,f} m_{2,f}}\right)^2$$
The product $m_1 m_2$ is maximised (if the total mass is constant), when $m_1 = m_2$. Thus if mass is lost by the less massive star, then the final $m_1 m_2$ becomes smaller and the binary widens. This is what happens in an Algol-type system -- a less massive red giant loses mass to a more massive main sequence companion and the orbit widens.


text:
Q: Using ICapturegraphBuilder in DirectShow I am working on Direct Show samples, and have run into a problem. I want to multiplex video recievedfrom capture device to both preview and file, but do not know how.
The sample i use as base is playcap. In there, ICaptureGraphBuilder2 is used; in its documentation is function SetOutputFileName that presumably turns on file output.
In practive, though, file appears in the file system, but is always empty and is deleted when  the application exits. I suspect wrong usage of the API on my part.
Here is the code i am using:
    HRESULT hr;
IBaseFilter *pSrcFilter=NULL;

// Get DirectShow interfaces
hr = GetInterfaces();
if (FAILED(hr))
{
    Msg(TEXT("Failed to get video interfaces!  hr=0x%x"), hr);
    return hr;
}

// Attach the filter graph to the capture graph
hr = g_pCapture->SetFiltergraph(g_pGraph);
if (FAILED(hr))
{
    Msg(TEXT("Failed to set capture filter graph!  hr=0x%x"), hr);
    return hr;
}

// Use the system device enumerator and class enumerator to find
// a video capture/preview device, such as a desktop USB video camera.
hr = FindCaptureDevice(&pSrcFilter);
if (FAILED(hr))
{
    // Don't display a message because FindCaptureDevice will handle it
    return hr;
}

// Add Capture filter to our graph.
hr = g_pGraph->AddFilter(pSrcFilter, L"Video Capture");
if (FAILED(hr))
{
    Msg(TEXT("Couldn't add the capture filter to the graph!  hr=0x%x\r\n\r\n")
        TEXT("If you have a working video capture device, please make sure\r\n")
        TEXT("that it is connected and is not being used by another application.\r\n\r\n")
        TEXT("The sample will now close."), hr);
    pSrcFilter->Release();
    return hr;
}
IBaseFilter * pBaseFilter;
IFileSinkFilter  *pfSink;
// Attach the file writerto the capture graph
hr = g_pCapture->SetOutputFileName (&MEDIASUBTYPE_Avi,L"output.avi",&pBaseFilter,&pfSink);
if (FAILED(hr))
{
    Msg(TEXT("Failed to set capture filter graph!  hr=0x%x"), hr);
    return hr;
}
// Render the preview pin on the video capture filter
// Use this instead of g_pGraph->RenderFile
hr = g_pCapture->RenderStream (&PIN_CATEGORY_PREVIEW, &MEDIATYPE_Video,
                               pSrcFilter, NULL, NULL);
if (FAILED(hr))
{
    Msg(TEXT("Couldn't render the video capture stream.  hr=0x%x\r\n")
        TEXT("The capture device may already be in use by another application.\r\n\r\n")
        TEXT("The sample will now close."), hr);
    pSrcFilter->Release();
    return hr;
}
// Now that the filter has been added to the graph and we have
// rendered its stream, we can release this reference to the filter.
pSrcFilter->Release();

// Set video window style and position
hr = SetupVideoWindow();
if (FAILED(hr))
{
    Msg(TEXT("Couldn't initialize video window!  hr=0x%x"), hr);
    return hr;
}

// Add our graph to the running object table, which will allow
// the GraphEdit application to "spy" on our graph
hr = AddGraphToRot(g_pGraph, &g_dwGraphRegister);
if (FAILED(hr))
{
    Msg(TEXT("Failed to register filter graph with ROT!  hr=0x%x"), hr);
    g_dwGraphRegister = 0;
}
// Start previewing video data
hr = g_pMC->Run();
if (FAILED(hr))
{
    Msg(TEXT("Couldn't run the graph!  hr=0x%x"), hr);
    return hr;
}

// Remember current state
g_psCurrent = Running;

return S_OK;

How should i achieve functionality i want?

A: In above code you are passing NULL to RenderStream as last parameter.
At RenderStream msdn documentation
it is stated:
If the pSink parameter is NULL, the method tries to use a default renderer. For video it uses the Video Renderer, and for audio it uses the Audio Renderer (WaveOut) Filter.
On the same above link, please have a look at the code snippet:
pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi, L"C:\\Example.avi",
    &ppf, &pSink);
pBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Video,
    pCaptureFilter, NULL, ppf);

You might want to look at AmCap also.


text:
Q: Writing SSM ParameterStore update once when many are trying from Lambda? We've inherited an application that runs on Lambda. On initialization, this App reads a configuration stored on ParameterStore and if a certain value is out of date, then that value is updated and the app can continue.
The problem is that many users (about 7 concurrent at any one time) can run this app, and they could hit the same update nearly at the same time and therefore cause ParameterStore to throw a PutParameter throttle-back error.
To avoid that and to update the ParameterStore  value only once per day rather than on every run, we've devised a simple solution, and we're wanting to get some advice on whether it makes sense or not...
Here are the steps we're thinking:

*

*Random sleep between 1 and 10 seconds ("queue" up calls to minimize clashes -- perhaps this isn't necessary??)

*Does an S3 object exist for today: obj_MMDDYYYY (signals that the PStore update has been done today)

*If YES then skip updating ParameterStore value

*If NO then create S3 obj_MMDDYYYY (today's date),  run the Update ParameterStore value

Any advice appreciated.
Thanks!


text:
Q: JQuery code issues while calling functions on button click Am new to node.js and Jquery.
In the following code on the button click i have run a task and we cannot predict when will that task will complete
while completing the task i will get a test result and stored in  DB.
Here is my html code

        Running the test...

<button id="runBtn">RUN</button>

in button click first i write the code to run the task and we cannot predict when will it complete.After storing data in DB i have to fetch that data,it is also i have to call on the button click function.
$('#runBtn').click(function() {
var unitData
.....
.....
// For running the task
   $.ajax({
      type: "post",
      url: "/runTask",
      dataType: "json",
      data: unitData,
      success: function (value) {
        console.log("Data saved succesfully");
      },
    });

// For fetching the result of task

    $('#testResult').html(' Running the test...');
        $('#testResult').show();
        $.ajax({
          url: '/getReport',
          cache: false
        }).done(function (html) {
          $("#testResult").html( htm );
          $('#edit').removeAttr("disabled");
        }).fail(function () {
          $("#testResult").html("Failed to run the test");
          $('#edit').removeAttr("disabled");
        });

    })

What i need is on button click i have to display a spinner image with test is running...(we cannot predict when will test complte)and after test complete storing data in db(it is working fine) and have to show that data in webpage and disappear spinner image.
Now what happend is while i clicking the run button the test will run and at the same time calling the '/gerReport' and returing null value.I need to call /getReport only after the test result come and show the spinner image with text test is running..
.

A: Here you go:
var $testResultElement = $("#testResult"),
    onRunTaskCompleted = function () {
        console.log("Data saved succesfully");

        // Task running is complete, so now we can get the report
        $.ajax({
            url: '/getReport',
            cache: false
        }).done(function (html) {
            $testResultElement.html(html);
        }).fail(function () {
            $testResultElement.html("Failed to run the test");
        }).always(function () {
            $('#edit').removeAttr("disabled");
        });
    };

$('#runBtn').click(function() {
    // var unitData
    // .....
    // .....
    $testResultElement.html(' Running the test...').show();

    // For running the task
   $.ajax({
        type: "post",
        url: "/runTask",
        dataType: "json",
        data: unitData,
        success: onRunTaskCompleted
    });

Here's the logic:

*

*When button is clicked, first display the spinner (running the
test...)

*Start the task. Notice how I changed the success property of the ajax
call. I made a separate function to handle 'success' to make your
code a bit easier to follow (for yourself)

*onRunTaskCompleted is run when the task is done. It will do the call
'getReport'. The spinner is still spinning!

*When the call 'getReport' returns, we set the html that is returned,
or the message 'Failed to run the test'. I added an always-callback
to remove the disabled attribute from the edit button. This is
because you wanted to do it both on done and on fail, and always is
the ideal way, since it gets run both on done and fail.

A: You can use your code when save data record successfully something like that
$('#runBtn').click(function() {
var unitData
.....
.....
// For running the task
   $.ajax({
      type: "post",
      url: "/runTask",
      dataType: "json",
      data: unitData,
      success: function (value) {
        console.log("Data saved succesfully");

// For fetching the result of task
        $('#testResult').html(' Running the test...');
        $('#testResult').show();
       $.ajax({
         url: '/getReport',
        cache: false
       }).done(function (html) {
         $("#testResult").html( htm );
         $('#edit').removeAttr("disabled");
       }).fail(function () {
         $("#testResult").html("Failed to run the test");
         $('#edit').removeAttr("disabled");
       });

      },
    });
})


text:
Q: Only one eth adapter is working in Ubuntu under VirtualBox I have set up 2 network adapters in mu Ubuntu 16.04 VM: Nat and Host-Only, set up /etc/network/interface as follows:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto enp0s3
iface enp0s3 inet dhcp

#allow-hotplug enp0s8
auto enp0s8
iface enp0s8 inet static
    address 192.168.56.110
    netmask 255.255.255.0
    gateway 192.168.56.1

The problem I am facing that only one of the 2 network adapters is working at any time. With the set up above I can connect to my VM, but the there is WAN connection from the VM. I have followed advice in this question, but when I remove the gateway line, internet is working in the VM, but I cannot connect to the VM from my host.
Another (Debian) VM works fine with the same gateway setting.
What am I doing wrong?

A: I found the solution in this answer. The solution is to use
 network 192.168.56.0

Instead of
 gateway 192.168.56.1


text: Q: How to reduce the size of every input field from default 56px to 50px through out the project for vuetify components The vuetify's field have default 56px height , which I want to reduce to 50px through out the project., without giving height prop to every vuetify input component.How can I do that. I tried to update some class and gave a height to 50px , but that made 50px height for the vuetify components that were explicitly given a height prop with some pixels.


text:
Q: How do I use my custom logging configuration? using System;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
using Newtonsoft.Json.Linq;

namespace LoggingExample
{
    class Logging
    {

        static void Logging()
        {

                var config = new LoggingConfiguration();

                var consoleTarget = new ColoredConsoleTarget();
                config.AddTarget("console", consoleTarget);
                var fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);

                consoleTarget.Layout = "${message}";

                fileTarget.FileName = "C:/log.txt";
                fileTarget.Layout = "${message}";

                consoleTarget.UseDefaultRowHighlightingRules = true;

                string json = File.ReadAllText("config.json");
                JObject jo = JObject.Parse(json);
                string debugLevel = (string) jo.SelectToken("Logging_Properties.LogLevel");

                LogLevel level = TestDebugLevel(debugLevel) ? LogLevel.FromString(debugLevel) : LogLevel.Info;

                LoggingRule rule1 = new LoggingRule("Console", LogLevel.Debug, consoleTarget);
                LoggingRule rule2 = new LoggingRule("File", level, fileTarget);

                config.LoggingRules.Add(rule1);
                config.LoggingRules.Add(rule2);

                LogManager.Configuration = config;

        }

        static bool TestDebugLevel(string level)
        {
            switch (level.ToLower())
            {
                case "info":
                    return true;
                case "debug":
                    return true;
                case "warn":
                    return true;
                case "error":
                    return true;
                case "fatal":
                    return true;
                default:
                    return false;

            }
        }
    }

My application must contain a programatically configured logger, the only issue is that I have no idea how to use it. I think everything is written correctly but I have no idea how to actually call the the logger within the application. I know I have to use Logmanager.GetLogger() with the logger I want to use, either the console or file logger but when I try to nothing gets logged.

A: You aren't logging anything, but only configuring NLog.
You need to log to the logger, in this case, after calling Log() (this could be in another class)
var appConsoleLogger = LogManager.GetLogger("ConsoleLogger");
appConsoleLogger.Info("info log to console");

var appFileLogger = LogManager.GetLogger("FileLogger");
appFileLogger.Info("info log to file");

PS:  The name of your method is a bit confusing, I think it should "SetupLogging" instead of "Log"

A: I think you're missing one LogManager.ReconfigExistingLoggers()


text:
Q: Combine Arrays with similar values into a new array My array looks like this:
array(4) (
0 => array(3) (
    "id" => string(1) "2"
    "state" => string(8) "San Francisco"
    "options" => array(2) (
        "value" => string(1) "1"
        "label" => string(8) "SF1"
    )
)
1 => array(3) (
    "id" => string(1) "2"
    "state" => string(8) "San Francisco"
    "options" => array(2) (
        "value" => string(1) "2"
        "label" => string(6) "SF2"
    )
)
2 => array(3) (
    "id" => string(1) "1"
    "state" => string(7) "New Jersey"
    "options" => array(2) (
        "value" => string(1) "3"
        "label" => string(9) "NJ1"
    )
)
3 => array(3) (
    "id" => string(1) "1"
    "state" => string(7) "New Jersey"
    "options" => array(2) (
        "value" => string(1) "4"
        "label" => string(10) "NJ2"
    )
)

)
What I want to achieve is get an array with the options added on duplicate state names. So that I end up with San Francisco options having 2 arrays in it and so on for any other duplicate state names I get.
How do I do this in php?
What I would like to have is:
Combine the arrays so that the "options" part of "state" has the multiples. For example "San Franciso" would have its Options section as 2 arrays with SF1 and SF2. I hope that is clear.

A: I think you need something similar:
$output_array = array();

foreach($input_array as $input){
    $output_array[$input['state']][] = $input;
}

Demo


text:
Q: Elasticsearch exception : mappping depth in index has been exceeded I have setup an Elasticsearch cluster on Bonsai. I am using elasticsearch-rest-high-level-client library to read Twitter-tweets stored in Kafka and push them to the Elasticsearch index.
I getting below exception :
Exception in thread "main" ElasticsearchStatusException[Elasticsearch exception [type=illegal_argument_exception, reason=Limit of mapping depth [20] in index [twitter] has been exceeded due to object field [THIS CONTAINS ALL OF THE JSON MESSAGE RETRIEVED FROM KAFKA]
It seems my code is trying to put all the message as a single field. What could be going wrong?
IndexRequest indexRequest = new IndexRequest("twitter").source(jsonMessage, XContentType.JSON);
 IndexResponse indexResponse = restClient.index(indexRequest, RequestOptions.DEFAULT);

A: This error is about the depth of the Json you are trying to index. Default Mapping depth of 20 denotes that the Json you are trying to index can have fields going maximum of 20 levels deep. For example
For example in below json, shippingAddress is 3 levels deep
{
"order": {
    "orderNo": "test_order",
    "orderDate": "2020-01-01",
    "customer": {
        "customerName": "John Doe",
        "customerPhone": "555-555-5555",
        "shippingAddress": {
            "addressLine1": "test",
            "addressLine2": "test",
            "city": "test",
            "state": "test",
            "country": "test"
        }
    }
}

}
Try to optimize your document if possible. If not, the setting can be updated if really required,

index.mapping.depth.limit -
      The maximum depth for a field, which is measured as the number of inner objects. For instance, if all fields are defined at the root
  object level, then the depth is 1. If there is one object mapping,
  then the depth is 2, etc. The default is 20.

Check the documentation
https://www.elastic.co/guide/en/elasticsearch/reference/7.6/mapping.html#mapping-limit-settings

A: Similar issue I faced. The fix was to provide the json as string instead of the actual json.
In this case instead of providing actual json object as jsonMessage, provide the plain string object of that json.


text:
Q: What's the difference between "a contract with" and "a contract from"? What is the difference between "a contract with" and "a contract from"? For example, in the sentence

SpaceX has a $1.6 billion contract from NASA.

Can I replace "from" by "with" in this sentence? Or does "from" indicate something like the contract is made by NASA and endorsed by SpaceX, and if "with" is used, this information will be lost?

A: Speakers will often use words loosely. They will have in mind something which is related to the word they're using.
The contract no doubt involves supplying NASA with goods and/or services, and thus the contract is a kind of "order".  Vendors and suppliers receive such orders from customers.

We just got a big order from GM to supply them with ball bearings.
We just got a big contract from GM. loose, a little sloppy

So that sentence means merely that SpaceX has a $1.6 billion deal with NASA where NASA is the customer and SpaceX is the supplier.

A: I think this specific sentence you have here means that spacex is built or developed upon a contract that NASA had with someone. If you use "contract with", then I think spacex should be one of the parties in the contract.


text:
Q: Write Object[] in parquet file To write some csv data into parquet I can use Spark SQL. I write simple code like this:
org.apache.spark.sql.types.StructType schema = getSchema();
List<Object[]> data = getData();
List<Row> rows = data.stream().map(RowFactory::create).collect(Collectors.toList());
sparkSession.createDataFrame(rows, schema).write().parquet(path);

But now I need to do that without spark. I have org.apache.spark.sql.types.StructType schema. And I found library org.apache.parquet:parquet-hadoop:1.11.0 (https://javadoc.io/doc/org.apache.parquet/parquet-hadoop/1.11.0/index.html). In this library, class ParquetWriter is used to write data. To do that it has method write(T object) and required object of class WriteSupport<T> (with metadata), where T - data type to write.
I have two questions about this class:

*

*How can I simply convert org.apache.spark.sql.types.StructType schema to WriteSupport.

*How can I simply convert Row or Object[] to type T and how to define its type?

P.S.: I read about writing with Avro format and classes, but this is not what I want.


text:
Q: iPOJO and service damping The comparison table for iPOJO says it supports service damping, like Blueprint does. Does this just refer to temporal dependencies or other service dependencies as well?

A: Right now, only temporal dependencies are supporting damping. However temporal dependencies are just regular (optional) dependencies, so it does not change much.
In addition, it's planned to integrate the 'temporal' aspect directly in the core.


text:
Q: Time complexity of union We have a directed graph G=(V,E) ,at which each edge (u, v) in E has a relative value r(u, v) in R and 0<=r(u, v) <= 1, that represents the reliability , at a communication channel, from the vertex u to the vertex v.
Consider as r(u, v) the probability that the chanel from u to v will not fail the transfer and that the probabilities are independent.
I want to write an efficient algorithm that finds the most reliable path between two given nodes.
I have tried the following:
DIJKSTRA(G,r,s,t)
1.  INITIALIZE-SINGLE-SOURCE(G,s)
2.  S=Ø
3.  Q=G.V
4.  while Q != Ø
5.         u<-EXTRACT-MAX(Q)
6.         if (u=t) return d[t]
7.         S<-S U {u}
8.         for each vertex v in  G.Adj[u]
9.             RELAX(u,v,r)

INITIAL-SINGLE-SOURCE(G,s)
1. for each vertex v  in  V.G
2.      d[v]=-inf
3.      pi[v]=NIL
4. d[s]=1

RELAX(u,v,r)
 1. if d[v]<d[u]*r(u,v)
 2   d[v]<-d[u]*r(u,v)
 3.   pi[v]<-u

and I wanted to find the complexity of the algorithm.
The time complexity of INITIALIZE-SINGLE-SOURCE(G,s) is O(|V|).
The time complexity of the line 4 is O(1).
The time complexity of the line 5 is O(|V|).
The time complexity of the line 7 is O(log(|V|)).
The time complexity of the line 8 is O(1).
Which is the time complexityof the command S<-S U {u} ?
The line 10 is executed in total  O(Σ_{v \in V} deg(v))=O(E)  times and the time complexity of RELAX is O(1).
So the time complexity of the algorithm is equal to the time complexity of the lines (3-9)+O(E).
Which is the time complexity of the union?

A: I think that the solution should be based on the classic Dijkstra algorithm (complexity of which is well-known), as you suggested, however in your solution you define the "shortest path" problem incorrectly.
Note that the probability of A and B is p(A) * p(B) (if they're independent). Hence, you should find a path, whose multiplication of edges is maximized. Whereas Dijkstra algorithm finds the path whose sum of edges is minimized.
To overcome this issue you should define the weight of your edges as:
R*(u, v) = -log ( R(u, v) )
By introducing the logarithm, you convert multiplicative problem to additive.

A:
So the time complexity of the algorithm is equal to the time
  complexity of the lines (3-9)+O(E). Which is the time complexity of
  the union?

No, it is not the complexity of the union, union can be done pretty efficiently if you are using hash table for example. Moreover, since you use S only for the union, it seems to be redundant.
The complexity of the algorithm also depends heavily on your EXTRACT-MAX(Q) function (usually it is logarithmic in the size of the Q, so logV per iteration), and on RELAX(u,v,r) (which is also usually logarithmic in the size of Q, since you need to update entries in your priority queue).
As expected, this brings us to the same complexity of original Dijkstra's algorithm, which is O(E+VlogV) or O(ElogV), depending on implementation of your priority queue.


text:
Q: Location of files in classpath section of web.xml inside WAR (spring application) I am new to spring. While going through an application I found that its web.xml contains the following -
<context-param>
    <param-value>
        classpath:com/abc/def/ghijkl.xml
    </param-value>
</context-param>

I am trying to understand that when you build a WAR of this application, does the ghijkl.xml file get compiled too?
I have been digging into the WAR and havent found any refernce to the xml files there.
Can someone please guide me through this?

A: Context parameters which can be read from all servlets in your application, in Spring project this is used as below.
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:context.xml</param-value>
    </context-param>

You declare all servlets can access too these beans which are defined in context.xml.

I am trying to understand that when you build a WAR of this
  application, does the ghijkl.xml file get compiled too?

xml files are not compiled, they are used in runtime when the application is start(deploy to application server and initial start)

I have been digging into the WAR and havent found any refernce to the
  xml files there

It should some reference if it is not you get an runtime exception when you start your application like below stacktrace
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/abc/def/ghijkl.xml]; nested exception is java.io.FileNotFoundException: class path resource [com/abc/def/ghijkl.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181)
    at  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.io.FileNotFoundException: class path resource [sasa.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 21 more


text:
Q: Windows Phone Emulator Fails to Start I am unable to get the Windows Phone 8 Emulator to start.
From Visual Studio 2013 I create a new Windows Phone 8 Application and press F5.
The emulator hangs on the screen below.  When I close the window there is an error listged in Visual Studio saying "Invalid pointer"


text:
Q: Why is the energy of quantum harmonic oscillator independent of its amplitude? The energy of a harmonic oscillator with amplitude $A$, frequency $\omega$, and mass $m$ is
$$E=\frac 12 m \omega^2A^2 \, .$$
It is intuitive to think that the energy depends on the amplitude because more the amplitude means that the oscillator has more energy, and similarly if the angular frequency is high even then the energy will be more.
Now let's consider a quantum harmonic oscillator (QHO).
The energy is
$$E=\left( n+ \frac 12 \right ) h\nu \, .$$
No amplitude term is there! This is odd because, even  if you argue that we are dealing in microscopic domain, we all can agree to the fact that, in general for any mass oscillating under some force, if we have more energy then the oscillator will move farther from its mean position and therefore will have more amplitude.
The relation of energy of QHO can't be wrong, where else the above conception of energy for an oscillator also doesn't seems to be wrong.

A: If you want to understand the classical limit of a harmonic oscillator, it is more meaningful to consider coherent states $$|\alpha \rangle = e^{-|\alpha|^2/2}\sum_{n=0}^\infty \frac{\alpha^n}{\sqrt{n!}} |n \rangle$$ for $\alpha$ an arbitrary complex number. Such states satisfy $a |\alpha \rangle  = \alpha |\alpha \rangle$. These states all saturate the Heisenberg uncertainty relation, and (unlike the higher excited states of the harmonic oscillator) do have associated dynamics, namely $e^{-i H t/\hbar} |\alpha \rangle = |\alpha e^{i \omega t} \rangle$ up to an overall phase.
One advantage to using a coherent state is that we can easily define the amplitude of the oscillation. The position and momentum expectation values are just $\langle x \rangle = \sqrt{\frac{2 \hbar}{m \omega}} \text{Re} \alpha$ and  $\langle p \rangle = \sqrt{2 m \omega \hbar} \text{Im} \alpha$ where $\text{Re} \alpha$ and $\text{Im} \alpha$ are the real and imaginary parts of $\alpha$, and both are normally distributed about their mean values. Restricting to real $\alpha$ means the oscillator is maximally displaced (as $\langle p \rangle = 0$), and so we would associate the amplitude $A = \sqrt{\frac{2 \hbar}{m \omega}} |\alpha|$ (in fact this remains correct if $\alpha$ is not real). The coherent state is not an energy eigenstate, but $\langle E \rangle = (|\alpha|^2+\frac12)\hbar \omega$. Then we see that $\langle E \rangle = \frac12 m \omega^2 A^2 + \frac12 \hbar \omega$. The first term matches the expression you have in the classical case. The second term is the ground state energy of the quantum harmonic oscillator. It is $0$ in the classical limit $\hbar \rightarrow 0$, and it can also be consistently removed if you choose to by just shifting the potential down by a constant $\frac12 \hbar \omega$.
While one can attempt to recover the classical limit from the higher energy eigenstates rather than from coherent states, it is quite a bit less satisfying to do so, as the high energy eigenstates describe a particle that is delocalized on a macroscopic scale (with similar issues in momentum space) and which does not evolve in time, while a classical particle in a harmonic oscillator should be localized at a scale much smaller than the length of its oscillation and should oscillate with characteristic angular frequency $\omega$ (which is not the case in a single eigenstate, only in a superposition of multiple energy eigenstates). Since energy eigenstates only depend on a single parameter $n$, even for large $n$ where the spacing between adjacent energy levels is negligible the energy eigenstates can not describe a single classical state (which depends on both initial position and momentum), only the time-averaged phase space density of the state, whereas since $\alpha$ is complex (2 real parameters) we have a one-to-one correspondence between classical states and coherent states as we saw above.

A: I ask students in my modern physics classes to deal with exactly this question, but I take the approach of having them find the physical extent of the motion in terms of a probability distribution function for both the classical and quantum cases.
The text I used most recently reads (in part):

Comparison of spatial probability distribution of a one-dimensional harmonic oscillator between the classical and quantum cases.
A quantum mechanical solution to the harmonic oscillator (mass
    of a spring) problem is developed in Townsend in section 4.3
    which gives
    \begin{align*}
      \psi_n(x) &= A_n H_n\left(\sqrt{\frac{m\omega}{\hbar}}x\right)
               \exp \left(-\frac{m\omega}{2\hbar}x^2\right) \,,
  \end{align*}
    where $A_n$ is a normalizing factor; $\omega = \sqrt{k/m}$ is
    the angular frequency of the oscillator; $m$ is the mass; and
    $H_n$ indicates the $n$th Hermite polynomial. These polynomials
    are tabulated in many places including Wikipedia.

*

*Plot the normalized probability distribution
  $P(x) = \psi_n^*(x) \psi_n(x)$ for three cases we care about
  ($n \in \{0, 1, 4\}$). Use $m = \omega = 1$

*Derive an expression for the normalized classical distribution in terms of position and total energy. (This is a purely classical computation; no wavefunctions are involved!)

*Using the fact that the $n$th solution to the quantum
  harmonic oscillator has energy
  $E_n = \left(n + \frac{1}{2}\right)\hbar\omega$, plot the classical
  probability distribution for the energy for each of the plots
  you did for the quantum cases.

And later I give them my computer plotted solutions for the cases I requested and a higher $n$ case:

The solid blue curves represent the classical PDF while the dashed red curves represent the quantum probability.
As you can see the spacial extent of the quantum and classical wave-functions track each other pretty well (there is, of course, some quantum penetration into the classical forbidden zone, but that is to be expected).
In the limit of high $n$ (i.e. macroscopic energy) these two cases approach each other very closely as expected from the correspondence principle.

A: You can calculate the variance of the position coordinate, $\sigma_x^2$, for a general eigenstate of the energy $\psi_n$ to be
$$\sigma_x^2=\frac{\hbar}{m\omega}\left(n+\frac{1}{2}\right) \, .$$
We can replace the $n$ dependance by energy dependence using the relation
$$E_n = \hbar\omega\left( n+\frac{1}{2} \right)$$
and we get
$$\sigma_x^2=\frac{\hbar}{m\omega}\frac{E_n}{\hbar\omega} \, .$$
Rearranging we get
$$E_n=m\omega^2\sigma_x^2 \, .$$
Remembering that for the classical case $$\sigma_x^2=\frac{1}{2}A^2$$ we retrieve the original relation in the quantum case as well.
Check the derivation at this link

A: Let's denote $A$ as $x$ while addressing this, as people usually do with the quantum simple harmonic oscillator (well, that or $q$ anyway). The full energy has a term you forgot due to the momentum, viz. $E=\frac{m\omega^2 x^2}{2}+\frac{p^2}{2m}$. In quantum mechanics, the states of definite energy don't have definite values for $x$ or $p$ (or even $x^2$ or $p^2$), although on average half the energy is due to each term. So the amplitude $x$ is a random variable; in fact, in the ground state it has a Normal distribution. (In higher-energy states, we must multiply the Gaussian pdf by a polynomial function.)