text:
Q: JAM 2005 Mathematics Question 7
This is a multiple-choice question having only a single correct option that appeared in JAM 2005 (an Exam in India). Now according to me options B, C, and D all should be correct but only option D is marked as correct. My reasoning behind B, C and D is that:
$$ T(x) = cx, I(x) = x$$
$$ \therefore (T -cI)x = T(x) -cI(x)=cx-cx=0 $$ for all $x \in \mathbb{R}^3 $. Therefore rank of the transformation $(T-cI) $ should be the dimension of its image, which is the vector $0$. Hence the rank of the transformation is $0$. So B, C and D should all be correct. Where am I wrong?

A: If $\text{rank}(T-cI) = 3$, i.e. full rank, $(T-cI)$ is invertible and the only solution of $(T-cI)x = 0$ is $x = 0$. However, we are given a non-zero $x\in\mathbb{R}^3$ such that $x\in \ker(T-cI)$, i.e. $Tx = cx$ so $\text{rank}(T-cI) \neq 3$.
The rank may be $0,1$ or $2$ - we don't know what it is exactly! This is the best we can say when we are given the existence of at least one $x$ such that $Tx=cx$. If $Tx = cx$ happens for all $x$, then $(T-cI) = 0$ (the zero operator on $\mathbb{R}^3$) - but this isn't the case!

A: AS J.W. Tanner said, we don't have $T(x)=cx$ for all $x$, but only for one.
Here the only thing you can say is $(T-cI)$ is not inversible because it is not injective, so its rank cannot be $3$.
But you can find $T$ such that its rank is $0$ (for instance $T=0$), or $1$ (for instance $T(x,y,z) = (x,y,0)$), or $2$ (for instance $T(x,y,z) = (x,0,0)$).
The concept behind this question is the one of eigenvalues.
cf https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors.


text:
Q: Iframe scroll issue .. What is the solution? I have two files on different servers, I am showing the data of one server into another using iframe, I am using below code
server.php (hosted on server A)
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
?>
this is itest

sdfsd

Go to Top

client.php (hosted on server B)

When I click on "Go to Top"  link I get "Uncaught SecurityError: Blocked a frame with origin "...." from accessing a frame with origin "...". Protocols, domains, and ports must match. "
What is the solution?

A: *

*Create a function in the parent frame that will scroll to the top (you have done this already in the form of goTop)

*Use that function in an event listener for a message event on the window object

*Use parent.postMessage from the document in the frame to send a message to the parent element

See the MDN postMessage page for examples.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt Multimedia: Library 'gstreamer' is not defined I have problem building QtMultimedia with GStreamer:
user@user-VirtualBox:~/sources/qt/build$ /usr/local/Qt-5.12.1/bin/qmake -r GST_VERSION=1.0 ../qt-everywhere-src-5.12.1/qtmultimedia/qtmultimedia.pro
Info: creating stash file /home/user/sources/qt/build/.qmake.stash
Info: creating cache file /home/user/sources/qt/build/.qmake.cache

Running configuration tests...
Checking for ALSA... no
Checking for GStreamer 1.0... yes
Checking for GStreamer App 1.0... yes
Checking for GStreamer encoding-profile.h... yes
Checking for GStreamer Photography 1.0... no
Checking for Video for Linux... yes
Checking for OpenAL... no
Checking for PulseAudio >= 0.9.10... no
Checking for libresourceqt5... no
Done running configuration tests.

Configure summary:

Qt Multimedia:
  ALSA ................................... no
  GStreamer 1.0 .......................... yes
  GStreamer 0.10 ......................... no
  Video for Linux ........................ yes
  OpenAL ................................. no
  PulseAudio ............................. no
  Resource Policy (libresourceqt5) ....... no
  Windows Audio Services ................. no
  DirectShow ............................. no
  Windows Media Foundation ............... no

Qt is now configured for building. Just run 'make'.
Once everything is built, you must run 'make install'.
Qt will be installed into '/usr/local/Qt-5.12.1'.

Prior to reconfiguration, make sure you remove any leftovers from
the previous build.

Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/src.pro [/home/user/sources/qt/build/src]
 Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/multimedia/multimedia.pro [/home/user/sources/qt/build/src/multimedia]
 Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/qtmultimediaquicktools/qtmultimediaquicktools.pro [/home/user/sources/qt/build/src/qtmultimediaquicktools]
 Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/imports/imports.pro [/home/user/sources/qt/build/src/imports]
  Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/imports/multimedia/multimedia.pro [/home/user/sources/qt/build/src/imports/multimedia]
 Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/multimediawidgets/multimediawidgets.pro [/home/user/sources/qt/build/src/multimediawidgets]
 Reading /home/user/sources/qt/qt-everywhere-src-5.12.1/qtmultimedia/src/gsttools/gsttools.pro [/home/user/sources/qt/build/src/gsttools]
Project ERROR: Library 'gstreamer' is not defined.

I believe that I've installed all required GStreamer components, but it looks like the GStreamer library was't found. Any ideas?
OS: Ubuntu 16.04
Installed GStreamer related packages:
gir1.2-gst-plugins-bad-1.0/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gir1.2-gst-plugins-base-0.10/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gir1.2-gst-plugins-base-1.0/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
gir1.2-gstreamer-0.10/xenial,now 0.10.36-1.5ubuntu1 i386 [installed,automatic]
gir1.2-gstreamer-1.0/xenial-updates,now 1.8.3-1~ubuntu0.1 i386 [installed]
gstreamer-qapt/xenial-updates,now 3.0.2-0ubuntu1.2 i386 [installed,automatic]
gstreamer0.10-alsa/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gstreamer0.10-doc/xenial,now 0.10.36-1.5ubuntu1 all [installed]
gstreamer0.10-gconf/xenial-updates,xenial-security,now 0.10.31-3+nmu4ubuntu2.16.04.3 i386 [installed]
gstreamer0.10-gnomevfs/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gstreamer0.10-nice/xenial,now 0.1.13-0ubuntu2 i386 [installed]
gstreamer0.10-plugins-base/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gstreamer0.10-plugins-base-apps/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gstreamer0.10-plugins-base-dbg/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gstreamer0.10-plugins-base-doc/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 all [installed]
gstreamer0.10-plugins-good/xenial-updates,xenial-security,now 0.10.31-3+nmu4ubuntu2.16.04.3 i386 [installed]
gstreamer0.10-plugins-good-dbg/xenial-updates,xenial-security,now 0.10.31-3+nmu4ubuntu2.16.04.3 i386 [installed]
gstreamer0.10-plugins-good-doc/xenial-updates,xenial-security,now 0.10.31-3+nmu4ubuntu2.16.04.3 all [installed]
gstreamer0.10-pulseaudio/xenial-updates,xenial-security,now 0.10.31-3+nmu4ubuntu2.16.04.3 i386 [installed]
gstreamer0.10-qapt/xenial-updates,now 3.0.2-0ubuntu1.2 all [installed]
gstreamer0.10-tools/xenial,now 0.10.36-1.5ubuntu1 i386 [installed]
gstreamer0.10-x/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed]
gstreamer1.0-alsa/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-clutter/xenial,now 2.0.18-1 i386 [installed]
gstreamer1.0-clutter-3.0/xenial,now 3.0.18-1 i386 [installed]
gstreamer1.0-crystalhd/xenial,now 1:0.0~git20110715.fdd2f19-11build1 i386 [installed]
gstreamer1.0-doc/xenial-updates,now 1.8.3-1~ubuntu0.1 all [installed]
gstreamer1.0-dvswitch/xenial,now 0.1.1-1 i386 [installed]
gstreamer1.0-espeak/xenial,now 0.4.0-1 i386 [installed]
gstreamer1.0-fluendo-mp3/xenial,now 0.10.32.debian-1 i386 [installed]
gstreamer1.0-hybris/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-libav/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-libav-dbg/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-nice/xenial,now 0.1.13-0ubuntu2 i386 [installed]
gstreamer1.0-packagekit/xenial-updates,now 0.8.17-4ubuntu6~gcc5.4ubuntu1.4 i386 [installed]
gstreamer1.0-plugins-bad/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-bad-dbg/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-bad-doc/xenial-updates,now 1.8.3-1ubuntu0.2 all [installed]
gstreamer1.0-plugins-bad-faad/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-bad-videoparsers/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-base/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-base-apps/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-base-dbg/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
gstreamer1.0-plugins-base-doc/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 all [installed]
gstreamer1.0-plugins-good/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.4 i386 [installed]
gstreamer1.0-plugins-good-dbg/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.4 i386 [installed]
gstreamer1.0-plugins-good-doc/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.4 all [installed]
gstreamer1.0-plugins-ugly/xenial-updates,now 1.8.3-1ubuntu0.1 i386 [installed]
gstreamer1.0-plugins-ugly-amr/xenial-updates,now 1.8.3-1ubuntu0.1 i386 [installed]
gstreamer1.0-plugins-ugly-dbg/xenial-updates,now 1.8.3-1ubuntu0.1 i386 [installed]
gstreamer1.0-plugins-ugly-doc/xenial-updates,now 1.8.3-1ubuntu0.1 all [installed]
gstreamer1.0-pocketsphinx/xenial,now 0.8.0+real5prealpha-1ubuntu2 i386 [installed]
gstreamer1.0-pulseaudio/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.4 i386 [installed]
gstreamer1.0-tools/xenial-updates,now 1.8.3-1~ubuntu0.1 i386 [installed]
gstreamer1.0-vaapi/xenial-updates,now 1.8.3-1~ubuntu0.1 i386 [installed]
gstreamer1.0-vaapi-doc/xenial-updates,now 1.8.3-1~ubuntu0.1 all [installed]
gstreamer1.0-x/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
libclutter-gst-3.0-0/xenial,now 3.0.18-1 i386 [installed]
libgstreamer-plugins-bad1.0-0/xenial-updates,now 1.8.3-1ubuntu0.2 i386 [installed,automatic]
libgstreamer-plugins-base0.10-0/xenial-updates,xenial-security,now 0.10.36-2ubuntu0.1 i386 [installed,automatic]
libgstreamer-plugins-base1.0-0/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
libgstreamer-plugins-base1.0-dev/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.2 i386 [installed]
libgstreamer-plugins-good1.0-0/xenial-updates,xenial-security,now 1.8.3-1ubuntu0.4 i386 [installed]
libgstreamer0.10-0/xenial,now 0.10.36-1.5ubuntu1 i386 [installed,automatic]
libgstreamer0.10-dev/xenial,now 0.10.36-1.5ubuntu1 i386 [installed,automatic]
libgstreamer1.0-0/xenial-updates,now 1.8.3-1~ubuntu0.1 i386 [installed]
libgstreamer1.0-0-dbg/xenial-updates,now 1.8.3-1~ubuntu0.1 i386 [installed]
libgstreamer1.0-dev/xenial-updates,now 1.8.3-1~ubuntu0.1 i386 [installed]
libqt5gstreamer-1.0-0/xenial,now 1.2.0-3 i386 [installed]
libqtgstreamer-1.0-0/xenial,now 1.2.0-3 i386 [installed]
libreoffice-avmedia-backend-gstreamer/xenial-updates,xenial-security,now 1:5.1.6~rc2-0ubuntu1~xenial6 i386 [installed]


