text:
Q: Me muestra error en registrar usuario en mi jsp Estoy haciendo un registrar usuario, pero al registrarlo me envía al servlet y me muestra una pagina en blanco.
Estoy con oracle, ya revise la conexión con la db y esta bien.
aquí esta el código del servlet que debe hacer el registro:
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("alertaRegistro", false);
        Usuario usu = new Usuario();
        UsuarioDAO usudao = new UsuarioDAO();
        Cliente cli = new Cliente();
        ClienteDAO clidao = new ClienteDAO();

        String m_alert = "";
        String razon_social = request.getParameter("razon_social");
        String rut_empresa = request.getParameter("rut_empresa");
        String nom_rep_legal = request.getParameter("nom_rep_legal");
        String rut_rep_legal = request.getParameter("rut_rep_legal");
        String nombre_usuario = request.getParameter("nombre_usuario");
        String contrasena = request.getParameter("contrasena");
        String rep_contrasena = request.getParameter("rep_contrasena");
        String telefono = request.getParameter("telefono");
        String correo_electronico = request.getParameter("correo_electronico");
        String rep_correo_elec = request.getParameter("rep_correo_elec");
        String direccion = request.getParameter("direccion");;
        String region = request.getParameter("region");
        String provincia = request.getParameter("provincia");
        String comuna = request.getParameter("comuna");
        String direccionCompleta;

        int estadoInsertCliente;

                if (estadoInsertCliente == 1) {
                    Usuario usu2 = usudao.obtenerDatosUsuario(usu.getCorreo_electronico(), usu.getContrasena());
                    request.setAttribute("nombre_usuario", usu2.getNombre_usuario());
                    request.setAttribute("contrasena", usu2.getContrasena());
                    request.setAttribute("razon_social", usu2.getRazon_social());
                    request.setAttribute("registrado", estadoInsertCliente);
                    request.setAttribute("correo_registro", usu2.getCorreo_electronico());
                    request.getRequestDispatcher("vistas/registro_exitoso.jsp").forward(request, response);
                } else {

                    request.getRequestDispatcher("vistas/error_registro.jsp").forward(request, response);
                }
            }
        }
    }
}

no logro determinar cual es el error en el codigo.


text:
Q: Rails ActiveRecord Date Comparison Database Agnostic? I'm trying to find a database agnostic way of comparing dates with active record queries. I've the following query:
UserRole.where("(effective_end_date - effective_start_date) > ?", 900.seconds)