text:
Q: How to update variable value inside while loop How can I make my SensorValue value update automatically? I am trying to make the SensorValue  variable update itself if the condition of SensorValue < Maxdryness or SensorValue >= Maxdryness is false at any time. I want to be able to switch my moisture sensor between dry and wet soil and make it turn my motor on or off as needed automatically.
  if(incomingData.indexOf("Auto on")>=0) // if received command is to turn system automatic
 {
  auto_flag = 1;
  message1 = "System is now automatic";
  send_message(message1); // Send a sms back to confirm that the motor is turned auto

  if (readSoil() >= Maxdryness)
     {
  Serial.println("Soil is good.\r");
  digitalWrite(wetSoil, HIGH);
  digitalWrite (drySoil, LOW);
  digitalWrite(motorPin1,LOW);
  digitalWrite(motorPin2,LOW);
  delay(1000);
    }

  else
   {
  Serial.println("Low Soil Moisture detected.\r");
  digitalWrite(wetSoil, LOW);
  digitalWrite (drySoil, HIGH);
  digitalWrite(motorPin1,HIGH);
  digitalWrite(motorPin2,LOW);
    }

  delay(1000);
  Serial.print("Soil Moisture = ");
  Serial.println(readSoil());
  delay(1000);//take a reading every second

  auto_flag = 0;
 }

My project involves sending SMS to turn the system on or off manually, Motor on, Motor off but I wanted an option to make the system run by itself without having to manually turn the motor on or off myself. Hence Auto on. This auto can be turned off by Auto off. I don't know how to make the system run while on Auto on to turn the motor off by switching my soil moisture probe from the dry soil into the wet soil and vice versa from wet to dry and turning the motor on.  If the condition of SensorValue is >= Maxdryness I want it to stop and only turn on when the value is < the Maxdryness.

A: If SensorValue is a sensor on a single pin, read that pin each loop or periodically!
Documentation for: analog pin and digital pin
It seems more likely from your code that it's an analog pin. It also doesn't appear from the docs (I haven't read them in a while) that you need to declare analog-readable pins in your setup() block (while you do for a digital pin), so it should be as simple to get the result as assigning the return from calling analogRead() to SensorValue
void loop() {
    ...
    SensorValue = analogRead(PIN_NUMBER);
    ...
}

You may want to do some massaging to linearize logarithmic outputs force the value into some range (0-100 rather than 0-1023), etc. but this would depend on unshown code and on the value the sensor pin represents.
If the sensor is something more advanced, such as living on an SPI bus, you'll need to do some extra work, but the setup will be similar. Whomever produced the component should provide some documentation. Arduino also provides an example for some generic Barometric Pressure Sensor if you need another reference.


text:
Q: Creating a very custom list I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>

filled by data from database.
Thank you

A: Here it is:
public class Avancee extends Activity {
    // Log tag
    private static final String TAG = MainActivity2.class.getSimpleName();

    // Movies json url
    private static final String url = "http://blabla.com/movie.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();
        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj

        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                        //Log.d(TAG, response.toString());
                        hidePDialog();

                        String result = getIntent().getStringExtra("ITEM_EXTRAA");
                        System.out.println(result);
                        try{
                            JSONArray ja = new JSONArray(result);
                            for (int i = 0; i < ja.length(); i++) {
                                try {

                                    JSONObject obj = ja.getJSONObject(i);
                                    Movie movie = new Movie();
                                    movie.setTitle(obj.getString("title"));
                                    movie.setLocation(obj.getString("location_search_text"));
                                    movie.setId(obj.getInt("id"));

                                    // adding movie to movies array
                                    movieList.add(movie);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        }catch(JSONException e){
                            Log.e("log_tag", "Error parsing data "+e.toString());
                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

It's the "id" that I want to get in the OnClick event.

A: use this code
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

Movie movie= movieList.get(position);

            }
        });

//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object


text:
Q: Remote vs local API for local web app development I'm developing both a REST API and a frontend web app. What's the best way to go about plugging the API into the web app while I'm developing locally on my machine?

*

*I could spin up a local copy of the API and point my web app to localhost:api-port, but that seems like unnecessary administrative work to have a local copy of both the API and web app running. Every time I want to do any development work I'll have to spin up the API, then spin up the web app.

*I could set up a remote dev environment and point my web app to dev.api.mydomain.com for local development, but it seems counter intuitive to have to set up a remote API sandbox to develop the web app locally.

*I could mock schemas and data with JSON files for local development. Instead of the web app doing a GET to api.mydomain.com it'll just read ./mock-data/some-resource.json. Seems like extra overhead to keep schemas and data matching production. Also wouldn't handle any logic that's built into the API on top of returning raw resources.
Best way forward?

A: Option 1 is definitely the best route in my experience.  I sometimes use Option 2, typically in scenarios such as hooking my local application into a remote database (that usually also has another instance of the application hooked up to it, do this with extreme caution).
Advantages of running all applications locally for development:

*

*You can debug integrations with your API without the hassle of a remote debugger.

*You can see the logs for both applications without needing to access a server (log analysis tools like Splunk can mitigate this point).

*You can do whatever you want to the underlying data of the application without affecting anyone else who works on the app (assuming you run the application database locally as well).

*You can prototype changes in both codebases without deploying.

Running everything locally does incur a setup cost (depending on how complex your runtime dependencies are, this can be anywhere between a few minutes to several days of work), but even so, the overhead is a one-time effort.

Every time I want to do any development work I'll have to spin up the API, then spin up the web app.

To address this, you could write a startup script that launches both services together, or use something like docker and docker-compose for running your apps locally.  Using docker-compose, if you register dependencies between docker containers in the docker-compose.yml file, the API will launch when you start the front-end app.  This kind of application orchestration is exactly what docker-compose is made for.  Also on the plus side, with Docker you only have to solve the environment setup problem once, and it can be highly repeatable for other developers.
The downside of Docker is that it can be tricky (or impossible) to hook an IDE debugger into the container depending on your runtime.  In those cases it may be best to set up your local development environment natively on the machine and use the startup script approach for orchestration of services.


text:
Q: Rails 3: Get current namespace? using a method :layout_for_namespace I set my app's layout depending on whether I am in frontend or backend, as the backend is using an namespace "admin".
I could not find a pretty way to find out which namespace I am, the only way I found is by parsing the string from params[:controller]. Of course that's easy, seems to be fail-safe and working good. But I am just wondering if there's a better, prepared, way to do this. Does anyone know?
Currently I am just using the following method:
def is_backend_namespace?
  params[:controller].index("admin/") == 0
end

Thanks in advance
Arne

A: In Rails 6, the controller class does not seem to have a namespace method on it.
The solution that seemed cleanest and worked for me in a view was: controller.class.module_parent
Specifically, if your namespace is Admin:: and you wanted 'admin', you'd do:
controller.class.module_parent.to_s.downcase

A: You can use:
self.class.parent == Admin

A: Outside the controller (e.g. in the views), use controller.class.name. You can turn this into a helper method like this:
module ApplicationHelper
  def admin?
    controller.class.name.split("::").first=="Admin"
  end
end

A: In both the controller and the views, you can parse controller_path, eg.:
namespace = controller_path.split('/').first

A: Rails 6
Accessing the namespace in the view?
do not use: controller.namespace.parent == Admin
the parent method will be removed in Rails 6.1
DEPRECATION WARNING: `Module#parent` has been renamed to `module_parent`. `parent` is deprecated and will be removed in Rails 6.1.

use module_parent instead:
controller.namespace.module_parent == Admin

A: Not much more elegant, but it uses the class instead of the params hash.  I am not aware of a "prepared" way to do this without some parsing.
self.class.to_s.split("::").first=="Admin"

A: Setting the namespace in application controller:
path = self.controller_path.split('/')
@namespace = path.second ? path.first : nil

A: None of these solutions consider a constant with multiple parent modules.  For instance:
A::B::C

As of Rails 3.2.x you can simply:
"A::B::C".deconstantize #=> "A::B"

As of Rails 3.1.x you can:
constant_name = "A::B::C"
constant_name.gsub( "::#{constant_name.demodulize}", '' )

This is because #demodulize is the opposite of #deconstantize:
"A::B::C".demodulize #=> "C"

If you really need to do this manually, try this:
constant_name = "A::B::C"
constant_name.split( '::' )[0,constant_name.split( '::' ).length-1]

A: In Rails 6 you can do:
controller.class.module_parent

to get the parent module. Haven't tried it with multiple nestings. But for one you can convert to a symbol like this:
controller.class.module_parent.to_s.underscore.to_sym


text:
Q: Rails: PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint Here is the error when saving a record into postgres database on rails 3.2.12 & pg 9.3:
ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR:  null value in column "id" violates not-null constraint
: INSERT INTO "sw_module_infox_module_infos" ("about_controller", "about_init", "about_log", "about_misc_def", "about_model", "about_onboard_data", "about_subaction", "about_view", "about_workflow", "active", "api_spec", "category_id", "created_at", "last_updated_by_id", "module_desp", "name", "submit_date", "submitted_by_id", "updated_at", "version", "wf_state") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21) RETURNING "id"):
  activerecord (3.2.12) lib/active_record/connection_adapters/postgresql_adapter.rb:1166:in `get_last_result'
  activerecord (3.2.12) lib/active_record/connection_adapters/postgresql_adapter.rb:1166:in `exec_cache'