This works fine on MySQL but produces an error on PG as the sql it generates doesn't contain the 'interval' syntax. From the console:
  ←[1m←[36mUserRole Load (2.0ms)←[0m  ←[1mSELECT "user_roles".* FROM "user_roles" WHERE "user_roles"."effective_end_date" IS NULL AND ((effective_end_d
ate - effective_start_date) > '--- 900
...
')←[0m
ActiveRecord::StatementInvalid: PG::Error: ERROR:  invalid input syntax for type interval: "--- 900

When I run this with the to_sql I option I get:
irb(main):001:0> UserRole.where("effective_end_date - effective_start_date) > ?", 900.seconds).to_sql
=> "SELECT \"user_roles\".* FROM \"user_roles\"  WHERE \"user_roles\".\"effective_end_date\" IS NULL AND (effective_end_date - effective_start_date) >
'--- 900\n...\n')"

All help appreciated.

A: If your effective_end_date and effective_start_date columns really are dates then your query is pointless because dates have a minimum resolution of one day and 900s is quite a bit smaller than 86400s (AKA 25*60*60 or 1 day). So I'll assume that your "date" columns are actually datetime (AKA timestamp) columns; if this is true then you might want to rename the columns to avoid confusion during maintenance, effectively_starts_at and effectively_ends_at would probably be good matches for the usual Rails conventions. If this assumption is invalid then you should change your column types or stop using 900s.
Back to the real problem. ActiveRecord converts Ruby values to SQL values using the ActiveRecord::ConnectionAdapters::Quoting#quote method:
def quote(value, column = nil)
  # records are quoted as their primary key
  return value.quoted_id if value.respond_to?(:quoted_id)

  case value
  #...
  else
    "'#{quote_string(YAML.dump(value))}'"
  end
end

So if you try to use something as a value for a placeholder and there isn't any specific handling built in for that type, then you get YAML (a bizarre choice of defaults IMO). Also, 900.seconds is an ActiveSupport::Duration object (despite what 900.seconds.class says) and the case value has no branch for ActiveSupport::Duration so 900.seconds will get YAMLified.
The PostgreSQL adapter provides its own quote in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#quote but that doesn't know about ActiveSupport::Duration either. The MySQL adapter's quote is also ignorant of ActiveSupport::Duration. You could monkey patch some sense into these quote methods. Something like this in an initializer:
class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
    # Grab an alias for the standard quote method
    alias :std_quote :quote
    # Bludgeon some sense into things
    def quote(value, column = nil)
        return "interval '#{value.to_i} seconds'" if(value.is_a?(ActiveSupport::Duration))
        std_quote(value, column)
    end
end

With that patch in place, you get intervals that PostgreSQL understands when you use an ActiveSupport::Duration:
> Model.where('a - b > ?', 900.seconds).to_sql
 => "SELECT \"models\".* FROM \"models\"  WHERE (a - b > interval '900 seconds')"
> Model.where('a - b > ?', 11.days).to_sql
 => "SELECT \"models\".* FROM \"models\"  WHERE (a - b > interval '950400 seconds')"

If you add a similar patch to the MySQL adapter's quote (which is left as an exercise for the reader), then things like:
UserRole.where("(effective_end_date - effective_start_date) > ?", 900.seconds)

will do The Right Thing in both PostgreSQL and MySQL and your code won't have to worry about it.

That said, developing and deploying on different databases is a really bad idea that will make Santa Claus cry and go looking for some coal (possibly laced with arsenic, possibly radioactive) for your stocking. So don't do that.
If on the other hand you're trying to build database-agnostic software, then you're in for some happy fun times! Database portability is largely a myth and database-agnostic software always means writing your own portability layer on top of the ORM and database interfaces that your platform provides. You will have to exhaustively test everything on each database you plan to support, everyone pays lip service to the SQL Standard but no one seems to fully support it and everyone has their own extensions and quirks to worry about. You will end up writing your own portability layer that will consist of a mixture of utility methods and monkey patches.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I calculate the new position of a given rectangle after subjecting it to rotation and scaling? I want to calculate the new position of a modified version of a given rectangle.

*

*The given rectangle is shown in Yellow.

*The rectangle undergoing rotation and scaling is shown in Red.

Step-1:  The known coordinates of the Yellow rectangle are given in image below.
X = -39,
Y = 501,
Width = 843,
Height = 181,
Center X = 383,
Center Y = 592

Step-2: I start by rotating the given rectangle $\bf{45^o}$ counterclockwise about its center.

Step-3: Now, I am decreasing its width and increasing its height while holding its top and left edges in place.
Width = 639,
Height = 284

Step-4: Finally, the scaled rectangle is rotated clockwise by $\bf{45^o}$ about its new center.

I want to determine the Cartesian coordinates of the top-left corner and the center of the modified rectangle.

A: One way is, just apply the rules for each transformation to each point, starting at the beginning and continuing until you are finished.
However, in this particular case there are some simplifying observations.
First, the rotations do not move the center of the rectangle.
The center moves only during the "rescaling" operation.
For every unit the width increases, the center moves $\frac12$ unit in the diagonal direction toward the upper right.
For every unit the height increases, the center moves $\frac12$ unit in the diagonal direction toward the lower right.
Since you apparently have the $x$ axis to the right and the $y$ axis downward,
a unit vector toward the upper right is $\left(\sqrt2/2, -\sqrt2/2\right)$
and a unit vector toward the lower right is $\left(\sqrt2/2, \sqrt2/2\right)$.
At the end, once you determine the position of the center, you can use the new height and width to determine the upper left corner.

As an aside, in regular coordinate geometry the height of an axis-parallel rectangle would be exactly twice the difference between the $y$ coordinates of one corner and the center, whereas you have $2(592 - 501) = 182 \neq 181,$
so there is some unusual arithmetic going on in how you define your objects.


text:
Q: Lwc Data Binding not working Hey Salesforce StackExchange!
I am trying to databind inside of a span but it does not work. I am getting an Undefined Result back, but I can also see that the span has rendered out with data from the chrome dev console. This is happening on onclick={handelBadgeSelected}
Could someone please point me in the right direction and tell me what I am doing wrong?
Here is the HTML:
<template for:each={selectedbadges} for:item="selectedbadge">

                                <input type="radio" id={selectedbadge.Id} value={selectedbadge.Id} name="options" />

                                        {selectedbadge.Name}

                        </template>

And here is the JS
handelBadgeSelected(event) {
  window.console.log('Selected Badge Info:',  event.target.dataset.name);
}

The Error:

A: I am not completely certain but I believe your problem is coming from the fact that you have a few nested elements. Let's take a look:

In this example you have the parent span <span data-name={selectedbadge.Name} onclick={handelBadgeSelected}. However inside of it you have a few other spans and img tags. So when you click on the parent span you are probably actually clicking on one of the children and then the event propagates to the parent span. However the event is coming from the child which doesn't have a data-name attribute.
The way to solve this is to either:

*

*Put data-name={selectedbadge.Name} on all children OR

*To use the css property pointer-events: none; on the children so you can control where the event triggers from.


text:
Q: How can i continously move the view? I want to create a simple app in which I want to make a road which is continuously animated. How can I do that?

A: I used a UIScrollView. Then, set up an NSTimer that runs the following:

-(void)scroll{
    CGPoint currentPoint = playerStatsRect.contentOffset;
    CGPoint scrollPoint = CGPointMake(currentPoint.x, currentPoint.y + 1);
    [playerStatsRect setContentOffset:scrollPoint animated:NO];

    if(scrollPoint.y == playerStatsRect.contentSize.height+5)//If we've reached the bottom, reset slightly past top, to give ticker look
    {
        [playerStatsRect setContentOffset:CGPointMake (0,-125)];
    }
}

Hope this helps :)


text:
Q: My footer link CSS styles aren't working The links on my footer are not working. The links are not hoverable or clickable.

I'm sorry, I should have added that the z-index on the footer is set to -999 so that it stays behind the main content. Is there a work around if that is the issue?

Contact Us

About EIC

footer {
    position: fixed;
    width: 100%;
    height: 8em;
    background-color: e0e0e0;
    z-index: -999;
    overflow: hidden;
    bottom: 0px;
    padding-top: 2%;
}
footer li {
    display: inline;
    padding: 2em;
}
footer a:link {
    color: #000;
    text-decoration: none;
}
footer a:hover {
    color: #999;
}

View it on jsFiddle.

A: Your z-index: -999 on the footer moves it behind the actual document. So the links are not clickable or hoverable.
Actually, this kind of problem is easily noticable when using the "Inspect Element" feature of firebug or firefox's developer tools. Inspecting the link will not select the link but rather your document - that tells you that the link is behind something (the element that was inspected instead of the link).

A: Remove the z-index: -999 declaration. Your footer is behind the clickable page area.

A: What the above people said, plus your missing a # for you background color.
http://jsfiddle.net/Vsvg2/8/

A: You should remove:
html{
    height: 100%;
}

from your css.
Edit:
you still have to remove z-index: -999;
Thank you animuson for correcting me.


text:
Q: Why does the program work after removing the symbol information? I made one SO file and compiled it with a compile option called "-Xlinker --strip-all " to counter any reverse engineering (use clang).
Thanks to this, most of the symbols of functions other than functions directly exposed to the outside do not appear (objdump -TC test.so). The question is, if a symbol is deleted like this, it should not be used inside the program, so I think it is normal. What am I missing?

A: You're right, debugging symbols aren't needed by the program itself to execute; the linker computes (and therefore knows at link-time) what the memory-address of each function/global-variable/etc will be at run-time, so it can just place that memory-address directly into the executable where necessary.
The symbols are there for a debugger to use, to make the debugging output easier for a human (or a debugging tool) to use and understand.


text:
Q: RESTful API for POST when other HTTP Verbs' paths have multiple Params? Hello and happy January!
Reviewing my recently created a very simple RESTful API, I am wondering if I did the RESTful API signature for its POST.
This RESTful API queries a very simple MongoDB collection Apps, and its columns are:

*

*_id, (appId)

*siteId (required)

*accountId (required)

*provider (required)

*description
Index:

*

*provider, siteId, accountId: unique
Data structure:

*

*Each Site (siteId) has multiple Accounts (accountId).

*Each Account (accountId) has multiple Apps (appId).

The paths for HTTP Verbs GET DELETE and PATCH handling items in the collection Apps are:

*

*GET /api/v1/sites/:siteId/accounts/:accountId/apps

*DELETE /api/v1/sites/:siteId/accounts/:accountId/apps

*PATCH /api/v1/sites/:siteId/accounts/:accountId/apps
My quandary is a follows: I want to POST a new app that will be associated with siteId + accountId.
I am wondering if how I defined this POST path makes sense, because the new app may be adding to this collection either siteId or accountId for the first time.
This is what I had implemented for HTTP Verb POST:
POST /api/v1/sites/:siteId/accounts/:accountId/apps

params: {
  siteId: string,
  accountId: string,
},
body: {
  provider: '[** Provider **]',
  description: '[** Description **]',

  siteId: '[** Site ID **]',
  accountId: '[** Account ID **]'
},
response: new `appId`

Or should it be (which I am starting to lean towards):
POST /api/v1/apps

body: {
  provider: '[** Provider **]',
  description: '[** Description **]',

  siteId: '[** Site ID **]',
  accountId: '[** Account ID **]'
},
response: new `appId`

Recommendations are truly welcomed!

A: First of, it would be a little odd to have the siteId and accountId both in the url and the body. The url suggests you are creating an app for a specific site, and then the site is a variable in the message body, meaning it could be any site. This would only lead to confusion.
Do you want someone to be able to register a new app for any site/account combination? Or would someone go from selecting a site to registering a new app for that site. In the first case I would put it all in the body, in the second case go with the site in the url.
Considering RESTfulness; when you use the api to find sites or a specific site before you register an app to a specific site, the 'site' object in the response would have a reference to where one would register an app for that site. This link would probably contain the siteId. However if it were just a url where you could register any site, the siteId would have no place in the url and not even be part of that specific response.
I think I would take account out of the url regardless, this seems to be that it would always be the same and just something you have to pass on as a variable.


text:
Q: Undefined offset when printing elements of an array I have this code:
$items_query = mysql_query('SELECT * FROM Items_Orders NATURAL JOIN Items
                                    WHERE order_id="'.$order->order_id.'"');

    if(!$items_query)
    {
        echo 'MySQL error: '.mysql_error();
        die();
    }

    //add each item to the order
    while($items_row = mysql_fetch_array($items_query))
    {
        echo "item: ";

        for($i = 0; $i < count($items_row); $i++)
        {
            echo $items_row[$i];
        }
    }

When the elements of the items_row are printed, my code iterates beyond the bounds of items row.  I am confused at why this is.  I explicitly define i to only iterate up to the size of items_row.  What's going on here?

A: You are counting double length, because by default, you are getting named an numbered values. Try the following
while($items_row = mysql_fetch_array($items_query, MYSQL_NUM))
{
    echo "item: ";

    for($i = 0; $i < count($items_row); $i++)
    {
        echo $items_row[$i];
    }
}

See offical docs
P.S. mysql_* is deprecated, look into PDO object.

A: Try this:
while($row = mysql_fetch_array($query,MYSQL_NUM)){
   $count = count($row);
   for($i = 0;$i < $count;$i++){
       echo $row[$i];
   }
}

But your code is very dirty, why you do not use PDO ? Is the fast way how to make escaped queries... PDO manual


text:
Q: How can I change a working python program so that it runs as python flask program I have a python program, an expert system, it runs ok as a purely python program. but I now want to run it as a python flask program so that it can appear as on a browser and maybe be integrated as a whatsapp or sms chatbot.
the change from just python to make the code into sort of a chatbot is what I am looking for.
  # from pyknow import *
from experta import *
from flask import Flask
# import os
app = Flask(__name__)

# print(os.getcwd())
diseases_list = []
diseases_symptoms = []
symptom_map = {}
d_desc_map = {}
d_treatment_map = {}

def preprocess():
    global diseases_list,diseases_symptoms,symptom_map,d_desc_map,d_treatment_map
    diseases = open("diseases.txt")
    diseases_t = diseases.read()
    diseases_list = diseases_t.split("\n")
    diseases.close()
    for disease in diseases_list:
        #symptoms=os.path.dirname("symptoms/"+ disease + ".txt")
        disease_s_file = open("Dsymptoms/"+ disease + ".txt")
        disease_s_data = disease_s_file.read()
        s_list = disease_s_data.split("\n")
        diseases_symptoms.append(s_list)
        symptom_map[str(s_list)] = disease
        disease_s_file.close()
        disease_s_file = open("Ddescriptions/" + disease + ".txt")
        disease_s_data = disease_s_file.read()
        d_desc_map[disease] = disease_s_data
        disease_s_file.close()
        disease_s_file = open("Dtreatments/" + disease + ".txt")
        disease_s_data = disease_s_file.read()
        d_treatment_map[disease] = disease_s_data
        disease_s_file.close()

def identify_disease(*arguments):
    symptom_list = []
    for symptom in arguments:
        symptom_list.append(symptom)
    # Handle key error
    return symptom_map[str(symptom_list)]

def get_details(disease):
    return d_desc_map[disease]

def get_treatments(disease):
    return d_treatment_map[disease]

def if_not_matched(disease):
        print("")
        id_disease = disease
        disease_details = get_details(id_disease)
        treatments = get_treatments(id_disease)
        print("")
        print("The most probable disease that you have is %s\n" %(id_disease))
        print("A short description of the disease is given below :\n")
        print(disease_details+"\n")
        print("The common nutritional treatments recommended by doctors, nurses and nutrionists are \n")
        print(treatments+"\n")

def identify_disease(*arguments):
    symptom_list = []
    for symptom in arguments:
        symptom_list.append(symptom)
    # Handle key error
    return symptom_map[str(symptom_list)]

def get_details(disease):
    return d_desc_map[disease]

def get_treatments(disease):
    return d_treatment_map[disease]

def if_not_matched(disease):
        print("")
        id_disease = disease
        disease_details = get_details(id_disease)
        treatments = get_treatments(id_disease)
        print("")
        print("The most probable disease that you have is %s\n" %(id_disease))
        print("A short description of the disease is given below :\n")
        print(disease_details+"\n")
        print("The common nutritional treatments recommended by doctors, nurses and nutrionists are: \n")
        print(treatments+"\n")

# @my_decorator is just a way of saying just_some_function = my_decorator(just_some_function)
#def identify_disease(bloated_stomach, thin_limbs,reddish hair, swollen face):
@app.route('/')
class Greetings(KnowledgeEngine):
    @DefFacts()
    def _initial_action(self):
        print("")
        print("Hi! I am Dr.Jephtah, I am here to help your child's health better.")
        print("Firstly I am are assuming that the child is under the age of 6 as this system works best for those childeren  ")
        print("For that you'll have to answer a few questions about your conditions")
        print("Do you feel any of the following symptoms:")
        print("")
        yield Fact(action="find_disease")

    @Rule(Fact(action='find_disease'), NOT(Fact(slight_hair=W())),salience = 1)
    def symptom_0(self):
        self.declare(Fact(slight_hair=input("slight hair: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(reddish_hair=W())),salience = 1)
    def symptom_1(self):
        self.declare(Fact(reddish_hair=input("reddish hair: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(hair_falling=W())),salience = 1)
    def symptom_2(self):
        self.declare(Fact(hair_falling=input("hair falling easily: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(abnormal_skin=W())),salience = 1)
    def symptom_3(self):
        self.declare(Fact(abnormal_skin=input("abnormal skin (eg skin shedding, lessions, skin ulcers): ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(swollen_face=W())),salience = 1)
    def symptom_4(self):
        self.declare(Fact(swollen_face=input("Swollen Face: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(glazed_eyes=W())),salience = 1)
    def symptom_5(self):
        self.declare(Fact(glazed_eyes=input("glazed eyes: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(apathetic=W())),salience = 1)
    def symptom_6(self):
        self.declare(Fact(apathetic=input("child is apathetic: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(smaller_muscles=W())),salience = 1)
    def symptom_7(self):
        self.declare(Fact(smaller_muscles=input("smaller muscles: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(anaemic=W())),salience = 1)
    def symptom_8(self):
        self.declare(Fact(anaemic=input("anaemic (weak/tired): ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(diarrhoea=W())),salience = 1)
    def symptom_9(self):
        self.declare(Fact(diarrhoea=input("diarrhoea: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(bloated_stomach=W())),salience = 1)
    def symptom_10(self):
        self.declare(Fact(bloated_stomach=input("bloated stomach: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(thin_body=W())),salience = 1)
    def symptom_11(self):
        self.declare(Fact(thin_body=input("thin body: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(older_face=W())),salience = 1)
    def symptom_12(self):
        self.declare(Fact(older_face=input("Face looks older: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(cranky_child=W())),salience = 1)
    def symptom_13(self):
        self.declare(Fact(cranky_child=input("cranky child: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(wrinkled_skin=W())),salience = 1)
    def symptom_14(self):
        self.declare(Fact(wrinkled_skin=input("Wrinkled skin: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(little_fattie_tissue=W())),salience = 1)
    def symptom_15(self):
        self.declare(Fact(little_fattie_tissue=input("Liitle fattie tissue on hips and others: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(converse_stomach_rib_prominent=W())),salience = 1)
    def symptom_16(self):
        self.declare(Fact(converse_stomach_rib_prominent=input("converse stoamch rib prominent: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(chronic_infections=W())),salience = 1)
    def symptom_17(self):
        self.declare(Fact(chronic_infections=input("repeated chronic infections: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(skin_reddish_purging=W())),salience = 1)
    def symptom_18(self):
        self.declare(Fact(skin_reddish_purging=input("Skin reddish or purging: ")))

    @Rule(Fact(action='find_disease'), NOT(Fact(age=W())),salience = 20)
    def symptom_19(self):
        self.declare(Fact(age=input("Is age below 2 years: ")))

    @Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="no"),Fact(bloated_stomach="yes"),Fact(thin_body="no"),Fact(older_face="no"),Fact(child_cranky="no"),Fact(wrinkled_skin="no"),Fact(little_fattie_tissue="no"),Fact(converse_stomach_rib_prominent="no"),Fact(chronic_infections="no"),Fact(skin_reddish_purging="no"),Fact(age="no"))
    def disease_0(self):
        self.declare(Fact(disease="Kwashiorkor"))

    @Rule(Fact(action='find_disease'),Fact(slight_hair="no"),Fact(reddish_hair="no"),Fact(hair_falling="no"),Fact(abnormal_skin="yes"),Fact(swollen_face="no"),Fact(glazed_eyes="no"),Fact(apathetic="no"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="no"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="no"))
    def disease_1(self):
        self.declare(Fact(disease="Marasmus"))

    @Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="yes"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="no"))
    def disease_2(self):
        self.declare(Fact(disease="Marasmus-Kwashiorkor"))

    @Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="no"),Fact(bloated_stomach="yes"),Fact(thin_body="no"),Fact(older_face="no"),Fact(child_cranky="no"),Fact(wrinkled_skin="no"),Fact(little_fattie_tissue="no"),Fact(converse_stomach_rib_prominent="no"),Fact(chronic_infections="no"),Fact(skin_reddish_purging="no"),Fact(age="yes"))
    def disease_3(self):
        self.declare(Fact(disease="Kwashiorkor_"))

    @Rule(Fact(action='find_disease'),Fact(slight_hair="no"),Fact(reddish_hair="no"),Fact(hair_falling="no"),Fact(abnormal_skin="yes"),Fact(swollen_face="no"),Fact(glazed_eyes="no"),Fact(apathetic="no"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="no"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="yes"))
    def disease_4(self):
        self.declare(Fact(disease="Marasmus_"))

    @Rule(Fact(action='find_disease'),Fact(slight_hair="yes"),Fact(reddish_hair="yes"),Fact(hair_falling="yes"),Fact(abnormal_skin="yes"),Fact(swollen_face="yes"),Fact(glazed_eyes="yes"),Fact(apathetic="yes"),Fact(smaller_muscles="yes"),Fact(anaemic="yes"),Fact(diarrhoea="yes"),Fact(bloated_stomach="yes"),Fact(thin_body="yes"),Fact(older_face="yes"),Fact(child_cranky="yes"),Fact(wrinkled_skin="yes"),Fact(little_fattie_tissue="yes"),Fact(converse_stomach_rib_prominent="yes"),Fact(chronic_infections="yes"),Fact(skin_reddish_purging="yes"),Fact(age="yes"))
    def disease_5(self):
        self.declare(Fact(disease="Marasmus-Kwashiorkor_"))

    @Rule(Fact(action='find_disease'),Fact(disease=MATCH.disease),salience = -998)
    def disease(self, disease):
        print("")
        id_disease = disease
        disease_details = get_details(id_disease)
        treatments = get_treatments(id_disease)
        print("")
        print("The most probable disease that you have is %s\n" %(id_disease))
        print("A short description of the disease is given below :\n")
        print(disease_details+"\n")
        print("The common treatments recommended by experts are: \n")
        print(treatments+"\n")

    @Rule(Fact(action='find_disease'),
        Fact(slight_hair=MATCH.slight_hair),
        Fact(reddish_hair=MATCH.reddish_hair),
        Fact(hair_falling=MATCH.hair_falling),
        Fact(abnormal_skin=MATCH.abnormal_skin),
        Fact(swollen_face=MATCH.swollen_face),
        Fact(glazed_eyes=MATCH.glazed_eyes),
        Fact(apathetic=MATCH.apathetic),
        Fact(smaller_muscles=MATCH.smaller_muscles),
        Fact(anaemic=MATCH.anaemic),
        Fact(diarrhoea=MATCH.diarrhoea),
        Fact(bloated_stomach=MATCH.bloated_stomach),
        Fact(thin_body=MATCH.thin_body),
        Fact(older_face=MATCH.older_face),
        Fact(cranky_child=MATCH.cranky_child),
        Fact(wrinkled_skin=MATCH.wrinkled_skin),
        Fact(little_fattie_tissue=MATCH.little_fattie_tissue),
        Fact(converse_stomach_rib_prominent=MATCH.converse_stomach_rib_prominent),
        Fact(chronic_infections=MATCH.chronic_infections),
        Fact(skin_reddish_purging=MATCH.skin_reddish_purging),
        Fact(age=MATCH.age),NOT(Fact(disease=MATCH.disease)),salience = -999)

        #   Fact(age=MATCH.age),

    def not_matched(self,slight_hair, reddish_hair, hair_falling, abnormal_skin, swollen_face, glazed_eyes, apathetic, smaller_muscles, anaemic ,diarrhoea ,bloated_stomach ,thin_body ,older_face, cranky_child ,wrinkled_skin ,little_fattie_tissue ,converse_stomach_rib_prominent ,chronic_infections, skin_reddish_purging, age):
        print("\nDid not find any disease that matches your exact symptoms")
        lis = [slight_hair, reddish_hair, hair_falling, abnormal_skin, swollen_face, glazed_eyes, apathetic, smaller_muscles,anaemic ,diarrhoea ,bloated_stomach ,thin_body ,older_face, wrinkled_skin, cranky_child, little_fattie_tissue, converse_stomach_rib_prominent, chronic_infections, skin_reddish_purging, age]
        max_count = 0
        max_disease = ""
        for key,val in symptom_map.items():
            count = 0
            temp_list = eval(key)
            for j in range(0,len(lis)):
                if(temp_list[j] == lis[j] and lis[j] == "yes"):
                    count = count + 1
            if count > max_count:
                max_count = count
                max_disease = val
        if_not_matched(max_disease)

if __name__ == "__main__":
    preprocess()
    engine = Greetings()
    while(1):
        engine.reset()  # Prepare the engine for the execution.
        engine.run()  # Run it!
        print("Would you like to diagnose some other symptoms?")
        if input() == "no":
            exit()
        #print(engine.facts)

`

A: You need to follow the steps in a Flask tutorial. Take a look at this one


text:
Q: How to compare 2 columns and concatenate in Scala This is my text file that is an input to the program:
Id       Title Copy
B2002010 gyh   1
D2001001 abc   12
M2003005 zxc   3
D2002003 qwe   13
M2001002 efg   1
D2001004 asd   6
D2003005 zxc   3
M2001006 wer   6
D2001006 wer   6
B2004008 sxc   10
D2002007 sdf   9
D2004008 sxc   10

ID is formatted as Xyyyyrrr where:

*

*X is B => Book or M => Magazine

*yyyy is the year

*rrr is random number.

What I have to do is: Obtain the total number of copies for books or magazines which are from the same year. Plus, a small data cleansing for the column "copy", if I find something other than a number I will replace it with a '0'.
My Spark project is on Eclipse and I am using Maven and Scala IDE
I need to use a MapReduce Function.
I have started my Map function that splits the text file.
This is the code I started:
package bd.spark_app

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.sql.SQLContext
import org.apache.spark.sql._
import org.apache.spark.sql.types.IntegerType
import org.apache.spark.rdd.RDD.rddToOrderedRDDFunctions
import scala.io.Source
import org.apache.spark.sql.functions._
import scala.collection.mutable.WrappedArray
import org.apache.log4j._
import org.apache.spark.sql.types.{StructType, StructField, StringType}
import org.apache.spark.sql.Row
import scala.Array

object alla {
  def main(args:Array[String]) = {
    val conf = new SparkConf().setMaster("local").setAppName("trying")
    val sc = new SparkContext(conf)
    val x = sc.textFile("/home/hadoopusr/sampledata")

    x.map(_.split(" ")).foreach(r =>
      println(r(0).dropRight(3), r(2))
    )

    sc.stop()
  }
}

This is my result for the Map function I have showed above
(B2002,1)
(D2001,12)
(M2003,3)
(D2002,13)
(M2001,1)
(D2001,6)
(D2003,3)
(M2001,6)
(D2001,6)
(B2004,10)
(D2002,9)
(D2004,10)
(M2004,11)
(D2004,11)

I just need some sort of reduce function that will grab all the books and magazines from the same year and add the number of copies together and check that the column "copy" are Numbers
Example: with records (B2002,12) and (B2002,16) the result should be (B2002,28).

A: Method "reduceByKey" can be used:
val converted = x.map(_.split(" ")).map(r => (r(0).dropRight(3), r(2).toInt))
val result = converted.reduceByKey(_ + _)

Output:
(M2001,7)
(D2001,24)
(M2003,3)
(D2003,3)
(D2002,22)
(D2004,10)
(B2002,1)
(B2004,10)

Note: looks like input file has "csv" format, and better use "spark.read.csv" for read data, and work with DataFrame instead of RDD.


text:
Q: How to split string in JavaScript with splitter? can we split the input string with splitter /* ! */
I have string
var a ="/*! ###################################################### # Test.cs #  RELEASE: 1.1.1 # BUILD DATE: Fri Oct 30 2020 15:25:57 GMT-0700 (PDT) # COPYRIGHT ###################################################### *//*! MISC + SASS */a:focus,button:focus,div[tabindex]:focus,li[tabindex]:focus,span[tabindex]:focus{outline-offset:2px;outline-width:2px!important;outline-style:dotted!important;outline-color:currentColor}/*! GENERIC - BGIMG */.bgimg{background-size:cover;background-position:50% 50%;background-repeat:no-repeat}/*! CG2111 - test */span{color:red}/*! CG2112 - test */span{color:red}/*! INFO */#id{content:'1.1.1'}"

I am trying to split string using commented code /* ! */
Expected output
{
  "MISC + SASS " : "span[tabindex]:focus,
  li[tabindex]:focus,
  div[tabindex]:focus,
  button:focus,
  a:focus {
    outline-offset: 2px;
    outline-width: 2px !important;
    outline-style: dotted !important;
    outline-color: currentColor;
  }",
  "GENERIC - BGIMG":".bgimg {
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
  }",
  "CG2111 - test":"span {
    color: red;
  }",
  "CG2112 - test":"span {
    color: red;
  }",
  "INFO":"#id {
    content: '1.1.1';
  }"

}

or store in array only value.

A: Here's one way using a regex to split it into an array based on the /*! ... */ structure.

const a = "/*! ###################################################### # Test.cs #  RELEASE: 1.1.1 # BUILD DATE: Fri Oct 30 2020 15:25:57 GMT-0700 (PDT) # COPYRIGHT ###################################################### *//*! MISC + SASS */a:focus,button:focus,div[tabindex]:focus,li[tabindex]:focus,span[tabindex]:focus{outline-offset:2px;outline-width:2px!important;outline-style:dotted!important;outline-color:currentColor}/*! GENERIC - BGIMG */.bgimg{background-size:cover;background-position:50% 50%;background-repeat:no-repeat}/*! CG2111 - test */span{color:red}/*! CG2112 - test */span{color:red}/*! INFO */#id{content:'1.1.1'}";

const result = {}, temp = a.split(/\/\*\!\s*(.*?)\s*\*\//).slice(1);
while (temp.length) result[temp.shift()] = temp.shift();

console.log(result);

A: Assuming the sequence *//*! will always be a part of your string(just before the beginning of your expected result):

const a ="/*! ###################################################### # Test.cs #  RELEASE: 1.1.1 # BUILD DATE: Fri Oct 30 2020 15:25:57 GMT-0700 (PDT) # COPYRIGHT ###################################################### *//*! MISC + SASS */a:focus,button:focus,div[tabindex]:focus,li[tabindex]:focus,span[tabindex]:focus{outline-offset:2px;outline-width:2px!important;outline-style:dotted!important;outline-color:currentColor}/*! GENERIC - BGIMG */.bgimg{background-size:cover;background-position:50% 50%;background-repeat:no-repeat}/*! CG2111 - test */span{color:red}/*! CG2112 - test */span{color:red}/*! INFO */#id{content:'1.1.1'}";

const arr = a.split('*//*!');
const arr2 = arr[1].split('/*!');

const obj = {};
for(const item of arr2){
  const tmp = item.split('*/');
  obj[tmp[0]] = tmp[1];
}
console.log(obj);


text:
Q: Insert all remaining dates until a specific date into a slider I am using a bootstrap slider for an interest calculator, where I can slide an amount from 0 - 15.000 DKK and another slider that contains remaining days until a specific dates.
Those two slider will calculate the interest when money is inserted at specific dates.
My problem now is that I want the slider tooltip to show sequential dates, i.e at page load the slider will start on todays date (3 March 2016), then when I slide it 4 steps the tooltip should show 7 March 2016, and if I slide it 30 steps it should show 2 April.
The slider is initialised with this:
$(".date").slider({
    tooltip: 'always',
    min: 1,
    max: daysRemaining,
    step: 1,
    value: daysRemaining,
    formatter: function (daysRemaining) {
       DateOutputFunction here
     }
 });

daysRemaining are found using moment.js
var today = moment();
var lastDate = moment("20161212");
var daysRemaining = lastDate.diff(today, "days");

A: You can use moment add and moment format to get what you need, for example:

var today = moment();
var lastDate = moment("20161212");
var daysRemaining = lastDate.diff(today, "days");

$(".date").slider({
    tooltip: 'always',
    min: 1,
    max: daysRemaining,
    step: 1,
    value: daysRemaining,
    formatter: function (value) {
        var today = moment();
        var day = today.add(value, "days");
        return day.format("D MMMM YYYY");
    }
 });
.slider{
  margin: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/6.1.1/bootstrap-slider.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/6.1.1/css/bootstrap-slider.min.css">

<input type="text" class="date">


text:
Q: AS3 Air — Check a Zip to get Audio File I have a problematic situation that I wish to expose you because it contains some opposites constraints. Maybe someone will have an idea on how to unlock my problem.
I'm going to make a mobile application with ActionScript 3 and Air for iOS and Android. This application has to download zip file which it uses to display text, bitmap and sound.
This last one is the problem.
After some research, one of the best way I found to check a zip file is FZip, but it allows us to get data from zip on a ByteArray form. And a Sound can't be converted from ByteArray. ( That's what a lots of results about it appear to say. )
One of the solution proposed is to put the ByteArray of a sound and put it in a SWF. Then take the SWF from the zip to get the Sound.
I can't do that because this zip will be uploaded from a admin interface used by anybody. I can't force them to use Flash.
I have few potential direction where I ask for your advices :
• Use Code or Native Extension ( iOS and Android ) to check a zip without files read in ByteArray
• Convert a ByteArray into Sound without have to pass it in a SWF
• Dynamicly create a SWF with the ByteArray of a Sound
• In the last possibility, another way to drag and download few files together which can be consulted in another format than ByteArray ( Like a iOS Bundle but with android too )
Thanks a lot to help me,

A: You can simply write the ByteArray on a local mp3 (or mp4) file and then play it, to write a ByteArray to file see documentation here.


text:
Q: iOS: create a NSDate object for each month between two specific dates So i'm looking to create an object for each month in-between two dates..
Start: 01/08/2012
End: 02/10/2012
would be two months so id like to list out:
01/09/2012
01/10/2012
..ready for me to create an NSDate for each of those to push to Parse(.com)..
Here's what i've got so far:
    NSString *start = @"2010-09-15";
    NSString *end = @"2011-07-15";

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [f dateFromString:start];
    NSDate *endDate = [f dateFromString:end];

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSMonthCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];

    int i=0;

    for (i = 0; i < [components month]; i++)
    {

        NSLog(@"%i", i+1);

        NSDateFormatter *df = [NSDateFormatter new];
        // change locale if the standard is not what you want
        NSArray *monthNames = [df standaloneMonthSymbols];
        NSString *monthName = [monthNames objectAtIndex:(i)];

        NSLog(@"Month name: %@", monthName);

    }

Thanks for your help!

A: You have the right idea. You have code to convert the start date string to an NSDate, and to figure out the number of months between the 2 dates. Presumably what you want to send to parse.com is date strings in the same format, right?
Let's call the number of months between your start date and end date monthCount.
In that case, in your for loop, you should use the NSCalendar method dateByAddingComponents:toDate:options: to add 0 -> monthCount to the date, and then use your date formatter's stringFromDate method to convert that date to a date string.


text:
Q: Sqlalchemy errror: obj must be an instance or subtype of type I get the following error when running the code below:
File "E:\ProgramData\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 60, in __init__
    super(VisitableType, cls).__init__(clsname, bases, clsdict)
TypeError: super(type, obj): obj must be an instance or subtype of type

Code:
import pandas as pd
import mysql.connector
import sqlalchemy as sl

engine=sl.create_engine('mysql+mysqlconnector://root:xxxx@11.11.11.11:3306/kafka')

df = pd.read_sql('select * from kafka_test limit 10', con=engine)
df.head()


text:
Q: How to execute chained commands in a shell running as a child process? Following the question at How to execute a command in a shell running as a child process?, I want to execute multiple commands.
let mut child = Command::new("sh").stdin(Stdio::piped())
    .stderr(Stdio::piped())
    .stdout(Stdio::piped())
    .spawn()?;

child.stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?
    .write_all(b"something...")?;

let output = child.wait_with_output()?;

Is it possible to do something like this?
.write_all(b"something...")?
.write_all(b"something...")?;

A: This is not a problem in Rust, but sh. In sh you need to separate commands by newlines ("\n"):
//...
.write_all(b"command1\ncommand2")?;
//...

this should work too:
//...
let child_stdin = child.stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?;

child_stdin.write_all(b"command1\n")?;
child_stdin.write_all(b"command2\n")?;
//...

A: Chaining method calls works for methods that, by convention, return self or &mut self. There is no guarantee that all methods do that, some simply have more useful return values. For example, write_all() returns Result<(), io::Error>, declaring that it has no useful value other than showing whether the writing succeeded or failed.
To call such a method twice, you need to save your value into a local variable:
let child_stdin = child
    .stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?;
child_stdin.write_all(b"something...")?;
child_stdin.write_all(b"something...")?;


text:
Q: How do I get a log-log plot in Numbers I can't seem to find a way to create a log-log plot in Numbers 4.2, something that should be as easy as clicking twice!
The option is only available for the Y-axis:

A: You need to use a scatter graph for value-value graphs. Other graph types use category-value, shown at the top of your screenshot. To replace your graph with a scatter graph, choose Chart → Chart Type and select 2D Scatter. Now, under Axis the tabs will show 'Value (Y)' and 'Value (X)' instead of 'Category (X)', such that Logarithmic is available for both.


text:
Q: I am trying to copy the content of file into a class variable. But its not working class book:
    def __init__(self):
        print("class created")
    def input(self):
        no_list=[]
        fp="book_file.txt"
        file=open(fp,"r")
        x_list=[]
        y_list=[]
        while True:
            x=(file.readline()).strip("\n")
            x_list.append(x)
            y=file.readline()
            y_list.append(y)
            #z=file.readline()
        print(x_list)
        print(y_list)

b=book()
b.input()

The first three lines of the text file have the number of books, title, and price. After retrieving the values in variables I have to find the cost in method of the class book

A: "from linecache import getline" allows you to get specified lines according to indexs
official docs about it:https://docs.python.org/3/library/linecache.html


text:
Q: ORA-19202: Error occurred in XML processing LPX-00651: VM Stack overflow in APEX_JSON.WRITE() I am trying to use new APEX JSON APIs in my code and when I try to generate JSON with large data and nesting, I am getting error as stated in my question. I have tried following code
SET SERVEROUTPUT ON
DECLARE
   l_cursor SYS_REFCURSOR;
BEGIN

  OPEN l_cursor FOR
    SELECT K.KB_ID "KB_ID",
           K.TITLE "TITLE",
           K.CONTENT "CONTENT",
           K.KEYWORDS "KEYWORDS",
           CURSOR(SELECT F.FILE_ID AS "FILE_ID",
                         F.FILE_NAME AS "FILE_NAME",
                         F.FILE_URL AS "FILE_URL"
                  FROM MY_FILES F
                  WHERE F.TYPE_PK = K.KB_ID AND F.TYPE='ITV_KB') AS "Files"
    FROM ITV_KB_ML_V K
    WHERE K.ENABLED = 1;

 APEX_JSON.initialize_clob_output;

 APEX_JSON.open_object;
 APEX_JSON.write('KNOWLEDGE_DATA', l_cursor);
 APEX_JSON.close_object;

 DBMS_OUTPUT.put_line(APEX_JSON.get_clob_output);
 APEX_JSON.free_output;
END;

I am getting error at APEX_JSON.write('KNOWLEDGE_DATA',l_cursor) and my CONTENT column has large data, if I comment CONTENT then it works fine. Please suggest what I can use to generate JSON with large data in ORACLE APEX.


text:
Q: How to create a linux user where sudo promps for the root password and not current user I created a new user with adduser but when I tried to sudo from his account I got xxxx * is not in the sudoers file. This incident will be reported..
So I started tampering with the visudo command...
I get that root account has the following config:
root    ALL=(ALL:ALL) ALL

But I don't want to duplicate this for my new user...

I want my user xxxx to NOT have root access, except when using sudo.
When using sudo I want the xxxx user to be prompt for the root password and not his own password !!
Thx

Using debian 10
VM, ssh only

A:
I want my user xxxx to NOT have root access, except when using sudo.

This is actually the normal state for regular users: you don't have to do anything, other than configure sudo to specify which commands to allow.
root    ALL=(ALL:ALL) ALL

This line exists just to allow the use of sudo if you are already switched to the root user. The important line that grants permissions to non-root users is this one:
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

(In some Linux distributions, the first regular user generated during the OS installation may become a member of the sudo group and thus have root access enabled for them automatically. This is the exception, not a default for all users.)
The basic form of the permission specification in the sudoers file is
<who>  <where>=(<as_who>) <what>

*

*<who> specifies which user(s) get to use this entry. It can be a user, a group (prefixed with a % sign), or a previously-defined User_Alias (basically a shorthand for a long list of users and/or groups) and a few other things.

*<where> can be a hostname: it restricts this entry to a particular system. It might be useful in an enterprise environment where you slap a centrally-managed standard sudoers file on all hosts, but often this is specified as ALL to avoid problems in case hostname resolution is not working or the system is misconfigured.

*(<as_who>) defines the user account(s) the commands can be run as. The default is root, but you could also restrict an user to be able to run commands with sudo on some specific non-root application account only, for example.

*<what> is the command (or commands, separated with commas) to allow.
There are also various tags and options, but the above is the important part of the sudoers file in a nutshell.

When using sudo I want the xxxx user to be prompt for the root password and not his own password

This is possible, and quite easy to do. If you add these lines to your sudoers file:
Defaults:xxxx rootpw,timestamp_timeout=0
xxxx    ALL=(ALL:ALL) ALL

then for user xxxx (and only for them), the sudo command will ask for a root password - and it will ask every time the sudo command is used, instead of the default behavior of allowing up to 15 minutes of time for using the sudo command without asking for the password again.
This is important if you plan to be monitoring the user and typing the root password yourself when needed by this user - if you miss the timestamp_timeout=0 option, the user may first ask you to enter the root password for some legitimate action, then make up some distraction for you within the next 15 minutes, and during that time they will be able to use sudo for anything they want.
But note that if you tell your user the root password, they will be able to use it with the su command also, unless you apply non-default restrictions to su. The classic (and usually the only) way to restrict su is to require the user to be a member of a particular group, or else they won't be able to use su at all. To apply this restriction, edit /etc/pam.d/su and find this part near the beginning:
# Uncomment this to force users to be a member of group root
# before they can use `su'. You can also add "group=foo"
# to the end of this line if you want to use a group other
# than the default "root" (but this may have side effect of
# denying "root" user, unless she's a member of "foo" or explicitly
# permitted earlier by e.g. "sufficient pam_rootok.so").
# (Replaces the `SU_WHEEL_ONLY' option from login.defs)
# auth       required   pam_wheel.so

Just remove the # from the beginning of the last line and the su command will be usable by the members of the root group only.


text:
Q: User defined derived type IO file compile on gfortran I am trying to compile the sample code provided in example 1 of this link using GNU Fortran. I have placed the source code in a .f95 file called "Test" and tried to compile it in cmd using
gfortran test.95
This throws quite a few errors as shown below:
      GENERIC :: READ (FORMATTED) => UDIO_READ_ARRAY
                    1
Error: Expected '=>' at (1)
test.f95:12:17:

   INTERFACE WRITE(FORMATTED)
                 1
Error: Syntax error: Trailing garbage in INTERFACE statement at (1)
test.f95:13:21:

      MODULE PROCEDURE UDIO_WRITE_ARRAY
                     1
Error: MODULE PROCEDURE at (1) must be in a generic module interface
test.f95:14:5:

   END INTERFACE
     1
Error: Expecting END MODULE statement at (1)
test.f95:51:6:

   USE TYPES
      1
Fatal Error: Can't open module file 'types.mod' for reading at (1): No such file
 or directory
compilation terminated.

Why is this happening? How can I fix it?

A: Why is this happening?
Because gfortran 5.1.0 dosn't support derived type input/output (DTIO).
How can I fix it?
Download MinGW-w64 version>=7.1.0
https://sourceforge.net/projects/mingw-w64/files .


text:
Q: Route id not being picked up in Asp.Net Core MVC controller action Given the following HTML:

        EnerBurn

produces this URL:

https://localhost:44356/Product/Products/0

But in this controller action, the selected variable is always 0.
Why isn't the controller action picking up the id from the URL route?
This is the HttpGet controller action:
public IActionResult Products(int selected)
{
    var pivm = new ProductInfoViewModel {SelectedId = selected};
    pivm= UpdateModelFromSelectedId(pivm);
    return View(pivm);
}

A: With your current action definition, MVC tries to populate the selected value from query params (this is by default) and fails as you pass it as part of URL.
And so as you want this to be part of URL, you need to specify this explicitly as part of routing:

*

*Via route attribute:
[Route("Product/Products/{selected}")]
public IActionResult Products(int selected)

*Or if you use the convention routing
routes.MapRoute("products", {controller=Product}/{action=Products}/{selected?}");

A: Change the code and put id instead of selected:
public IActionResult Products(int id)
{
    var pivm = new ProductInfoViewModel {SelectedId = id};
    pivm= UpdateModelFromSelectedId(pivm);
    return View(pivm);
}

A: Why use "int selected"? It requires custom routing.
Use "string id" and MVC will handle it for you by default.
If you need the input parameter to be an int, then convert it to an int (in try catch?).
//in: id represents selected index
public IActionResult Products(string id)
{
int selected = Convert.ToUInt32(id);
//do work....
}


text:
Q: How to manually install Google Data Python library? I don't know how to install Google Data Python library, and I'm not a programmer either. I don't understand the Google Developers guide and on YouTube, the guy doesn't show how he install it (scripts maybe) on the python.
I tried Getting Started with the Google Data Python Library, but I'm only at step 2.
I'm stuck at "Installing the Google Data Library":

Download the Google Data Python library if you haven't done so. Look for the latest version on the Python project's downloads page.
After downloading the library, unpack it using unzip or tar zxvf depending on the type of download you chose.
Now you are ready to install the library modules, so that they can be imported into Python. There are several ways you can do this:

*

*If you have the ability to install packages for all users to access, you can run ./setup.py install from the unpacked archive's main directory.

*If you want to install these modules for use in your home directory, you can run ./setup.py install --home=<your home directory>

A: If you're using a Mac, download the Google Data Python library, then double click the file in your Downloads directory, which will automatically unpack it, regardless of whether you downloaded the .zip or .tar.gz version of the file.
Next, open Terminal, cd to the directory where the library has been installed (e.g.: cd ~/Downloads/gdata-2.0.18), and try running the commands they mention.
If the second paragraph doesn't make any sense to you, go here: http://cli.learncodethehardway.org/book/ and all will become clear. Don't worry, it's not book-length.


text:
Q: UIScrollView Scrollable Content Size Ambiguity when using Aspect Ratio I want to set a square scrollView in my nib file.
So for this reason I have pinned my scrollview to the top, left and right of the superview.
Then I'm setting the aspect ratio of the scrollView to 1:1.
However this triggers the error in IB about Ambiguity in contest size height and width of the scroll view.
Is this a bug, or am I understanding this wrong?

A: Well, this is ambiguous :-)
For example, what do you expect from your scroll view when its superview's height changes (let's say it gets taller)?
If your answer is "to get taller as well", you don't need the 1:1 constraint.
Or, if it's "to keep the original height", the bottom space constraint is extra.
Same exercise for the width and left/right constraints.
UPD: Looks like the warning has disappeared in the new Xcode (6A1052d); trying to check that in comments below.

A: I finally figured out the issue.
It was a subview that I had placed inside the UIScrollView that caused this (a UIActivityIndicator). Looks like centering an element inside an element that has with or height set based on Aspect Ratio is considered by the Interface builder ambiguous, which though is wrong.
I will file in a report for this.


text:
Q: Laravel 8.x - URI in custom success response In an application I'm building, I return the user to a program list page, after they have edited an academic Program.
I'm using the return redirect()->with() methods to return to the list page, however I am trying to append an in-page link to the success message, so the user can jump to the edited program's thumbnail, after clicking on that message.
I have tried multiple combinations but this is as far as I've gotten:
return redirect('/education/programs')->with('success', "The changes to the ".  `<a href="#program-.$program->id.">`.'program'.`</a>`. " have been saved.");

This unfortunatelly results to a plain text "The changes to the program have been saved." message, with no clickable uri whatsoever.
The reason why I do not append the uri to the redirect() method, is because I want the message to display on the top of the page, and give the user the option to jump to it only if they choose to.
Any idea how I could make it work in this form ? Or perhaps some other suggestions ? Thank you in advance!


text:
Q: Should flags in POSIX-style operating systems be prefixed by "no" or "no_"? When you have a boolean option and a flag for setting it to false by prefixing "no" to the name, should it be "no" or "no_"? What's most commonly used or better style? For example:
--no_foo

or
--nofoo

A: Neither. Use no- i.e. --no-foo.


text:
Q: how to extract the 2nd number in a string I want to extract only the second number (in order) from a string.
string = "vancomycin 1G IV 3 times a day over 1 hour."

desired output = 3

A: A posssible solution, but not the prettiest one
str_extract_all(string, "\\d+")[[1]][2]


text:
Q: php - get sum of clicks for past 7 days I have a table xeon_users_rented, with: clicks0, clicks1, clicks2, clicks3, clicks4, clicks5, clicks6
Each day, clicks0 will increase, and every day at midnight, a cronjob will run, making clicks0 = clicks1 (setting todays clicks, to yesterday clicks), and then set clicks0 to zero.
What I am trying to achieve is I want to make a graph, that shows the sum of clicks0, clicks1 etc., where clicks0 is todays date.
I have the query below:
$data = array();
for ($x = 0; $x <= 6; $x++) {
    $date = date("Y/m/d", time() - ($x * 86400));
    $queryE = $dbh->prepare("SELECT SUM(clicks$x) FROM xeon_users_rented WHERE user_by=:username");
    $queryE->bindParam(":username", $userdata['username']);
    $queryE->execute();
    $row = $queryE->fetch(PDO::FETCH_ASSOC);
    $dates[] = date("Y/m/d", time() - ($x * 86400));
    $data[] = ($row['clicks'.$x.''] > 0 ? $row['clicks'.$x.''] : 0);
}
$days = array('Today');
for ($i = 0; $i < 6; $i++) {
    $days[$i] = date('d-m', strtotime('-'.($i + 0).' day'));
}

The $days is working perfectly - it will print out today, and the last couple of days.
The $data is not working. It is just printing out:
0,0,0,0,0,0,0

Can someone please help me out here.

A: The column from your SUM isn't going to be named clicks$x.  It will be named something like SUM(clicks1).
Provide an explicit name in the SQL, like
SELECT SUM(clicks$x) as clickSum ...

Then reference it in row as
$row['clickSum']


text:
Q: Чем отличаются два обращения к элементу? В чем отличие в JS между document.getElementById("element") и
$('#element')?
И первое и второе выбирают элемент по id

A: *

*Условия использования: второй вариант требует подключения библиотеки

*Передаваемые параметры: в обе функции передаётся строка, однако в getElementById() передаётся сам ID, а в jQuery() (она же $()) - #ID (так как она работает не только с ID элементов)

*Возвращаемое значение: getElementById() возвращает Element или null, jQuery() - jQuery объект

*Производительность: функция jQuery()работает не только с ID элементов, поэтому ей нужно время на анализ переданных параметров. И в итоге она всё равно вызовет внутри себя getElementById(). Так что первый вариант работает быстрее

A: Ничем не отличаются. Первый написан на JS, а второй тоже на JS только с использованием библиотеки jQuery (поэтому в этом случая требуется ее подключить).


text:
Q: threading - передать каждому потоку свой аргумент Я хочу выполнить авторизацию в Google с разных аккаунтов в каждом из потоков. На данный момент могу просто запустить n потоков и авторизироваться в гугле под одним аккаунтом.
Подскажите, пожалуйста, как правильно передать произвольное кол-во аргументов в thread, чтобы потом каждый поток взял по 1 уникальному аргументу (там будет связка login:password) и в будущем авторизовался в гугл с полученными значениями?
import threading

from selenium import webdriver

# Не понимаю, как воспользоваться теми аргументами,
# Что передам в args,
# Так, что бы каждый поток взял по одному из них
def main():
    print(threading.current_thread)
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    options.add_experimental_option("excludeSwitches", ['enable-automation'])
    driver = webdriver.Chrome(options=options)
    start(driver)

#--
#-- Пропуск всей логики работы программы
#-- def start(driver):
#--     pass
#--

# Запускаю потоки
if __name__ == '__main__':
    threads = []
    for i in range(n):
        # В args планируется передать login:password в N-ом кол-ве штук
        t = threading.Thread(target=main)
        threads.append(t)
        t.start()

A: Зачем передавать произвольное количество аргументов, когда можно каждому треду передать свой аргумент?
import argparse

def main(loginpassword):
    print(loginpassword)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Логины пароли.')
    parser.add_argument('passwords', metavar='login:password', type=str, nargs='+', help='Логины пароли списком')
    args = parser.parse_args()

    for lp in args.passwords:
        t = threading.Thread(target=main, args=(lp, ))
        ....

Но если тред должен сам выбрать один пароль из списка:
import queue

def main(q):
    lp = q.get()

q = queue.Queue()
for lp in args:
    q.put(lp)

for i in range(5):
    t = threading.Thread(target=main, args=(q,))

Положим пароли в очередь по одному и уже в треде из этой очереди их выгребаем.

A: import multiprocessing.pool
processes = multiprocessing.cpu_count()
login_passw = [(1, 2), (3, 4), (5, 6), (1, 2), (3, 4), (5, 6), (1, 2), (3, 4), (5, 6), ]

ThreadPool
def main(log_pasw):
    return sum(log_pasw)

if __name__ == '__main__':
    with multiprocessing.pool.ThreadPool(processes=processes) as p:
        for s in p.imap_unordered(main, login_passw):
            print(s)

ThreadPoolExecutor
import concurrent.futures

def main(log_pasw):
    return sum(log_pasw)

if __name__ == '__main__':
    with concurrent.futures.ThreadPoolExecutor(max_workers=processes) as p:
        fut = [p.submit(main, a) for a in login_passw]
        for f in concurrent.futures.as_completed(fut):
            print(f.result())

threading.Thread
import queue, threading, contextlib

def main(qi, qo):
    with contextlib.suppress(queue.Empty):
        while True:
            qo.put(sum(qi.get_nowait()))

if __name__ == '__main__':
    qin, qout = queue.Queue(), queue.Queue()
    [qin.put(lp) for lp in login_passw]
    [threading.Thread(target=main, args=[qin, qout]).start() for _ in range(processes)]
    for e, s in enumerate(iter(qout.get, None), start=1):
        print(s)
        if e == len(login_passw):
            break


text:
Q: OpenLayers: Vector Layer not rendering in certain browsers I'm new to openLayers and trying to add a GML overlay:
http://the506.com/elxnmaps/2011/ftontest.html
The file renders perfectly as is in Chrome and Safari, but doesn't render at all in Firefox or IE; only the underlying Google layers. It's in the same directory as the HTML page. Nothing I try seems to work. Here's the code in question:
    function init(){
          map = new OpenLayers.Map('map', {
          projection: 'EPSG:3857',
          layers: [(Google layers)],
          center: new OpenLayers.LonLat(-66.6, 46.0).transform('EPSG:4326', 'EPSG:3857'),
          zoom: 10
});
    map.addControl(new OpenLayers.Control.LayerSwitcher());

    (styling rules)

var kmllayer = new OpenLayers.Layer.Vector("Poll-by-Poll Data", {
            protocol: new OpenLayers.Protocol.HTTP({
                url: './13003test.gml',
                format: new OpenLayers.Format.GML({extractAttributes: true})
            }),
            strategies: [new OpenLayers.Strategy.Fixed()],
    visibility: true,
    styleMap: new OpenLayers.StyleMap(style),
    projection: new OpenLayers.Projection('EPSG:4326')
        });

    map.addLayer(kmllayer);

        selectControl = new OpenLayers.Control.SelectFeature(kmllayer,
            {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});

        map.addControl(selectControl);
        selectControl.activate()
    }

What could be causing the problem, and can it be fixed?

A: When I test, it looks like your poll-by-poll layer loads successfully in Chrome/Firefox.  However, there's a syntax error on line 8 of your stylemap.js:
var main = new OpenLayers.Style(
{
    fillOpacity: 0.55,
    strokeWidth: 0.4,
    strokeOpacity: 0.9,
    pointRadius: 2,
    strokeColor: "#aaaaaa", // no comma here
}...

Remove the comma and try to reload in IE.


text:
Q: Accessing Parent of Inline Form Sets in template? I am wondering how to access the parent of the inline form set in Django. Here is what I am currently doing:
views.py
def upload(request):
    [Code Ommitted]
    formSet = inlineformset_factory(Tombstone, Tank, form = TombstoneForm)
        form = formSet(instance=t)
        return render(request, 'edit_form2.html', {'form': form})

In this instance I want to access the Tombstone object in my template.
Edit: I want to access the form element associated with each field in the Tombstone object.

A: You can use formset's instance attribute:
{{ form.instance.id }}


text:
Q: Python Matplotlib Pie chart merge two slices with identical titles together I'm doing a matplotlib project with pie charts and would like to merge two slices in a pie chart with identical titles together to form one big slice with the same title.

However, matplotlib just leaves the slices seperated, even though they have the same title.
May I know how I can do that? Thanks.
And yes, some code.
from matplotlib import pyplot as plt
list0 = [1,2,3]
list1 = ["apple", "banana", "banana"]
plt.pie(list0, labels = list1)
plt.show()

A: Preprocess your titles and values then draw the chart:
We loop through the list0 (the values) and list1 (the titles) together, and make each of the titles as the key of the dictionary then add the corresponding value from the list0 to that key. So the values of the titles with same name will be added to one and the same {key: val} in the dictionary.
When all the items are examined, we return the list of the keys of the dictionary as the titles and the corresponding values as the values of the charts for each title.
from matplotlib import pyplot as plt

def merge_slices(list0, list1):
    from collections import defaultdict
    dict_slices = defaultdict(lambda: 0)
    for val, title in zip(list0, list1):
        dict_slices[title] += val
    return list(dict_slices.values()), list(dict_slices.keys())

if __name__ == "__main__":
    list0 = [1,2,3]
    list1 = ["apple", "banana", "banana"]
    merged_list0, merged_list1 = merge_slices(list0 ,list1)
    plt.pie(merged_list0, labels = merged_list1)
    plt.show()

Output:

defaultdict will create a key and set a default value for the keys which are not in the dictionary. In the snippet above, we set it in a way that, it will set 0 for the key which wasn't in the dictionary before.

A: this can do,
from matplotlib import pyplot as plt

list0 = [1, 2, 3]
list1 = ["apple", "banana", "banana"]

sourceDict = {}
for i, j in zip(list1, list0):
    if not i in sourceDict:
        sourceDict.update({i: j})
    else:
        sourceDict[i] += j

plt.pie(sourceDict.values(), labels=sourceDict.keys())
plt.show()

Output:

A: In my opinion, it would be fastest to add code that aggregates values with the same title.
from matplotlib import pyplot as plt
list0 = [1,2,3]
list1 = ["apple", "banana", "banana"]

m = {k:sum([list0[i] for i, l in enumerate(list1) if l == k ]) for k in set(list1)}

plt.pie(m.values(), labels = m.keys())
plt.show()


text:
Q: Programmatically disconnect network connectivity Is there a way to programmatically and temporarily disconnect network connectivity in .NET 4.0?
I know I can get the current network connectivity status by doing this...
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()

but for testing purposes I would like test my application's behavior when it loses network connectivity (without physically unplugging the network cable).
Thanks,
Chris.

A: You could do it with WMI.  Here's one we use for disabling the physical adapter to test these types of scenarios.
using System.Management;
using System.Linq;

namespace DisableNIC
{
    internal static class Program
    {
        private static void Main()
        {
            var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
                                            "WHERE NetConnectionId != null " +
                                              "AND Manufacturer != 'Microsoft' ");
            using (var searcher = new ManagementObjectSearcher(wmiQuery))
            {
                foreach (var item in searcher.Get().OfType<ManagementObject>())
                {
                    if ((string) item["NetConnectionId"] != "Local Area Connection")
                        continue;

                    using (item)
                    {
                        item.InvokeMethod("Disable", null);
                    }
                }
            }
        }
    }
}

You didn't indicate the OS, but this works in Windows 7 and Windows 8.
Note that you will need to be an administrator for this to function.

A: if you use 'Managed Wifi API' you can simply delete the profile. That worked for me.
WlanClient client = new WlanClient();

WlanClient.WlanInterface m_WlanInterface = client.Interfaces.Where(i => i.InterfaceDescription.Contains(InterfaceIdentifierString)).First();
m_WlanInterface.DeleteProfile(ConnectionProfileString);

If you need to reconnect to that network, be sure to save the xml profile:
string xmlString = m_WlanInterface.GetProfileXml(ConnectionProfileString)

Then you can reuse it
 m_WlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, xmlString, true);
 m_WlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, ConnectionProfileString);


text:
Q: How to use locally produced NuGet in a docker image? I have a use case where I have a .nupkg file already generated locally on my machine.
I want to use this local nuget file in the docker image. Below is how existing docker file looks like -
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /app

RUN mkdir -p /nuget
ADD nuget /nuget/

COPY src/*.csproj .
RUN dotnet restore

COPY src/ .
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
WORKDIR /app
COPY --from=build /app/out ./
ENTRYPOINT ["dotnet", "EdgeService.dll"]

So in the RUN dotnet restore step it fetches a particular nuget package from nuget.org repository and builds the image. I want a mechanism by which it could use a .nupkg file which I have on my local machine instead of it fetching from nuget server.
Is there some change I could do in the .csproj file or the docker file to make sure that it happens?
Is it necessary to setup a local nuget server in this case?

A: Yes you need a nuget server running somewhere. Local is great, until you want to set up CI and then you need a hosted one. I used a hosted docker container with a nuget server in it before later migrating to GitHub packages.
After a while of running this set up however I found rebuilding packages for every change a pain so I rearchiteced my solution to not need private NuGet packages at all.

A: Below are the changes I did to get it working -
Dockerfile changes -
RUN mkdir -p /nuget
ADD Nuget /tmp/Nuget

COPY src/*.csproj .
RUN dotnet restore

Changes in the .csproj file -
<RestoreSources>$(RestoreSources);https://api.nuget.org/v3/index.json;/tmp/Nuget</RestoreSources>

And in the Nuget folder I copied the .nupkg file which I wanted to be referenced by the docker image.


text:
Q: How to adjust a fixed height parent div base on its child height? I have a parent div with a greater fixed height and a child div with a lesser height. What I want to know if it is possible when I insert the child div, can the parent div adjust to the child div height to 200px.

.parent {
    position: relative;
    height: 400px auto;
}

.child {
    height: 200px;
}

A: Just assign height auto to the parent div. It will automatically take the height of the child div.  And height: 400px auto won't work as it is invalid css syntax.
.parent {
    position: relative;
    height: auto;
}

.child {
    height: 200px;
}

A: Technically, this is possible using the :empty pseudo-class BUT current implemenation requires that there be no contents or whitespace in the .parent element.
:empty @ MDN
Then we can define a fixed height on the parent and switch this to auto if the parent has contents.
Like so:

.parent {
  width: 50%;
  height: 100px;
  margin: 1em auto;
  border: 2px solid red;
  background: orange;
}

.parent:not(:empty) {
  height: auto;
  background: pink;
}

.child {
  height: 50px;
}

A: Just set the height of parent div to 'auto'

.parent {
position: relative;
height: auto;
}


text:
Q: Simplification of rational expressions I'm struggling with getting maxima to simplify expressions in the way that I want them.
rhs(solve(a*x-3=b*y,x)[1]);

returns
(b*y+3)/3

However, I'm wanting to display the result to students and so I want the output to be
(b*y/3) + 1

Is there some simplification that I can do to a rational expression in this form to get the output I want?

A: You can undo the effect of ratsimp in this case by dividing each term in the numerator by the denominator. Here is a simple-minded implementation:
(%i1) unratsimp (e) :=
          block ([foo, bar],
                 [foo, bar]: [num(e), denom(e)],
                 map (lambda ([foo1], foo1/bar), expand (foo))) $
(%i2) 1 + a/b + c*d/3 - %pi*x/y;
                        %pi x    c d   a
(%o2)                (- -----) + --- + - + 1
                          y       3    b
(%i3) ratsimp(%);
                (b c d + 3 b + 3 a) y - 3 %pi b x
(%o3)           ---------------------------------
                              3 b y
(%i4) unratsimp(%);
                        %pi x    c d   a
(%o4)                (- -----) + --- + - + 1
                          y       3    b
(%i5) unratsimp((b*y + 3)/3);
                             b y
(%o5)                        --- + 1
                              3

I don't know how general that is; it's just the first thing I tried, but maybe it's enough for your purpose. I don't know a built-in function for this.
The results %o4 and %o5 are maybe not exactly as a human would write them. Convincing Maxima to display the terms in + and * expressions in a different way is not straightforward -- Maxima has strong ideas about how to order terms in an expression which are assumed throughout the code. But I think that others have asked questions, which might have answers, about displaying expressions -- you might search Stackoverflow if you are are interested.

A: The command you can use here is multthru:
(%i1) e1:(b*y+3)/3;
(%o1) (b*y+3)/3
(%i2) multthru(e1);
(%o2) (b*y)/3+1

In this case also the following will work
(%i3) distrib(e1);
(%o3) (b*y)/3+1
(%i4) expand(e1);
(%o4) (b*y)/3+1


text:
Q: Should constructor injection have parameters for the records to be processed? Hi we're trying to loosely couple our codebase and is implementing dependency injection via Force-DI. It's my first time working with dependency injection and would like some clarity on how to approach the scenario below. I'd like to know if I should be passing records on the constructor.
Lets say we have an interface and an implementation as below
public interface IDiscount {
    Decimal calculateDiscount(Id orderlineId);
}

public class DiscountService implements IDiscount{

    public Decimal calculateDiscount(){
        //some calculations
    }
}

Can you tell me which of the two below implementation would be appropriate? I'm having this issue now since most of our classes, the records are being passed on the constructor.
public class OrderLineCalculator1{
    private IDiscount discountService;

    public OrderLineCalculator1(IDiscount discountService){
        this.discountService = discountService;
    }

    public decimal process(Id orderlineId) {
        return discountService.calculateDiscount(orderlineId);
    }
}

public class OrderLineCalculator2{
    private IDiscount discountService;
    Id recordId

    public OrderLineCalculator2(IDiscount discountService, Id recordId){
        this.discountService = discountService;
        this.recordId = recordId;
    }

    public decimal process() {
        return discountService.calculateDiscount(orderlineId);
    }
}

This is how I imagine it would look like on the triggerhandler. 2nd implementation looks tricky as somehow I would need to pass the records on the di module. Is this even possible?
public class OrderLineItemTriggerHandler {
    //some logic
    //implementation 1
    OrderLineCalculator1 oliCalculator = di_Injector.Org.getInstance('Some Module Binding');
    orderlineItem.Discount__c = oliCalculator1.process(orderLineItem.Id);

    //implementation 2
    OrderLineCalculator2 oliCalculator2 = di_Injector.Org.getInstance('Some Module Binding'); //would be tricky to pass record id through the module
    orderlineItem.Discount__c = oliCalculator2.process();
}


text:
Q: Check if the hands of an analog clock are positioned correctely I'm creating an analog clock input method that users can use to pick a time. Users can click on the inner circle to set the short hand (hour) and can click on the outer circle to set the long hand (minute).

The problem is that users are free to click any point on the clock and therefor can pick an invalid position of the hands. Is there any way (algoritm) to detect this?
window.addEvent('domready', function()
{
  var handLong = [10, 20, 30, 40, 50, 60, 70, 80];
  var handShort = [10, 20, 30, 40, 50];

  injectHands('clock', handShort, handLong);

  $('clock').addEvent('click', function(e)
  {
    var x = correctX(e.page.x - e.target.getPosition().x, true);
    var y = correctY(e.page.y - e.target.getPosition().y, true);

    var angle = calculateAngle(x, y);

    // grote wijzer positioneren
    if (insideOuter(x, y))
    {
      moveHand(handLong, 'Long', angle);
    }
    // kleine wijzer positioneren
    else if (insideInner(x, y))
    {
      moveHand(handShort, 'Short', angle);
    }
  });
});

// Valt punt (x, y) binnen een cirkel met middenpunt (x, y) en radius r
function insideCircle(pointX, pointY, circleX, circleY, radius)
{
  dX = pointX - circleX;
  dY = pointY - circleY;

  return ((dX * dX) + (dY * dY)) <= (radius * radius);
}

// Valt punt (x, y) (enkel) binnen de buitenste cirkel (grote wijzer)
function insideOuter(pointX, pointY)
{
  return !insideInner(pointX, pointY) && insideCircle(pointX, pointY, 0, 0, 100);
}

// Valt punt (x, y) (enkel) binnen de binnenste cirkel (grote wijzer)
function insideInner(pointX, pointY)
{
  return insideCircle(pointX, pointY, 0, 0, 50);
}

// corrigeer x as (100 => 0) (0 => 100)
function correctX(x, nn)
{
  if (nn)
  {
    return x - 100;
  }
  return x + 100;
}

// corrigeer y as (100 => 0) (0 => 100)
function correctY(y, nn)
{
  if (nn)
  {
    return -y + 100;
  }
  return Math.abs(y - 100);
}

function calculateAngle(x, y)
{
  if ((x >= 0) && (y >= 0))
  {
    return Math.atan(x / y) * (180 / Math.PI);
  }
  else if (((x >= 0) && (y < 0)) || ((x < 0) && (y < 0)))
  {
    return 180 + Math.atan(x / y) * (180 / Math.PI);
  }
  else if ((x < 0) && (y >= 0))
  {
    return 360 - Math.abs(Math.atan(x / y) * (180/ Math.PI));
  }
}

function roundAngleByMinute(angle)
{
}

function calculateX(angle, hypotenuse)
{
  return Math.sin((Math.PI / 180) * angle) * hypotenuse;
}

function calculateY(angle, hypotenuse)
{
  return Math.cos((Math.PI / 180) * angle) * hypotenuse;
}

function injectHands(div, handShort, handLong)
{
  for (var i = 0; i < handShort.length; i++)
  {
    $(div).grab(new Element('img', {src: 'images/red_8x8.png', class: 'hands handShort', id: 'handShort-' + handShort[i]}));
  }
  for (var i = 0; i < handLong.length; i++)
  {
    $(div).grab(new Element('img', {src: 'images/blue_8x8.png', class: 'hands handLong', id: 'handLong-' + handLong[i]}));
  }

  $(div).grab(new Element('img', {src: 'images/black_8x8.png', class: 'hands', id: 'hand-center'}));

  $$('img.hands').hide();
  $('hand-center').show();
}

function moveHand(hand, whichHand, angle)
{
  for (var i = 0; i < hand.length; i++)
  {
    var hypotenuse = hand[i];
    var x = calculateX(angle, hypotenuse) - 5;
    var y = calculateY(angle, hypotenuse) + 5;
    var left = correctX(x);
    var top = correctY(y);

    $('hand' + whichHand + '-' + hypotenuse).set('styles', {'left': left + 'px', 'top': top + 'px'});
  }
  $$('img.hand' + whichHand).show();
}

A: When you set the hour hand, you can figure out the minute hand. trigonometry to the rescue!
When you set the minute hand, assume the minute hand forwards to the selected position and adjust hour hand accordingly.
The minute hand shows a function of the hour hands angle, much like the modulo operator works...
The other way round works too: Given a minute hand angle, there are only twelve possible hour hand angles. Just choose the one closest to the current hour hand angle...

A: Just round the position of the hour hand to the nearest hour and add the corresponding offset for the current minute hand position?


text:
Q: How to run tests for a node app deployed on Cloud Run with Cloud Build I have a nodejs  API running on Google cloud Run and am using Cloud Build for continuous Deployment.
I would need to run tests so that in case of errors found, cloud Build does not deploy the image to cloud Run. How can I implement this either in Dockerfile or using anyother way.

A: You have 2 solutions

*

*Either you start your API in background and run tests on it.

*Or, if you want to test the container, deploy the container on Cloud Run, in a staging instance and test it. If the tests are ok, continue and deploy the container on the correct service.

You can't run a container inside Cloud Build (Docker in Docker aren'r permitted. In fact, you can run the container, but the port forwarding is forbidden, so you can test your API with the container started!)


text:
Q: Socket Error while REST Call in via method POST not working We have below curl commands which run perfect.
curl -x http://x.x.x.x:9999  -X POST -F token=aaa -F "ref=prod_call" -F variables[name]="No" -F variables[CR_Number]="" -F variables[HOSTS_FILE]="lil.ini"  https://gitlab.com/api/v4/projects/1111/trigger/pipeline
Now same thing I implemented in node js and unfortunately it is not working
function callPipeline(){
    console.log("The host we are going to execute here")
    console.log("The command  are going to execute here")

    var formdata = new FormData();
    formdata.append("token", "aaa");
    formdata.append("ref", "prod_call");
    formdata.append("variables[name]", "No");
    formdata.append("variables[CR_Number]", "");
    formdata.append("variables[HOSTS_FILE]", "lil.ini");

 var options = {
  method: 'POST',
  host: "x.x.x.x", //proxy server
  port: 9999,
  path: "https://gitlab.com/api/v4/projects/1111/trigger/pipeline",
  body: formdata,
};

return new Promise((resolve, reject) => {

  http.request(options, function(res, err) {
    console.log(res);

    console.log(err);
    //res.pipe(process.stdout);
    resolve(res.toString() + "---err---" +err.toString())

  });

})

}

Getting error
node:events:498
      throw er; // Unhandled 'error' event
      ^

Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at Socket.socketOnEnd (node:_http_client:466:23)
    at Socket.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketOnEnd (node:_http_client:466:9)
    at Socket.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ECONNRESET'
}


text:
Q: Plotting frequency distribution/histogram with frequency table I'm familiar with the matplotlib histogram reference:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist
However, I don't actually have the original series/data to pass into the plot. I have only the summary statistics in a DataFrame. Example:
df
lower  upper  occurrences  frequency
0.0    0.5    17           .111
0.5    0.1    65           .426
0.1    1.5    147          .963
1.5    2.0    210          1.376
.
.
.

A: You don't want to calculate a histogram here, because you already have the histogrammed data. Therefore you may simply plot a bar chart.
fig, ax = plt.subplots()
ax.bar(df.lower, df.occurences, width=df.upper-df.lower, ec="k", align="edge")


text:
Q: How do I listen for Google APIs Push notifications? I am using Google Drive api and I would like for my UWP app to be notified of changes made to a user's files. Should there be some sort of event that I should be listening for which basically says, " changes have occurred to your files"?
I just registered for a domain that will be used as part of the set up process since I guess it is a requirement. But googles documentation does nothing to explain the steps required to actually LISTEN out for changes.
Googles documentation: Here

A: The Drive API provides push notifications that let you watch for changes to resources. You can use this feature to improve the performance of your application. It allows you to eliminate the extra network and compute costs involved with polling resources to determine if they have changed. Whenever a watched resource changes, the Drive API notifies your application.
Push notifications will be sent to a central location on your server. when you register the domain of your receiving URL.   For example, if you plan to use https://exampe.com/notifications as your receiving URL, you need to register https://exampe.com.
Once you have set up the domain where you would like the push notifications sent to its simply a matter of setting up a watch on the file in question.
You need to set up watch and then you will start recieving push notifications on changes of those files

POST https://www.googleapis.com/drive/v3/files/fileId/watch

request body
{
  "kind": "api#channel",
  "id": string,
  "resourceId": string,
  "resourceUri": string,
  "token": string,
  "expiration": long,
  "type": string,
  "address": string,
  "payload": boolean,
  "params": {
    (key): string
  }
}


text:
Q: How to Convert Hexe to ImageView in Android String photoByte2 = "FFD8FFE000104A46494600010101000000000000FFE2021C4943435...."

this is not whole hex code;

Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte2.getBytes(), 0,photoByte2.length());
        img.setImageBitmap(bitmap);

i want convert above Base16 or Hex code to Image View in my android Project?but i dont have idea what can i do...

A: First convert your Hex to  array of int (Int[]) and from that u can get bitmap by
bitmap=Bitmap.createBitmap(int[] intarray, int width, int height, Bitmap.Config config)


text:
Q: TypeError: Cannot call method 'get' of undefined I try to make a simple CRUD application on node.js using express.js. I try to connect to DB, but I have an error TypeError: Cannot call method 'get' of undefined. Part of my code:
app.js
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/notepad');

var app = express();

app.get('/users', routes.userlist);

// mongoDB
app.use(function (req, res, next) {
   req.db = db; // this is setting up db property to request
   next();
});

routes/index.js
exports.userlist = function (req, res) {
var db = req.db;
var collection = db.get('usercollection'); // error in this line
collection.find({}, {}, function (e, docs) {
    res.render('userList', {
        "userlist": docs
    });
});
};

I think the instanse of DB is not setted or it's not available in other file. How to solve this?

A: Your app.use should be written before your app.get. The app.get is called first by Express.
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/notepad');

var app = express();

// mongoDB
// Do all your "pre-route" use() functions first
app.use(function (req, res, next) {
   req.locals.db = db; // this is setting up db property to request
   next();
});

app.get('/users', routes.userlist);

In your routes...
var db = req.locals.db; // Instead of req.db

Or even better...
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/notepad');

var app = express();

app.locals.db = db;

app.get('/users', routes.userlist); // Access it using req.locals.db


text:
Q: Wired network connection fails after return from sleep in Ubuntu 20.04 I just upgraded from 18.04 to 20.04. Everything worked fine with 18.04, but after the upgrade every time the PC returns from sleep the wired network connection is gone. I cannot see the connection on the top bar and when looking at the network setup area it is also showing like the hardware is missing. The only way I have found to bring the connection back is to do a restart which works, but is a pain. Any ideas why the upgrade caused this problem and how to fix it short of going back to 18.04?
I have also tried a manual shutdown of the network using..
sudo nmcli networking off
sudo nmcli networking on
This created exactly the same symptoms. The shutdown worked, but the network did not restart using the networking on command. I do have a VPN, but the problem is the same if the VPN is active or not.
Thanks
PS. Gave up waiting for a response and solved the problem by installing a PCI-E ethernet card (A$15). This second ethernet port does not suffer the same issue of failing to return after putting the PC to sleep.

A: I have this problem after upgrading to 21.04, this desktop has wifi as well which means I can limp along for now but the wired lan comes up DISABLED after  resuming from sleep according to lspci -C network.
A diff of the output shows missing attributes after resume but I cant find a reason why this happens or way to turn it back on without a reboot.
Before reboot
*-network
description: Ethernet interface
product: Killer E2400 Gigabit Ethernet Controller
vendor: Qualcomm Atheros
physical id: 0
bus info: pci@0000:04:00.0
logical name: enp4s0
version: 10
serial: b8:85:84:b6:43:a7
size: 1Gbit/s
capacity: 1Gbit/s
width: 64 bits
clock: 33MHz
capabilities: pm pciexpress msi msix bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=alx driverversion=5.11.0-22-generic duplex=full ip=192.168.86.224 latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s
resources: irq:19 memory:ec500000-ec53ffff ioport:d000(size=128)
After Reboot
*-network DISABLED
description: Ethernet interface
product: Killer E2400 Gigabit Ethernet Controller
vendor: Qualcomm Atheros
physical id: 0
bus info: pci@0000:04:00.0
logical name: enp4s0
version: 10
serial: b8:85:84:b6:43:a7
width: 64 bits
clock: 33MHz
capabilities: pm pciexpress msi msix bus_master cap_list ethernet physical
configuration: broadcast=yes driver=alx latency=0 multicast=yes
resources: irq:19 memory:ec500000-ec53ffff ioport:d000(size=128)


text:
Q: gitignore and ruby on rails I'm processing my first app with ruby on rails ! But i've got a problem. When i create my app with rails new app_name, the rails command creates a lot of files, as gitignore. But i can't find this file anywhere ! And i need this file to use 'git add .' after.
So anybody knows where it could be ? I'm stuck because by the way i can't use git status or git commit and i can't add anything to my app, this is really annoying.
I precise that i've installed git.
When I use 'git add.', the command tells me that we 'can't use gitignore as an exclude file'. I don't know what that means.
Is anybody can help me ? :) I'd appreciate that :)
Thanks you !
Justine


text:
Q: My Login page replaced by browser authentication box I'm developing an asp.net web application with user login. It is working fine on development environment.
When user needs to access members only page my login.aspx file displayed but after publishing, the when members only page request browser native login page displayed instead of my login.aspx. Please help me to solve this:

A: Its because you are using windows authentication, and it seems that your testing environment is out of the domain (machine or active directory)


text:
Q: Parse, cloud code beforeDelete Before I'm deleting my user I would like to remove some objects in another class. This works fine in Swift.
class func deleteAnonymousUserListSettings(completetion:(result:Bool, error:NSError!) -> Void){
    var queryListSettings = PFQuery(className: "ListSettings")
    queryListSettings.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
        if let objs = objects as? [PFObject] where error == nil {
            PFObject.deleteAllInBackground(objs, block: { (success, error) -> Void in
                if success{
                    completetion(result: success, error: error)
                }
            })
        }
    }
}

Now I would like to transfer this to cloudCode. It works approximately 1 out of 10 times but I don't know why or when it works and sometimes not.
Parse.Cloud.beforeDelete(Parse.User, function(request, response) {
  var query = new Parse.Query('ListSettings');
  query.find({
  success: function(results) {

      for (var i = 0; i < results.length; i+=1) {
        results[i].destroy();
      }
      response.success(results);
    },
    error: function() {results
      response.error("error");
    }
  });
});

Help, please.

A: Instead of deleting one by one, you can delete all of the object at once and return success if it is successful. You can do this via the below code blocks;
   query.find().then(function (results)
   {
      Parse.Object.destroyAll(results);
      response.success("Success");
    },
    function (error)
    {
      response.success("Error");
    })

Hope this helps.Regards.

A: Here we go, this works for me.
Parse.Cloud.beforeDelete(Parse.User, function(request, response) {
    var query = new Parse.Query('ListSettings');
    query.find().then(function(results) {

      return Parse.Object.destroyAll(results);
    }).then(function() {
      response.success();

    }, function(error) {
      response.error("Error removing ListSettings.");

    });
});