The table was working fine until now (saved about 50 records before the error today). After opening the pg table in pgadmin. we found the id on the table is integer. We also found Id on other table is serial. It seems that the id should be serial so it can auto-increment. If it is, then how to convert a id column to serial from integer? If it is not, then how to fix this problem?

A: I had an issue like this when working on a Rails 6 application.
I had a User model that is used to create a student and an admin:
class User < ApplicationRecord
  belongs_to :role
end

And a Role model:
class Role < ApplicationRecord
end

However, I wanted the admin and student roles to be assigned for each admin and student respectively when they are created without having a roles field in the forms, so my  models were like this:
The Admin model:
class Admin < ApplicationRecord
  before_save :set_admin_role

  belongs_to :user

  private

  def set_admin_role
    # set role_id to '1' except if role_id is not empty
    user.role_id = '1' if user.role_id.nil?
  end
end

The Student model:
class Student < ApplicationRecord
  before_save :set_student_role

  belongs_to :user

  private

  def set_student_role
    # set role_id to '2' except if role_id is not empty
    user.role_id = '2' if user.role_id.nil?
  end
end

So this was throwing errors whenever I tried creating admins and students:
ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "role_id" violates not-null constraint)

Here's how I solved it:
The issue was that the role_id in the users table was set to null: false in my migration file. I had to change it to null: true:
class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :email
      t.string :password_digest
      t.references :role, null: true, foreign_key: true

      t.timestamps
    end
  end
end

And then also changed the User model, to have the role_id as optional:
class User < ApplicationRecord
  belongs_to :role, optional: true
end

That's all.
I hope this helps

A: I had a very similar problem.
I'll tell what was wrong, maybe someone will find my experience useful

I had ERROR:  null value in column "created_at" violates not-null constraint

and the problem was that I had a methods that ran in before_create and before_save and this methods tried to save with minor updates. So it tried to save few times.

My suggestion is to check what your code is doing in before_save
and before_create

A:
The data types smallserial, serial and bigserial are not true types, but merely a notational convenience for creating unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases).

If your column is an integer, you cannot convert it to serial, but you can mimic, what PostgreSQL would have done, just like you created your table with a serial:
CREATE SEQUENCE tablename_colname_seq;
ALTER TABLE tablename ALTER COLUMN colname SET DEFAULT nextval('tablename_colname_seq'::regclass);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

A: Just add  optional: true to the model which we have to map
example:
user :
class User < ApplicationRecord

  has_many :tasks
end

task:
class Task < ApplicationRecord

  belongs_to :user, optional: true

end

set ----->  null: true , in ur DB/migration/


text:
Q: javascript audio gets lauder each click I was implementing some audio files today in my Javascript and it works fine. But
I noticed that with each subsequent click the sound gets louder. I alreadio used the "Audio.volume" method but no luck.
My Code:
var AppController = (function () {
    var correctItem, secondItem, thirdItem, selectedItems, selectedItemsShuffled;

var rotateImage = function() {
    var i = 0;
    var randomNumbers = createThreeRandomNumbers();

    var interval = window.setInterval(function () {
            i++;
            document.getElementById("imageToRotate").src= "img/" + items.images[i].imageLink;

            if (i === items.images.length -1) {
                i = -1;
            }
    }, 125);

    var clearData = function () {
        correctItem = "";
        secondItem = "";
        thirdItem = "";
        selectedItems = "";
        selectedItemsShuffled = "";
        removeNodeChildren("button-1");
        removeNodeChildren("button-2");
        removeNodeChildren("button-3");
    };

    var removeNodeChildren = function (obj) {
        var myNode = document.getElementById(obj);
        while (myNode.firstChild) {
            myNode.removeChild(myNode.firstChild);
        }
    };

    var resetGame = function () {
        clearData();
        document.getElementById("buttonWrapper").classList.remove("show");
        rotateImage();
    }

    document.getElementById("imageToRotate").addEventListener("click", function (e) {

        // select 3 items
        correctItem       = getSelectedItemDetails(e);
        secondItem = getRandomItem(correctItem);
        thirdItem = getSecondRandomItem(correctItem, secondItem);
        selectedItems = [correctItem, secondItem, thirdItem];
        selectedItemsShuffled = shuffleArray(selectedItems);

        // create the numbers 1 to 3 randomly
        var order = createThreeRandomNumbers();

        // remove the rotating effect
        clearInterval(interval);

        // set the images to the buttons in a random order.
        setItemsToButtons(order, selectedItemsShuffled);

        //show the buttons
        showButtons();

        // Create an event which triggers when a button is clicked.
        document.getElementById("buttonWrapper").addEventListener("click", function(e) {
            var valueOfButtonPressed = e.srcElement.innerText.toLowerCase();
            var clickedButton = e.srcElement.id;

            if (valueOfButtonPressed === correctItem) {
                document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '';

                if (!audio) {
                    var audio = new Audio("audio/correct.mp3");
                }

                audio.play();
                audio.volume = 0.5;

                setTimeout(resetGame, 5000);

            } else {
                document.getElementById(clickedButton).innerHTML = e.srcElement.innerText.toLowerCase() + '';

                if (!audio) {
                    var audio = new Audio("audio/wrong.mp3");
                }

                audio.play();
                audio.volume = 0.5;

                setTimeout(resetGame, 5000);
            }
        });
    });
};

// 1: hide the buttons
hidebuttons();

// 2: Replace the title
replaceTitle("Animals");

// 3: set up image rotation until it's clicked.
rotateImage();
})();

Any help will be much appreciated. Cheers!

A: I'm fairly certain the reason is that you're making a new Audio object with every single click.
Instead of doing this with every click:
var audio = new Audio("audio/correct.mp3");

do a check to see if audio already exists. if it does, then simply do audio.play(). If it does not, THEN you make a new audio object.


text:
Q: How to arrange date/time into AM in/out and PM in/out I am making a payroll system and I bought the B3 tft from zktechnology and would like to arrange the record.
Currently I can pull the data from the biometric with this format:

Count   EmpID   InOutMode   Date
1       1       0           8/20/2012 07:49:01
2       1       1           8/20/2012 12:08:21
3       1       0           8/20/2012 12:43:10
4       1       1           8/20/2012 17:56:15
5       2       0           8/20/2012 07:53:11
6       2       1           8/20/2012 12:02:01
7       2       0           8/20/2012 12:39:56
8       2       1           8/20/2012 17:20:43
9       1       0           8/21/2012 08:10:20
10      1       1           8/21/2012 12:01:26
11      1       0           8/21/2012 13:03:11
12      1       1           8/21/2012 17:11:15
13      2       0           8/21/2012 07:48:26
14      2       1           8/21/2012 12:14:58
15      2       0           8/21/2012 12:59:31
16      2       1           8/21/2012 17:20:12

InOutMode:
0 = In, 1 = Out
Now, I want to convert the data above like this:

EmpID   Date        AM_In       AM_Out      PM_In       PM_Out
1       8/20/2012   07:49:01    12:08:21    12:43:10    17:56:15
2       8/20/2012   07:53:11    12:02:01    12:39:56    17:20:43
1       8/21/2012   08:10:20    12:01:26    13:03:11    17:11:15
2       8/21/2012   07:48:26    12:14:58    12:59:31    17:20:12

So I can save it to the database with EmpID, Date, AM_In, AM_Out, PM_In, PM_Out fields.
I saw a similar code here before but I can't remember the URL.
Update:
VB.net code or sql in ms access format is acceptable.

A: It might be easiest to create two cross tabs and a query to join them to the available dates and employees.
1 AM Crosstab
TRANSFORM Min(tm.Date) AS MinOfDate
SELECT Format([Date],"dd/mm/yyyy") AS dt, tm.EmpID
FROM tm
GROUP BY Format([Date],"dd/mm/yyyy"), tm.EmpID
PIVOT tm.InOutMode;

2 PM Crosstab
TRANSFORM Max(tm.Date) AS MinOfDate
SELECT Format([Date],"dd/mm/yyyy") AS dt, tm.EmpID
FROM tm
GROUP BY Format([Date],"dd/mm/yyyy"), tm.EmpID
PIVOT tm.InOutMode;

Where tm is the name of your table.
You can then join these up.
SELECT Alldates.dt,
       Alldates.empid,
       am.[0] AS [Am In],
       am.[1] AS [Am Out],
       pm.[0] AS [Pm In],
       pm.[1] AS [Pm Out]
FROM   ((SELECT DISTINCT Format([date], "dd/mm/yyyy") AS dt,
                        empid
        FROM   tm) AS Alldates
        LEFT JOIN am
               ON ( Alldates.empid = am.empid )
                  AND ( Alldates.dt = am.dt ))
       LEFT JOIN pm
              ON ( Alldates.empid = pm.empid )
                 AND ( Alldates.dt = pm.dt );

A: Here is a query that should produce the results that you want in MS Access:
select am_in.empid,
    format(am_in.min_in_dt, "MM/DD/YYYY") as [date],
    format(am_in.min_in_dt, "hh:mm:ss") as AM_In,
    format(am_out.min_out_dt, "hh:mm:ss") as AM_Out,
    format(pm_in.max_in_dt, "hh:mm:ss") as PM_In,
    format(pm_out.max_out_dt, "hh:mm:ss") as PM_Out
from
(
    (
        (
           SELECT empid,
              min(dt) as min_in_dt
            FROM yourTable
            where inoutmode = 0
            group by empid
        ) am_in
        inner join
        (
           SELECT empid,
              min(dt) as min_out_dt
            FROM yourTable
            where inoutmode = 1
            group by empid
        ) am_out
            on am_in.empid = am_out.empid
    )
    inner join
    (
       SELECT empid,
          max(dt) as max_in_dt
        FROM yourTable
        where inoutmode = 0
        group by empid
    ) pm_in
        on am_in.empid = pm_in.empid
)
inner join
(
   SELECT empid,
      max(dt) as max_out_dt
    FROM yourTable
    where inoutmode = 1
    group by empid
) pm_out
    on am_in.empid = pm_out.empid

A: Something like this will work
select
    empid,
    dateadd(day,datediff(day,0,DATE),0) as date,
    max(case when sno=1 then convert(varchar(8),DATE,108)) as AM_IN,
    max(case when sno=2 then convert(varchar(8),DATE,108)) as AM_OUT,
    max(case when sno=3 then convert(varchar(8),DATE,108)) as PM_IN,
    max(case when sno=4 then convert(varchar(8),DATE,108)) as PM_OUT
from
(
    select *,
        row_number() over (partition by empid order by Empid) as sno
    from
        table
) as t
group by
    empid,dateadd(day,datediff(day,0,DATE),0)


text:
Q: Unable to copy Lotus Notes text field's content to clipboard sometimes i'm unable to copy and paste the text content in a field of a form.
i try to do this:
FIELD ~$KeepPrivate:=~$KeepPrivate;
@SetField("$KeepPrivate";@Unavailable);
SELECT @All

but the situation is the same and i'm not able to copy and paste....
Someone can help me ?
thank's

A: Maybe property "Disable printing/forwarding/copying to clipboard" is set in form properties

It shouldn't be set to enable copying text to clipboard.
Another reason for not being able to copy field's text could be field property "Hide paragraph when document is Copied to the clipboard" although it has effect in read mode only.
.
Other possible reasons are described here. In case your document has a field "$KeepPrivate" then execute this formula on document:
FIELD $KeepPrivate := @DeleteField

A: To resolve this just go to Preferences / Basic Notes Client Configuration and on Additional options box enable (Enable alternate keyboard shortcuts (for example, CTRL+R=Reply)

A: Here I would like to know if you are using CTRL+C or CTRL+Insert.
Please try using CTRL+Insert once and see if you can achieve copying it to your clipboard.


text:
Q: Count time browser render content How can I count time browser render (re-render) my aspx page after page load?
(I have a lot of components on the page,so I need to compare perfomance of different approachs)

A: Use a browser extension such as FireBug for Firefox.
Using the Net panel, you can see a 'timeline' like a Gantt chart of how long each element takes to load, render etc.


text:
Q: bash for loop, strings with spaces cat file.txt
ob_No  ob_kind  ob_value  ob_lat   ob_lon   ob_depth  ob_time
1      S        36.045    44.1432  12.5701  1.6       201303210000
2      S        37.148    44.1432  12.5701  8.5       201303210000
3      S        36.069    44.1432  12.5701  1.6       201303210029
4      S        37.117    44.1432  12.5701  8.5       201303210029
5      S        36.105    44.1432  12.5701  1.6       201303210100
6      S        37.136    44.1432  12.5701  8.5       201303210100
7      S        36.143    44.1432  12.5701  1.6       201303210130
8      S        37.081    44.1432  12.5701  8.5       201303210130
9      S        36.162    44.1432  12.5701  1.6       201303210159

mapfile -s 1 -t ArrayObs < file.txt
I get the array of lines 1 to 9.
for  oline in ${ArrayObs[@]};do
  varDP=`echo ${oline} | awk '{print $6}'`
     if [ "${ArrayObs[0]}" == "$oline" ]; then
      valuesMO=`echo ${oline}`
      echo -e " first time"
      awk '{printf ("%.3f\n", $6)}' valuesMO > MkDepth
    else
      echo -e " not the first time"
      valuesMO=`echo ${oline}`
      awk '{printf ("%.3f\n", $6)}' valuesMO >> MkDepth
    fi
  done

I want to concatenate when its first iteration and append for the rest. the if loop gives fatal error (awk) because there are spaces in the strings.
Thanks,

A: I will provide a script that reads file line by line; each line is an array and will iterate over value by value over an array. Hope it helps.

file.txt
ob_No  ob_kind  ob_value  ob_lat   ob_lon   ob_depth  ob_time
1      S        36.045    44.1432  12.5701  1.6       201303210000

Script
#!/usr/bin/env bash
# author    : Daniel Leybovich
# SO        : http://stackoverflow.com/questions/27981928/bash-for-loop-strings-with-spaces

FILE=${1}

while read LINE
do
    declare -a ROW

    ROW=($(echo ${LINE}))
    COLS=${#ROW[@]}

    echo "LINE    : .... ${LINE}"
    echo "COLS NUM: .... ${COLS}"
    echo "----------------------"
    echo "value by value:       "

    for INDEX in $(seq 0 $((COLS - 1)))
    do
        echo -e "\tCOL[${INDEX}] = ${ROW[${INDEX}]}"
    done

    echo '========================================='

done < ${FILE}

exit 0

Output
daniel@synapse:/tmp$ ./so27981928.sh file.txt
LINE    : .... ob_No  ob_kind  ob_value  ob_lat   ob_lon   ob_depth  ob_time
COLS NUM: .... 7
----------------------
value by value:
    COL[0] = ob_No
    COL[1] = ob_kind
    COL[2] = ob_value
    COL[3] = ob_lat
    COL[4] = ob_lon
    COL[5] = ob_depth
    COL[6] = ob_time
=========================================
LINE    : .... 1      S        36.045    44.1432  12.5701  1.6       201303210000
COLS NUM: .... 7
----------------------
value by value:
    COL[0] = 1
    COL[1] = S
    COL[2] = 36.045
    COL[3] = 44.1432
    COL[4] = 12.5701
    COL[5] = 1.6
    COL[6] = 201303210000
=========================================

EDIT [minor script improvements]
#!/usr/bin/env bash
# author        : Daniel Leybovich

# create a temporary file
TABLE=$(mktemp)

# populate file with tabular data
cat << EOF >> ${TABLE}
col1    col2    col3    col4
[0,0]   [0,1]   [0,2]   [0,3]
[1,0]   [1,1]   [1,2]   [1,3]
EOF

# count line numbers
declare -i LN=0

# iterate over matrix rows
while read LINE; do
    echo "-------------------------------------------------------------------"

    declare -a ROW

    ROW=(${LINE})
    COLS=${#ROW[@]}

    echo "LINE NO# ....... ${LN}"
    echo "COLUMNS  ....... ${LINE}"
    echo "COLUMNS NUM .... ${COLS}"

    # iterate over values
    for INDEX in $(seq 0 $((COLS - 1)));do
        echo -e "\tCOL[${INDEX}] = ${ROW[${INDEX}]}"
    done

    # increment line counter
    let LN=$((LN + 1))

done < ${TABLE}

# clean up
rm -rf ${TABLE}

# we are done
exit 0

OUTPUT
daniel@synapse:/tmp$ ./arrays_2d.sh
-------------------------------------------------------------------
LINE NO# ....... 0
COLUMNS  ....... col1    col2    col3    col4
COLUMNS NUM .... 4
    COL[0] = col1
    COL[1] = col2
    COL[2] = col3
    COL[3] = col4
-------------------------------------------------------------------
LINE NO# ....... 1
COLUMNS  ....... [0,0]   [0,1]   [0,2]   [0,3]
COLUMNS NUM .... 4
    COL[0] = [0,0]
    COL[1] = [0,1]
    COL[2] = [0,2]
    COL[3] = [0,3]
-------------------------------------------------------------------
LINE NO# ....... 2
COLUMNS  ....... [1,0]   [1,1]   [1,2]   [1,3]
COLUMNS NUM .... 4
    COL[0] = [1,0]
    COL[1] = [1,1]
    COL[2] = [1,2]
    COL[3] = [1,3]

A: I don't see a question in there at all.
Some code review:
for  oline in ${ArrayObs[@]};do

quotes missing: need "${ArrayObs[@]}"
  valuesMO=`echo ${oline}`

Same as valuesMO=$oline except the whitespace is squeezed. Is that your intention?
  varDP=`echo ${oline} | awk '{print $6}'`
     if [ "${ArrayObs[0]}" == "$oline" ]; then
      echo -e " first time"
      awk '{printf ("%.3f\n", $6)}' valuesMO > MkDepth

Do you have a file named valuesMO? You're missing a $
    else
      echo -e " not the first time"
      awk '{printf ("%.3f\n", $6)}' valuesMO >> MkDepth
    fi
  done

You don't need the if statement. Put the redirect after the for loop to capture all its output. Like this:
for x in ...; do
    echo $x
done > MkDepth


text:
Q: Puzzled about the display of two up/down votes tallies at the same time What do two up/downvote numbers mean?
Edit: Thank you very much R. Martinho Fernandes for your gracious and simple answer.
I don't know whether other answerer's number of 1000 is correct. I've only just reached 2000 three days ago.
I don't know what "Established users are those who have been participating on the site for a fair amount of time"# really means. But I guess it includes me. Edit: Looking at R's reference https://meta.stackoverflow.com/privileges/established-user, it seems to need 8000, which definitely ***ex***cludes me.)
But why does this simple newbie question from me get -8 votes, while the leading answerer gets +15?

*

*(Maybe I should stay out of the kitchen?)

*(Or perhaps I`m putting up my hand and asking Teach! Teach!?)

*(Or should I RTFM?)

A: The ability to see how votes are split on a post is granted when you hit 1000 reputation on a site.  The top number is upvotes.  The bottom number is downvotes. Hover your mouse over the split votes and it explains (0 up / 3 down).

A: Those numbers are the number of upvotes, in green, and the number of downvotes, in red. You can get that view if you click on the post score. You can read the fine manual in the list of privileges for established users.

Voting scores, as displayed, are the sum of the up and down votes on a post. Vote counts are the individual up and down votes that make up the score.
You can view the vote counts by clicking on the score of a post. This will break the score into upvotes and downvotes, like so:

The upvotes have a plus sign next to them and are displayed as the top number, in green. The downvotes have a negative sign next to them and are displayed as the bottom number, in red.


text:
Q: How to allow dynamically created file to be downloaded in CherryPy? I'm trying to use CherryPy for a simple website, having never done Python web programming before.
I'm stuck trying to allow the download of a file that is dynamically created. I can create a file and return it from the handler, or call serve_fileobj() on the file, but in either case the contents of the file are simply rendered to the screen, rather than downloaded.
Does CherryPy offer any useful methods here? How can this be accomplished?

A: If you set the correct content type, you won't have to worry about it rendering in the browser when you return it unless it's appropriate.  Try:
response.headers['Content-Type'] = 'application/foo'

(or whatever the correct MIME type for your content is) before you return the content.

A: Add 'Content-Disposition: attachment; filename="<file>"' header to response

A: Putting the previous answers from @varela and @JasonFruit together:
dynamic_content = "this was generated on the fly!"
cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="<file>"'
return dynamic_content


text:
Q: MySql_workbench_import_, button While importing data, the import start button is missing.
I saw that - someone written resolution should be minimal.
How can we do resolution on MySQL workbench?
Need- solution for resolution of MySQL workbench


text:
Q: Determine the cluster for a new document with Scikit I have implemented the k-means algorithm in scikit. Therefore, I have clustered the historical documents. Now, for a new document I want to determine the cluster.
How can I determine the cluster for the new document?

A: Assuming you built your classifier using:
km = KMeans()
km.fit(X)

If you have X_new_sample with the same vector format as X, you can use predict() to identify which cluster each row in X_new_sample belongs to.
km.predict(X_new_sample)


text:
Q: How do I loop through a numeric function parameter? I'm having a lot of trouble figuring this one out. I have a function which passes value as a parameter, and I need a way to store each single digit that I'm passing in when I'm calling the function. I'm assuming I need to use a for loop and I can assign each digit to [i] but the logic isn't coming to me.
function assignValue(value) {
  for (let i = 0; i < value.length; i++) {
    // I'M LOST
  }
}
assignValue(123);

A: There are no "digits" in a value of type number, for the concept of "digits" you have to convert to string in the numbering system you want (for instance, base 10).¹ Once you've converted to string, you can loop through it with code like the code in your question, or more easily with a for-of loop:

function assignValue(value) {
    // Convert to string
    const str = String(value);
    // Loop through the string
    for (const char of str) {
        console.log(char);
    }
}
assignValue(123);

¹ It is possible to do this mathematically, by figuring out what the highest multiple of 10 you need is (100 in your case), and then working through by Math.floor(value / multiple), then doing value %= multiple and multiple /= 10, and continuing that while multiple >= 1:

function assignValue(value) {
    let multiple = 1;
    // Figure out where we need to start -- I'm sure there's a
    // clever mathematics way to do this rather than this brute
    // force approach
    while (multiple < value) {
        multiple *= 10;
    }
    // That took us too far, so:
    multiple /= 10;

    // Loop through
    while (multiple >= 1) {
        console.log(Math.floor(value / multiple));
        value %= multiple;
        multiple /= 10;
    }
}
assignValue(123);

But using a string is probably easier.

A: Another way to go about it, that's without using the for loop is to turn the number into an array of the digits

function assignValue(value) {
  return Array.from(String(value), Number);
}
console.log(assignValue(123))


text:
Q: How to make an array formula with two variables I have a problem with my array formula which contains two variables. I want to make a ArrayFormula to count filled cells in columns in my table generated in the new sheet. The table has number of columns depending of nos value. Cloumns are named "Tabela_" & name & "[Substancja1] etc. I want to sum all of filled cells in those columns. I think I have to fix something in syntax, either of formula or code. I made another array formula in Range("C5") and it works. I tried with quotation marks ("") between string and variables but it didn't work. Please, help me.
This code generate an error 1004: impossible to set the FormulaArray in Range class.
Sheet for example:
https://1drv.ms/x/s!AitFOK70PUC7wx_7vnh5EqkdJLfe
Sub newSheet()

    Dim name As String
    Dim nos As Integer
    Dim formRozp As String

name = InputBox("blabla:", "Add item")
nos = InputBox("blabla" & vbCrLf & vbCrLf & "Range: 1-10.", "Add item")

Range("C5").FormulaArray = "=SUM(IF(Tabela_" & nazwa & "[Data]="""",0,1))"

formRozp = "=SUM(IF(Tabela_" & name & "[Substancja1]="""";0;1))"

For nos = 2 To nos - 1
    formRozp = formRozp & "+SUM(IF(Tabela_" & name & "[Substancja" &
    nos & "]="""";0;1))"
Next nos

Range("C3").FormulaArray = formRozp

The code generate the formula for name=b5 and nos=3 but it isn't working.
=SUM(IF(Tabela_b5[Substancja1]="";0;1))+SUM(IF(Tabela_b5[Substancja2]="";0;1))+SUM(IF(Tabela_b5[Substancja3]="";0;1))

A: Hard for me to test with English version, but there might be a translation problem.
You might try, with your version of code, first writing it in your language, and then using something like:
.FormulaLocal = "my_formula"
.FormulaArray = .Formula

However, I think a simpler formula to count the filled cells would be something like:
=SUM(COUNTA(Tabela_b6[Substancja1],Tabela_b6[Substancja2],Tabela_b6[Substancja3]))

It is a non-array formula.

A: Try like this:
' If column's name is  "Tabela_" & name & "[Substancja1]"
Range("C5").FormulaArray = "=SUM(IF([@[Tabela_" & name & "Substancja1]]="""",0,1))"

' If column's name is Data and table name is Tabela_" & name
Range("C5").FormulaArray = "=SUM(IF(Tabela_" & name & "[@[Data]]="""",0,1))"

A: Thanks Ron for your concept. I changed the functions and it works for me:
The final formula: =SUM(CountA(Tabela_b11[Substancja1],Tabela_b11[Substancja2],Tabela_b11[Substancja3],Tabela_b11[Substancja4]))
the code:
formRozp = "=SUM(CountA(Tabela_" & nazwa & "[Substancja1]))"
For nos = 2 To nos - 1
    formRozp = Replace(formRozp, "))", ",Tabela_" & name & "[Substancja" & nos & "]))")
Next nos

Range("C3").formula = formRozp

I use the polish version so maybe that could be a problem. But now it works so I am happy. Thanks a lot!


text:
Q: David Hilbert's Foundations of Geometry, section 9, Compatibility of the Axioms I am reading David Hilbert's Foundations of Geometry.  In section 9, where he shows the "Compatibility of the Axioms" he begins with the following:
Let us consider the domain $\Omega$ consisting of all those algebraic numbers which may be obtained by beginning with the number one and applying to it a finite number of times the four arithmetical operations (addition, subtraction, multiplication, and division) and the operation $\sqrt{1+\omega^2}$, where $\omega$ represents a number arising from
the five operations already given.
Let us regard  a pair of numbers $(x, y)$ of the domain $\Omega$ as defining a point and the
ratio of three such numbers  $(a : b : c) \in\Omega$, where $a, b$ are not both equal to zero, as
defining a straight line. Furthermore, let the existence of the equation  $ax + by +c = 0$ express the condition that the point $(x, y)$ lies on the straight line $(a : b : c)$.
My question is, what is a ratio of three numbers?  Is it just a way to express the values that define a line?  I have tried to look up a ratio for more that two numbers and found a mix of odd answers.  Is he just using an older definition of the word "ratio"?

A: By "ratio" he means an equivalence class of triples $(a,b,c)$ (with $a,b,c$ not all $0$) where two triples $(a,b,c)$ and $(a',b',c')$ are considered equivalent if there exists a nonzero number $\lambda$ such that $a'=\lambda a$, $b'=\lambda b$, and $c'=\lambda c$.  This is just a formalization of the informal notion of a three-way ratio that is commonly used in everyday life, e.g. as described here.   The point here is if you are describing a line with an equation $ax+by+c=0$ then the line does not actually uniquely determine the triple $(a,b,c)$, since scaling them by a nonzero constant gives an equivalent equation.


text:
Q: Create a path in mapping software and export as vector? Is it possible to map a route in any mapping software (OpenStreetMaps, Google Maps/Earth, QGIS, etc. preferably Open Source or free) and export this route as a vector (PDF, AI, SVG etc.)?
I'm only interested in the route taken (as a line), without any other information.


text:
Q: $Amp(z)+Amp(w)=\pi.\;$ Find a relation between $\;z\;$ and $\;w.$ The question says:

Let $\;z\;$ and $\;w\;$ be two non-zero complex numbers such that $|z|=|w|$ and $amp(z)+amp(w)=\pi,\;$ then find a relation between $\;z\;$ and $\;w.$

In the solution they turn $ amp(z)+amp(w)$ into $amp(Z)-amp(\overline w)\;$ and equate it to $\pi$. What was the need to do so ? I think I may be missing some concept.
The final answer is $\;z+ \overline w=0.$

A: $$w=|w|e^{i\angle w}=|z|e^{i\pi-i\angle z}=e^{i\pi}|z|e^{-i\angle z}=-\overline z.$$


text:
Q: How can I write the whole word of the variable, in Python? I want to be able to print the whole variable, or just detect it. If I run it through a for loop as I've done in the code below, it just prints the individual letters. How can it print the whole word?
Question = input()
Answer = input()

def test():
    for words in Answer:
        print(words)

test()

A: Since answer is a string, and a string is an enumerable type, it enumerates over the characters. If you want to print a plain string just do print(Answer).

A: This would work perfectly
Question = input()
Answer = input()

def test():
    for words in Answer.split(' '):
        print(words)

test()

A: When you are iterating a string in python what it does, it makes an iterable out of a string and then it print's each letter in a given word. This is for both single word and multiple words, so either you can just print(Answer) or you can first split it by e.g. space and then print each word in a sentence like this:
answer = Answer.split()  # splits by space, you can provide any separator and this will generate a list for you
for word in answer:
    print(word)

This will print each word even if it's only 1.

A: This is a poorly phrased question and poorly researched question which can get you banned from asking questions in Stack overflow so keep that in mind when you post another question.
You can do
for word in Answer.split(" "):
    print(word)

If that's not what you are looking for you can try-
print(Answer)


text:
Q: Statement executed despite exception preceeding it I have this very simple code snippet which runs as expected if no exception is thrown:
try {
  session = HibernateHelper.getSessionFactory().openSession();
  session.beginTransaction();
  OracleTables.writeToLogTable(thisLogRecord); // <<<< this throws a java.sql.SQLException!

  boolean isSuccess = OracleTables.writeToActualDataTable(thisDataRecord);
  if (isSuccess) {
    System.out.println("writeToActualDataTable() successful.");
  }
}
catch (RuntimeException e) {
  if (e != null && e.getMessage() != null && e.getMessage().contains("No data to write")) {
    System.out.println("No more data to write.");
    System.exit(0);
  }
  else
    throw e;
}

But if there is some constraint violation in the first database write (e.g. attempt to insert a NULL into a field that doesn't allow it), a java.sql.SQLException is thrown (which is fine) but for some strange reason, the OracleTables.writeToActualDataTable() statement is being executed!
org.hibernate.exception.ConstraintViolationException: could not execute statement
        at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
        at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
        at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
        at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3067)
        at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3509)
        at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
        at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369)
        at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:286)
        at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339)
        at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
        at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
        at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
        at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
        at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
        at com.nicecor.test.myclient.OracleTables.writeToLogTable(OracleTables.java:159)
        at com.nicecor.test.myws.ServicePort_ServiceSoapPort_Client.main(ServicePort_ServiceSoapPort_Client.java:180)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at com.simontuffs.onejar.Boot.run(Boot.java:340)
        at com.simontuffs.onejar.Boot.main(Boot.java:166)
Caused by: java.sql.SQLException: ORA-01400: cannot insert NULL into ("USR"."LOG_TABLE"."CREATE_TMSTMP")

This is strange. I thought an exception in Java would abort execution and go immediately to the catch clause.
What could explain this weird behavior?
What am I missing?

A: OracleTables.writeToLogTable() is catching the exception and printing to System.err the contents while continuing execution.


text:
Q: Not Able To MultiProcess Python Flask Server Hi Everyone I was trying creating a multiprocessed flask server with waitress but evertime i execute it i run into issues and no able to identify them the same gets executed if i try multithreading
I am using multiprocessing because i want to have conplete control of the flask server (running/terminating)
APICommunications.py
import ProcessBuilder as pb
import ServiceLogger as sl
import SystemRecovery as sr
from flask import Flask, Response
from waitress import serve
from flask_cors import CORS

class EndpointAction(object):

    def __init__(self, action):
        self.action = action
        self.logger = sl.ServiceLogger()
        self.response = Response(status=200, headers={})

    def __call__(self, *args):
        self.action()
        return self.response

class APIServer:

    def __init__(self):
        self.server = None
        self.debug = sr.Recovery().debug
        self.port = sr.Recovery().api_port
        self.host = '127.0.0.1'
        self.logger = sl.ServiceLogger()
        self.app = Flask(__name__)
        CORS(self.app, resources={r"/api/*": {"origins": "*"}})
        self.register_endpoints()
        self.server = pb.ProcessBuilder().create_process(self.run, [self])

    def add_endpoint(self, endpoint=None, endpoint_name=None, handler=None):
        self.app.add_url_rule(endpoint, endpoint_name, EndpointAction(handler))

    def register_endpoints(self):
        return None

    def start(self):
        self.server.start()

    def run(self):
        serve(self.app, port=self.port, host=self.host)

    def terminate(self):
        self.server.kill()
        return None

a = APIServer()
a.start()
print("heyy")
a.terminate()
print("thread killed")

ProcessBuilder.py
import multiprocessing
import random
import string

import ServiceLogger as sl

class ProcessBuilder:

    def __init__(self):
        self.processes = []
        self.logger = sl.ServiceLogger()

    def create_process(self, method, args=[]):
        process = multiprocessing.Process(name=self.__generate_instance_name(), target=method, args=tuple(args))
        self.processes.append(process)
        return process

    def get_process_instance(self, process_name):
        for process in self.processes:
            if str(process.name) == process_name:
                return process
        return None

    def run_process(self, process):
        process.start()

    def kill_process(self, process):
        process.kill()

    def __generate_instance_name(self):
        # printing lowercase
        letters = string.ascii_lowercase
        randomString = ''.join(random.choice(letters) for i in range(3))

        # printing letters
        letters = string.digits
        randomDigits = ''.join(random.choice(letters) for i in range(5))

        return randomString + "" + randomDigits

Output:
C:\Python\python.exe D:\Projects\APICommunications.py
Service Logger Started...........
Service Logger Started...........
Traceback (most recent call last):
  File "D:\Projects\Red\APICommunications.py", line 52, in <module>
    a.start()
  File "D:\Projects\Red\APICommunications.py", line 41, in start
    self.server.start()
  File "C:\Python\Lib\multiprocessing\process.py", line 121, in start
    self._popen = self._Popen(self)
                  ^^^^^^^^^^^^^^^^^
  File "C:\Python\Lib\multiprocessing\context.py", line 224, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\Lib\multiprocessing\context.py", line 336, in _Popen
    return Popen(process_obj)
           ^^^^^^^^^^^^^^^^^^
  File "C:\Python\Lib\multiprocessing\popen_spawn_win32.py", line 94, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Python\Lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'Flask.__init__.<locals>.<lambda>'

A: This is not how you do it. :-)
If you want to have multiple processes answering HTTP requests on a given port, even if we work out the details so that any data there is pickable and you can actually start waitress in different processes, you'd run into the obvious wall of having more than one process trying to listen to the same port on the same computer - all but the first process would terminate with "address already in use" error by the O.S. itself.
Instead, keep in mind that waitress is not designed for production app serving and should be used only as the development http/wsgi server.  Recent versions even have some support for parallel requests, but that is in multi-threading mode - and even if it supported multiprocessing configurations, that should be done from within waitress, not externally to it.
Instead, you should check the documentation on how to serve your project with a production grade WSGI server, like gunicorn or uWSGI are good examples, and both are extensively configurable, allowing one to setup how many worker processes and within each process, how many working threads should answer requests. All parallelisation and multi-processing support is not trivial, and is built deep into these projects.


text:
Q: Proof by mathematical induction: stuck on algebra Use mathematical induction to prove the following:
For all $i$ starting from $1$ up to $N$, $i^3 =\frac{N^2(N + 1)^2}{4}$
Base Case:
$1 ^ 3 = 1^2(1 + 1)^2 / 4$
Conditions holds, so move onto general case.
Assume true for $N = k$
$1 ^ 3 + 2 ^ 3 + 3 ^ 3 + ... + (k)^3 = k^2(k+1)^2 / 4$
Prove for $k + 1$
$k^2(k+1)^2 / 4 + (k + 1)^3 = k + 1 ^2(k+2)^2/4$
LHS:
$= k^2(k+1)^2 + (k+1)^3(4)/4$
$= k^4 + 2k^3 + k^2 + (k+1)^3(4) / 4$
$= k^4 + 2k^3 + k^2 + 4k^3 + 12k^2 + 12k + 4 / 4$
$= k^4 + 6k^3 + 13k^2 + 12k + 4 / 4$
So I get to this point, but I don't know how to proceed. I'm confident that what I've done so far is completely wrong.

A: We need to prove that $$\frac{k^2(k+1)^2}{4}+(k+1)^3=\frac{(k+1)^2(k+2)^2}{4}$$ or
$$\frac{k^2}{4}+k+1=\frac{(k+2)^2}{4},$$
which is obvious.

A: If you can't figure out how to proceed from left hand side to right hand side via factorization.
Do consider working from right hand side as well.
Expand
\begin{align}
(k+1)^2(k+2)^2&=(k^2+2k+1)(k^2+4k+4) \\
&=k^4+6k^3+13k^2+12k+4
\end{align}


text:
Q: Visual Studio 2013 Update 5 Takes forever to install/uninstall I am installing Visual Studio 2013 Update 5 on windows 7. It got stuck for hours at a step. (I forgot at which step.) I then restarted and continued to install again. It got successfully installed but visual studio was giving weird errors while building the projects. So I ran repair on the installation. It got stuck again while applying "Windows Phone 8.1 SDK". There was no progress even when I left it to run overnight.
Now I am trying to uninstall update 5. But it has again stuck while applying "Windows Phone 8.1 SDK".
Any thoughts? Thanks.

A: Though I had fast internet, it was taking so long. I stopped the installation and tried again. It completed after few hours.

A: Had the same problem. After blocking the antivir activity, the speed of uninstalling raised many times. It is still slow, yes, but I see as the progress bar moves. The whole uninstall takes about 40 min.
Another feature I used is not uninstalling from Control Panel, but from command line, with /force key
cd c:\
dir /s vs_community.exe

Thus you find all folders containing vs_community.exe. Choose one from c:\ProgramData. cd to it. Launch
vs_community.exe /force /uninstall

It helps to overcome some possible blocking situations.
If the uninstalling process demands some additional files and their address by a popup message, download them and provide the downloads folder to the uninstall wizard. Sometimes it won't help, but then you can simply ignore it by cancelling the message. After uninstalling you can find these problem pieces of SW by name in the Control Panel and uninstall them separately.
This method helps even if you have several different installations of Visual Studio, with some of them broken.


text:
Q: How to get count of words from DataFrame based on conditions I have the following two dataframes badges and comments. I have created a list of 'gold users' from badges dataframe whose Class=1.
Here Name means the 'Name of Badge' and Class means the level of Badge (1=Gold, 2=Silver, 3=Bronze).
I have already done the text preprocessing on comments['Text']and now want to find the count of top 10 words for gold users from comments['Text'].
I tried the given code but am getting error
"KeyError: "None of [Index(['1532', '290', '1946', '1459', '6094', '766', '10446', '3106', '1',\n       '1587',\n       ...\n       '35760', '45979', '113061', '35306', '104330', '40739', '4181', '58888',\n       '2833', '58158'],\n      dtype='object', length=1708)] are in the [index]". Please provide me a way to fix this.
Note
I had some answers from datascience.stackexchange but they did not work. Link to StackExchange Problem
Dataframe 1 (badges)
   Id | UserId |  Name          |        Date              |Class | TagBased
   2  | 23     | Autobiographer | 2016-01-12T18:44:49.267  |   3  | False
   3  | 22     | Autobiographer | 2016-01-12T18:44:49.267  |   3  | False
   4  | 21     | Autobiographer | 2016-01-12T18:44:49.267  |   3  | False
   5  | 20     | Autobiographer | 2016-01-12T18:44:49.267  |   3  | False
   6  | 19     | Autobiographer | 2016-01-12T18:44:49.267  |   3  | False

Dataframe 2 (comments)
   Id|                    Text                             |    UserId
    6|  [2006, course, allen, knutsons, 2001, course, ...  |    3
    8|  [also, theo, johnsonfreyd, note, mark, haimans...  |    1

Code
#Classifying Users
df_gold_users = badges[(badges['Class'] == '1')]
df_silver_users = badges[(badges['Class'] != '1') & (badges['Class'] == '2') ]
df_bronze_users = badges[(badges['Class'] != '1') & (badges['Class'] != '2') & (badges['Class'] == '3')]

gold_users = df_gold_users['UserId'].value_counts().index
silver_users = df_silver_users['UserId'].value_counts().index
bronze_users = df_bronze_users['UserId'].value_counts().index

#Text Cleaning (clean_text function tokenizes and lemmatizes)
comments['Text'] = comments['Text'].apply(lambda x: clean_text(x))

#Getting comments made by Gold Users
for index,rows in comments.iterrows():
  gold_comments = rows[comments.Text.loc[gold_users]]
  Counter(gold_comments)

Expected Output
#Top 10 Words that appear the most in the comments made by gold users with their count.
 [['scholar',20],['school',18],['bus',15],['class',14],['teacher',14],['bell',13],['time',12],['books',11],['bag',9],'student',7]]

A: import itertools

df_gold_users = badges[(badges['Class'] == '1')]
df=pd.merge(df_gold_users,comments,on='UserId')
gold_text=list(itertools.chain.from_iterable(df['Text'].to_list()))
gold_text=list(map(lambda x:[x,1],gold_text))
gold_text_df=pd.DataFrame(gold_text,columns=['Text','xyz'])
gold_text_df=gold_text_df.groupby('Text')['xyz'].count().reset_index().sort_values(by=['xyz'], ascending=False)
gold_text_df(10).values.tolist()


text:
Q: How can I setup fiddlercore catch http request/response that without AfterSessionComplete? I want to catch a third-party made application's http/https messages with fiddlercore in C#.
I'm not sure what kind of the connection type is but what I did is
        FiddlerApplication.OnReadRequestBuffer += FiddlerApplication_OnReadRequestBuffer;
        FiddlerApplication.OnReadResponseBuffer += FiddlerApplication_OnReadResponseBuffer;
        FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
        FiddlerApplication.Startup(8888, false, true);

Then I start the application and setup proxy to fiddler's.
The AfterSessionComplete is called only once. The response code is 200 but responseBody is empty.
However, after that I keep receiving OnReadRequestBuffer and OnReadResponseBuffer. The application does keep connecting with the internet(through fiddler proxy)
In my other project I found any messages goes in and out through fiddler should contain one BeforeRequest, then some OnReadRequestBuffer, then following some OnReadResponseBuffer and finally one AfterSessionComplete.
In my mind this is the model of any single post/get process.
But here what I encountered here is that the session won't complete and request -> response -> another requests -> another response...
So how can I catch every full request and the full response to it?
Is there any callback that gives the sign of a full request or a full response is done?
How can I decrypt https base on the partial buffers that runs in and out that caught by OnReadRequestBuffer/OnReadResponseBuffer?
Edit: OnWebSocketMessage is never triggered. Someone says that this kind of protocol could be COMET. But I find nothing about how to catch COMET messages with fiddler. (And I know nothing about COMET)


text:
Q: no corre tensorflow por si alguién a tenido este problema y lo pudo solucionar.
cargue anaconda y cree dos ambientes, el base(root) y tensorflow, active tensorflow y keras, sin embargo al usar jupyter resuelve solo con el ambiente base(root) y no usa para la parte de redes neuronales el segundo ambiente, tensorflow-keras, indicando que no están cargados tensorflow y keras, estandolos en este segundo ambientes.
Que puedo hacer para resolver que vaya al segundo ambientes "tensorflow" jupyter?
gracias, Emilio

A: Cuando estás en Jupyter, puedes acceder a kernel y cambiar el kernel (change kernel) al que tú desees. Aquí te dejo una foto, para que lo veas.

A: muchas gracias por la sugerencia. Finalmente lo resolví de la siguiente forma: cree un ambiente en anaconda y en cargué todas las librerías que requiero usar incluido el tensorflow y keras.
Gracias nuevamente por contestar, si alguien tiene esta dificultad me puede preguntar los detalles.


text:
Q: Multiple Big Query tables or singular for similar data I'm looking into moving my analytics system across to BigQuery and I was wondering if someone could give me some pointers on the best way to structure my data.
I am logging analytics events that happen on a website. Each analytics event type must be stored in a separate table as they don't have similar fields.
I will be using partitions to separate by day, and running a query at midnight everyday on that days data to generate total counts which can then be stored elsewhere for faster querying for the analytics platform.
I create a dataset for each company, named such as company_123, company_124 etc.
Then within each dataset is the analytics for all the websites the company manages, with table names such as user_click_event_website_id, user_page_load_website_id etc.
I need to be able to query both 'all user clicks on website X' and 'all user clicks across all their websites'.
My question is, would it be better (cost & query time) to split my tables by website_id and run
select * from user_click_* and select * from user_click_website_x
or put them all in one table with a column for website_id and run
select * from user_click where website_id = 'website_x' and select * from user_click
Thanks

A: Without knowing the detail of your scenario and data, it is not easy to say which one is always better. As a starting point, I feel one table with website_id column seems worth to be tried unless you noticed major issues.


text:
Q: Connect postgresql database to codeigniter I have been connecting postgresql with codeigniter give error there is no connection and the db driver is invalid or not found what should i do ?
A Database Error Occurred
could not find driver

Filename: core/CodeIgniter.php

Line Number: 518

Be kind and suggest a solution.
Thanks.

A: https://codeigniter.com/user_guide/database/configuration.html
check your Database.php file in config folder.
add dns and other details. before that you must be ready with postgres installed on you server
    $db['default']['dsn'] = 'pgsql:host=localhost;port=5432;dbname=database_name';


text:
Q: visual studio code + ubuntu + chinese nameShort When I

*

*set nameShort to Chinese

*build deb

*install deb on ubuntu 20.04.2

then it will appear garbled on Ubuntu。 Like the screenshots

enter image description here
enter image description here


text:
Q: Why Doesn't DataObject.SetText(String) accept empty string? This is partially a rant and partially genuine curiosity.  Does anyone know why System.Windows.Forms.DataObject's SetText(String) method does not accept an empty string as its argument?  It states that this will throw an ArgumentNullException (even though it is not actually null).
I could understand it not accepting a null value, but it seems very unusual that it would not allow an empty string.  Is there something I am missing here, or was this just some arbitrary decision by an API designer?

A: The source says:
public virtual void SetText(string textData, TextDataFormat format)
{
    if (!string.IsNullOrEmpty(textData))
    {
        //
    }
    else
    {
        throw new ArgumentNullException("textData");
    }
}

But that's not the answer to your question, as you ask why this is. Browsing through the source I couldn't find an answer, nor during a quick scan of MSDN.


text:
Q: Call method of Objects, that are instances of Interface I have an Array of ClassA, which implements no interfaces. But there is a ClassB and a ClassC, which both implements the interface InterfaceA. InterfaceA looks like this:
public interface InterfaceA {
    int methodA();
}

Now I want to iterate through my Array of Instances of ClassA (which also contains some Instances of ClassB and ClassC) and I want to get the sum of every result of methodA().
At runtime, the following code should work (imO):
myArray = new ObjectA[10];

// how the Array gets it's content is irrelevant here

int result = 0;
for (final ObjectA a : myArray) {
    if (a instanceof InterfaceA) {
        result += a.methodA();
    }
}

But since ClassA does not necessarily have a methodA(), my Compiler is unhappy about it. It thinks, a.methodA() is not defined, because the compiler doesn't know about the if condition. So, in case you don't implement an abstract methodA() to ClassA, what would you do?

A: You should use cast to make your compiler happy. In your code the methodA is called on an a which can be an instance of ClassA, or ClassB or anything else.
As you are already restricting non interfaceA instances from reaching in the IF block you can use type cast.
for (final ObjectA a : myArray) {
    if (a instanceof InterfaceA) {
        result += ((InterfaceA)a).methodA();
    }
}


text:
Q: finding Remainder without actually dividing How to find the remainder when $6^{17}$ + $17^{6}$ is divided by 7 without actually performing the division

A: We have easily the result using the modular arithmetic
$$6^{17}+17^6\equiv -1+3^6\equiv-1+9^3\equiv-1+2^3=7\equiv0\mod7$$

A: Fermat little theorem gives: $$6^6 = 1  \mod 7 \Rightarrow 6^{12} = 1  \mod 7 $$ and $$6^5 = 6 \mod 7\Rightarrow 6^{17} = 6  \mod 7 $$ and $$17^6 = 1 \mod 7 \Rightarrow 6^{17} + 17^6 = 1 + 6  = 0 \mod 7$$


text:
Q: JUnit tests in IDEA: how to trim a stack trace? I have a Gradle project and when I run unit tests from within IntelliJ IDEA I got a very long stack trace:
org.opentest4j.AssertionFailedError: boom ==> expected: <true> but was: <false>
    at app//org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at app//org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    at app//org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
    at app//org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1152)
    at app//com.example.SimpleTest.shouldFail(SimpleTest.java:13)
    at java.base@17.0.3/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base@17.0.3/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base@17.0.3/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base@17.0.3/java.lang.reflect.Method.invoke(Method.java:568)
    at app//org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    at app//org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base@17.0.3/java.util.ArrayList.forEach(ArrayList.java:1511)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base@17.0.3/java.util.ArrayList.forEach(ArrayList.java:1511)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base@17.0.3/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base@17.0.3/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base@17.0.3/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base@17.0.3/java.lang.reflect.Method.invoke(Method.java:568)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)

How to configure Gradle and/or IDEA to hide most of the unrelated classes from the output?
Versions:

*

*IntelliJ IDEA 2022.1.2 (Ultimate Edition)

*Gradle 7.3.3

*JUnit 5.8.2

A: Right-click the line in the stack trace, choose "Fold lines like this". It will open the Console dialog where you can add/modify console lines


text:
Q: SQL group by (?) query not returning as required I have a sql table (see the .jpg included).
Some products, like 100 and 103 have the card value as 1300 but some products, like  101, don't. I need to create a sql query to identify products that don't have the 1300 card and return only those cards.
My group by query did not achieve this.

A: select product_id
from your_table
group by product_id
having sum(card = 1300) = 0

A: As mentioned in my comment, you can do it without a GROUP BY clause. @DrunkenCodeMonkey beat me to the answer while I was putting together a SQL Fiddle to show it in action.
select *
from products as t
where not exists (select *
                  from products as z
                  where z.product_id = t.product_id and z.card = 1300);

Both NOT IN and NOT EXISTS will work.

A: Not equal <> operator
You can use <> or != operator in where clause with group by
SELECT product_id
from table_name
where card <> 1300
group by product_id;

OR
SELECT product_id
from table_name
where card != 1300
group by product_id;

A: This should work. First get a list of the product IDs to exclude, and then get rows for all the other entries:
SELECT *
FROM MyTable
WHERE product_id NOT IN (SELECT product_id
                         FROM MyTable
                         WHERE card = 1300)

Here is a comparison on the execution plan of different approaches on MSSQL. The first two yield the exact same result, but the third, which is the closest approximation to MySQL's GROUP BY...HAVING SUM(card = 1300) = 0, is definitely more expensive because of the group by's aggregate and sort.


text:
Q: angularjs post data to mvc controller in json format I am working on a project in which I have used angularjs and mvc.I am passing data from angular js controller to my mvc controller by $http.post().For now I am using frombody attribute to retreive data like this -public string GetIssueDescription([FromBody]dynamic issueId).But I want that if I could do like this
public string GetIssueDescription(int issueId)
angularjs controller code
 //show issue details
$scope.showIssueDetails = function (issue) {
    //$scope.issueCount = 2;
    $scope.issueDetailsLoaded = false;
    $scope.selectedIssue = issue;
    $scope.statusName = issue.StatusName;
    var issueId = issue.Id;
    var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/GetIssueDescription/';
    $http.post(url, JSON.stringify({ issueId: issueId })).success(function (data, status, headers, config) {
        if (data != '' || data.length >= 0) {
            $scope.selectedIssue.Description = $sce.trustAsHtml(angular.fromJson(data));
            $scope.selectedIssue = issue;
            $scope.showedit = true;
            $scope.showeditdesc = true;

            //setting default properties
            //$scope.issue.DueDate = $scope.selectedIssue.DueDate;
            $scope.getIssueComment($scope.selectedIssue);
            $scope.issueDetailsLoaded = true;
        }
        else if (data == '') {
            $scope.selectedIssue.Description = "";
        } else {
            $scope.errors.push(data.error);
        }
    });
    if($scope.isVisible==false) {
        $("#changedetailsbox").hide();
        $scope.isVisible = true;
    }
    if ($scope.isVisibleReply == false) {
        $("#postReplybox").hide();
        $scope.isVisibleReply = true;
    }
};

MVC controller code
  [HttpPost]
    [AuthenticationRequired]
    public string GetIssueDescription([FromBody]dynamic issueId)
    {
        try
        {
            var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(issueId.ToString());
            var selectedIssueId = new Guid(dictionary["issueId"]);
            var result = PublicLayer.GetIssueDescription(selectedIssueId);
            return result.IsSuccessful ? result.Result : string.Empty;
        }
        catch (Exception ex)
        {
            BLL.Base.BaseLayer.WriteApplicationLog(ex);
            return string.Empty;
        }
    }

Please suggest how I could directly use my json data in my mvc controller.I took reference of this post but it didn't worked for me-Code I referred
I already have an issue model
 public partial class Issue
{
    public Guid Id { get; set; }
    public Guid ProjectId { get; set; }
    public Guid CreatorUserId { get; set; }
    public Guid AssignedUserId { get; set; }
    public Guid OwnerUserId { get; set; }
    public Guid LastUpdatedUserId { get; set; }
    public int DisplayId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public int IssueStatusId { get; set; }
    public int IssuePriorityId { get; set; }
    public int IssueTypeId { get; set; }
    public int IssueCategoryId { get; set; }
    public Guid? AffectedMilestoneId { get; set; }
    public int IssueResolutionId { get; set; }
    public DateTime DueDate { get; set; }
    public Guid? MilestoneId { get; set; }
    public decimal Estimation { get; set; }
    public int Progress { get; set; }
    public string SenderEmailAddress { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime LastUpdatedOn { get; set; }
}

Please suggest is it possible to use my this class in my method-public string GetIssueDescription(Issue issue) like this and can retreive my id by using issue.Id.Please suggest how to achieve this.

A: In your controller
change
public string GetIssueDescription([FromBody]dynamic issueId)

to
public string GetIssueDescription(Issue issue)

in your angular POST
var issueId = issue.Id;
.
.
$http.post(url, { Id: issueId }).success(function (data, status, headers, config) {


text:
Q: Temporarily launch dhcp server for point to point ethernet connection I have a headless computer configured to use a dhcp client which is directly connected to my laptop using an ethernet cable. I'm virtually sure I have seen a one liner before (using dnsmasq?) which would enable me to launch a dhcp server on that interface on my laptop, so that the headless computer would connect to it. This oneliner kept running in the foreground and displayed dhcp requests, so that I would see when the headless computer connected and would know its ip address. Could you tell me what that oneliner is?
I tried searching for quick/temporary dns setups and skimmed dnsmasq's manpage, but couldn't find anything.

A: You can connect to it using a local link IPv6 address.
Find out the address of the headless computer (let's say connected to eth3) with:
$ ping6 -L -I eth3 ff02::1
64 bytes from fe80::2671:89ff:ddb9:80be%eth3: icmp_seq=1 ttl=64 time=0.123 ms

Then use the address to ssh into it (if ssh is enabled).
ssh user@[fe80::2671:89ff:ddb9:80be%eth3]

Note that those addresses need to have the device attached to them and not all programs can parse them, but ssh, for example, can.
If both computers have avahi-daemon or a similar mDNS/DNS-SD software, the following command might be enough to connect via ssh.
ssh user@name_headless.local

(you can check with ping name_headless.local to see if it is resolving ok).
No need to configure anything else unless, of course, you need IPv4 connectivity.

A: dnsmasq --port 0 --no-daemon will launch dnsmasq in the foreground (so that you can see leases being allocated), as a DHCP server only (--port 0 disables DNS). dnsmasq will use the configuration in /etc/dnsmasq.conf; to ignore it and use default settings add --conf-file ''. You may also wish to add --interface to prevent dnsmasq from binding to all available interfaces by default. See the man page for the full list of options.


text:
Q: Databind Datagridview Combobox to a numeric field in c#.net 4.0 I am trying to bind a numeric field in an oracle table to a Datagridview - combo list in windows forms.  With this what am trying to achieve is;
1 ) Based on the numeric value present in the number field, fetch ad display the respective string value in dataviewgridcombolist column.
2). When a new row is added in the datagrid view, the user may be allowed to select a listed (string) value in the combo list and the respective index value to be stored in the table back.
lots of thanks in advance..
Regards
Rithesh Krishnan

A: I've created a customized grid control. Where you can specify each column type the respective editing control will be displayed - for the combo box column a combo box field will be displayed, for the numeric column a numeric editor will be displayed.
While user adding a new row also user will get these editors. Usage of this class as follows
customDataGrid1.ColumnDataTypeMapping.Add("EmployeeName", CustomDataGrid.CustomDataGridColumnType.TEXT);
customDataGrid1.ColumnDataTypeMapping.Add("ManagerID", CustomDataGrid.CustomDataGridColumnType.COMBOBOX);
customDataGrid1.ColumnDataTypeMapping.Add("JoinDate", CustomDataGrid.CustomDataGridColumnType.DATE);
customDataGrid1.ColumnDataTypeMapping.Add("DateOfBirth", CustomDataGrid.CustomDataGridColumnType.DATETIME);
customDataGrid1.ColumnDataTypeMapping.Add("Salary", CustomDataGrid.CustomDataGridColumnType.NUMERIC);