text:
Q: Angular 5 material, fetch mat-options (in autocomplete/select list) from backend server I'm upgrading an app from AngularJS to Angular 5. I figured most things out, but still in a bit of a learning process, and I can't figure out the best way to connect an autocomplete list to the backend. The Material Design website doesn't mention this either.
Here's what the code looks like now:
  <mat-form-field>

    // chips are up here

    <mat-autocomplete (optionSelected)="chipAdd($event,field)" #auto="matAutocomplete">
      <mat-option [value]="opt.id" *ngFor="let opt of field.options">
        {{ opt.name }}
      </mat-option>
    </mat-autocomplete>

  </mat-form-field>

I've removed the mat-chip-list and only included the relevant code.
So my question is... right now I'm getting the options from field.options -- instead of this, how can I load them dynamically from the http backend, once I start typing?
Thanks for your help! :)

A: You can use reactive forms to achieve that. The docs here: https://angular.io/guide/reactive-forms.
Form's value changes can be a stream. You can query the back-end based on the input value.
I.e. (in the component ts file):
// define appropriate type for your options, string[] just as an example,
// I don't know what you'll receive from the back-end and use as the option:
public autocompleteOptions$: Observable<string[]>;

constructor(private http: HttpClient) { }

ngOnInit() {
  // If you don't know how to have reactive form and subscribe to value changes,
  // please consult: https://angular.io/guide/reactive-forms#observe-control-changes

  this.autocompleteOptions$ = this.inputFormControl.valueChanges
    // this inputFormControl stands for the autocomplete trigger input
    .debounceTime(150)
    // well, you probably want some debounce
    .switchMap((searchPhrase: string) => {
    // "replace" input stream into http stream (switchMap) that you'll subscribe in the template with "async" pipe,
    // it will run http request on input value changes
       return this.http.get('/api/yourAutocompleteEndpoint', { search: {
          value: searchPhrase }}
       });
   }
 }

Then, in your component's template:
<mat-option [value]="opt.id" *ngFor="let opt of autocompleteOptions$ | async">
  {{ opt.name }}
</mat-option>

There might be some additional features required, like filtering in this stream not to trigger autocomplete when the number of chars is too low or something, but this is just the base example you can potentially follow.


text:
Q: Remotely finding the mass of a satellite I have a question similar to one I've asked earlier (Calculating mass of an orbiting body with force and acceleration), but without a specific formula...
How can you find the mass of a satellite body (such as a moon or asteroid) without orbiting that body, or without it already having a satellite of its own? I understand that larger bodies can noticeably perturb their parent objects, but for the sake of the question lets assume that the object is vastly smaller (Such as an asteroid), and so those perturbations would be unrecognizable. The information that is available is mostly orbital (Semi-major axis, time, and so forth), but you could also use diameter/radius measurements. You don't know volume, and you don't know density either.

A: You can't. Imagine that the satellite was two objects tied together -- the orbital mechanics would be the same. What answer would be correct -- the mass of one or both ? Now imagine that they weren't tied, but in close proximity -- same conclusion.
Basically, if the satellite has no measurable influence on the host, it's mass has no effect, and can't be measured.

A: Once you put in the constraint that the satellite doesn't disturb its host, its mass no longer has any bearing on its orbit (it's now a 'test mass' in a potential). So throw out all your orbital measurements, they're of no use.
Without knowing anything about the composition (density) of the object this is going to be difficult. The best I can think of is to try and use the tidal forces exerted by the host and the fact that the satellite hasn't been destroyed to try and put a lower limit on its mass (something is holding it together, which will be some combination of self-gravity and tensile strength if it's a solid). But this will only be a useful constraint if the tides are strong; if the tides are very weak you'll basically just get $M>0$. Might be a bit better if you can measure the diameter accurately enough to measure tidal deformation. If the satellite is a liquid/gas this could even give a decent mass estimate, but if its solid you'd want to know something about the composition again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Only allow to drag and drop text and not typing in html input field I have an application that requires an input field. The user can drag and drop a piece of text(a link) on the input field but not type in anything inside the field. How can I achieve this?
I tried using read-only and disabled attributes with the input but this totally does not allow there to be any kind of input to be entered in the field.
Please suggest some way to achieve this. I want a box which can act like an input field and allow text to be dragged and dropped in it, but not allow the user to type in anything. I am attaching a picture with this, which shows the box that i wish to use as the input box.

The html is coded as follows:

    Select Your Country:
    <select id="market">
        <option id="SelectMarket" class="market_option" selected disabled>Select Market (Domain)</option>
    </select>

    Enter Your Tracking ID:
    <input id="tr_id" type="text" name="tr_id" placeholder="Tracking ID">

Drop link here:

    <input readonly id="link" type="link" name="link" value="+">

A: You need to drag the text of the tracking ID to the box. You can do it with some css and javascript. Fill the textbox and select the text. Once selected drag the selection into your box.

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.value);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    var texteSelectionne = document.createTextNode(data);
    ev.target.appendChild(texteSelectionne);
}
#div1 {
        width: 350px;
        height: 70px;
        padding: 10px;
        border: 1px solid #aaaaaa;
    }

    Select Your Country:
    <select id="market">
        <option id="SelectMarket" class="market_option" selected=selected disabled=disabled>Select Market (Domain)</option>
    </select>

    Enter Your Tracking ID:
    <input id="tr_id" type="text" name="tr_id" placeholder="Tracking ID" draggable="true" ondragstart="drag(event)"/>

    Drop link here:


text:
Q: JSF listeners in selectOneMenu I have a selectOneMenu item with some products. Some of them are unavailable so after you click on it the button "Add" should be disabled and some message should appear that "Sorry the product you chose is currently unavailable". I have no idea how to achieve that. Tried listeners, ajax and still nothing.
This is one of many versions of my JSF Page:
<h:form>
            <h:selectOneMenu value="#{productBean.productName}">
                <f:selectItems id ="other" value="#{productBean.other}" var="other" itemValue="#{ordersBean.productName}" itemLabel="#{other.name}" />
                <f:ajax listener="#{productBean.valueChanged}" />
            </h:selectOneMenu>
            <h:commandButton value ="Dodaj do zamówienia" rendered="#{productBean.available}"/>
                    <h:outputLabel id="orderSummary"/>
        </h:form>

Beans are rather standard. I just need a clue how to do that and probably I will be able to do it myself.
Thanks in advance.

A: Here's one of the ways:

*

*In your AJAX listener you could check if a product is available and set up bean field accordingly, or add a message for a component.

*Introduce a component in your view that'll hold the message to the user, for example with the #{bean.available ? '' : 'Sorry, out of stock'} value, or enclose it within a <h:panelGroup> and let that component have a rendered attribute, or attach <h:message>/<h:messages> somewhere in your view.

*Specify id of the message holder to be rendered within render attribute of <f:ajax> tag.


text:
Q: Factoring third degree polynomials using long division I am sure there is a better strategy that someone smarter than me would use, but I am not that person.
I am trying to factor
$$x^2 - 3x^2 - 4x + 12$$
I don't know how so I attempt to guess with long division. I cheat and look at the answer so find out one of the factors to save myself time, so I try x - 2
I am not sure how to type out long division but I get
$$ x - 2  |  x^3 - 3x^2 - 4x + 12$$
so I know I can have an $x^2$ for how many times x goes into the leading term.
Subract it all and I am left with
$$ x - 2  |  -x^2 - 4x + 12$$
I know that the leading term goes into the inner leading term $-x$ times or however you say that.
$$ x - 2  |   - 2x + 12$$
Now -2
$$ x - 2  |   8$$
Now I don't know what to do, how did this go so wrong? I have $x^2 - x -2$ ontop and I have a remainder of 8. This can't be right, I cheated so I know that this should be a factor.

A: Your first term, upon division: $x^2$ is correct $\large\checkmark$ (in the quotient), leaving

$$ x - 2  |  -x^2 - 4x + 12\quad\large\checkmark$$
I know that the leading term goes into the inner leading term $-x$ times or however you say that.
$$ x - 2  |   - 2x + 12 \quad \longleftarrow \text{error}$$

Here you subtracted incorrectly: We should have $x^2 - x$ in the quotient, that's correct, but multiplying $-x(x - 2) = -x^2 + 2x$
So when we subtract, we subtract, from $(-x^2 - 4x + 12) - (-x^2 + 2x) = -6x + 12$.
Now, we have $$ x -2 \mid -6x + 12$$ and so our ongoing quotient becomes $x^2 - x  {\bf - 6}$
which, leaves a zero remainder since $-6(x-2) = -6x + 12$, as desired.
So...we have that $$\frac{x^3 - 3x^2 -4x + 12}{x - 2} = x^2 - x - 6$$
Or, that is,  $$x^3 - 3x^2 - 4x + 12 = (x -2)(x^2 - x - 6) = (x-2)(x +2)(x - 3)$$

A: When you subtracted $(-x)(x-2)$ you should have gotten $-6x+12$.  You dropped a sign there.

A: As Andrew Salmon's comment points out, the easiest thing to try first to factor a cubic polynomial is to try to pair off the terms and see if they share a common factor.  If paired off in the order in which they are written, this becomes
$$x^2(x-3)-4(x-3)$$
or if the odd and even exponents are paired together
$$x(x^2-4)-3(x^2-4)$$
Then simply take out the common factor.
Of course, this won't always work, when it doesn't, the method of guessing roots is known as the rational root theorem.  First you'll want to try plugging in factors of the constant term to see if you get zero.  $\pm1$ is the easiest to check, then in this case you'd also have $\pm2,\pm3,\pm4,\pm6$ and $\pm12$.  If those all failed, you'd want to test any of those values divided by a factor of the leading term.  However, since your leading term is $1$, there isn't anything extra to test here.  If you find one root, you should be able to handle the remaining quadratic.  I doubt you'll be expected to factor any cubic polynomials with no rational roots, possibly excepting the form
$$x^3\pm a$$
at which point you could use the formula for the sum or difference of cubes even if $a$ is not a perfect cube.
Finally, although it's not foolproof, if you suspect a polynomial is a multiple of $x-2$, then plugging in $2$ should yield $0$.  Since you're dividing by $x-2$, your remainder at each step should also be a multiple of $x-2$.  Testing your polynomials at each step reveals
$$2^3-3(2)^2-4(2)+12=8-12-8+12=0$$
$$-(2)^2-4(2)+12=-4-8+12=0$$
$$-2(2)+12=-4+12=8$$
This implies there was an error in the remainder $-2x+12$


text:
Q: Sockets: Receiving data from an (mostly) unknown (bluetooth) device I have a GPS tracker from which I want to collect the location data that it stored somehow. Client software exist, but I want to try it for myself.
I already downloaded and installed the needed python libraries and successfully connected to the device. Now, I have the socket (sending "Hello World" results in "4") and I don't know, what to do next.
How can I receive data from the device? Is it even possible?
This is the Bluetooth profile the device supports
I would be glad if you could help me.
Best regards,
Jan Oliver

A: You need to know the protocol of the device, which somtimes is openly published sometimes not.
For example I know that some professional (centimter-precision) GPS devices even have protection by a special handshake procedure that the client software need to send before it will allow any communication, to prevent any third-party software to be written.
If you can specify the exact brand and model of the GPS tracker it will be easier to help.


text:
Q: AttributeError: module 'torch._six' has no attribute 'PY3' if torch._six.PY3:

AttributeError: module 'torch._six' has no attribute 'PY3'

A: It's true. torch._six has no attribute PY3. At least the current version doesn't. It does, however, have an attribute PY37 (see current module source code). Perhaps that's what you meant? Or perhaps you're not using the PyTorch version that you intended? Without more information (e.g. your intended use case, your intended PyTorch version, your actual PyTorch version), I can only make guesses. In the future, please provide as much relevant information as you can.
Either way, I'm very confident this is an XY problem. torch._six isn't even a module that's intended to be imported except by other internal modules, hence the naming convention (i.e. prepended with an underscore; see here). Such private modules are not necessarily expected to be stable or backwards-compatible, so you generally should not rely on them. If you're indeed trying to check the python version, you should not rely on torch._six; you should check it yourself. You can even do it the same way torch._six does it, if you'd like (see previous link). But that's a separate question.


text:
Q: Hosts file not working with bindings in IIS I have added a website to IIS with a binding hostname of richard-danvers.dev assigned to port 80
I have then added an entry to the hostfile with the public ip address of the server and the host name:
51.141.98.202 richard-danvers.dev

I have also tried
127.0.0.1 richard-danvers.dev

this results in ERR_CONNECTION_REFUSED
when I ping the hostname I can see any changes I have made in the hostfile (e.g. 127.0.0.1) but it still does not work when trying to navigate to the site in a browser.
and I have also tried with the actual DNS record I have pointed to the public IP (this returns a ERR_CONNECTION_TIMED_OUT and ping resolves but does not get any successful pings)
none of these seem to allow my website to be accessed. When I enter a binding without a hostname I can hit the website under localhost fine so can't understand what I've done wrong/missed.

A: Because I am using a .dev domain the ssl certificate had to be set up and configured in the bindings to allow the hostname to be hit.


text:
Q: Custom actions without additional prerequisites In the past I've written all my custom actions in VBScript, because my understanding is that this (and JScript) is the only type of custom action which does not require additional prerequisites on the target system.
However, writing VBScript is a pain, and now I also encountered a problem which apparently cannot be solved in VBScript (see Currupted file in non-english locale (encoding problem?)).
So I'm considering using a C# custom action instead. But I don't want to introduce additional prerequisites just for the custom action (note that the application I'm installing does not use the .NET Framework).
This list shows which Windows version includes which .NET Framework version. Assuming that newer .NET Framework versions are backwards compatible, it looks like a .NET Framework 2.0 custom action should run on virtually any Windows version (except for XP, which I don't care about) out of the box. But then on this site it says

In addition, if your app targets version 2.0, 3.0, or 3.5, your users may be required to enable the .NET Framework 3.5 on a Windows 8, Windows 8.1, or Windows 10 computer before they can run your app.

So it looks like the assumption that newer .NET Framework versions are backwards compatible is not correct...
The WiX custom action project created a CustomAction.config file with the following settings:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0" />
        <supportedRuntime version="v2.0.50727"/>
    </startup>
</configuration>

So here are a few questions:

*

*Can I assume that a .NET Framework 2.0 custom action with the above config runs on any Windows (except for XP)? Or does .NET Framework 3.5 need to be enabled on newer versions of Windows despite the fact that the config file states 4.0 as a supported runtime?

*What's generally speaking the best way to create a custom action (not VBScript or JScript) without introducing any additional prerequisites? (I was considering a "C++ Custom Action Project for WiX v3", but it looks like this creates a managed C++ project, so the same questions around .NET Framework arise).

Update:
I tested this .NET Framework 2.0 custom action in a fresh Windows Server 2008 R2 and in a fresh Windows 10 VM. The custom action ran without needing to install the .NET Framework manually. So based on this little test it looks like compatibility of such a custom action is quite good.

A: There are some issues with .NET custom actions. I have this old answer - that I haven't reviewed in a while. I remember I read it once thinking "I must have lost my mind that day". It is the list towards the end of the answer that mentions a few managed code problems (quickly: 1) too many dependencies, 2) CLR version load behavior issues (up to date?), 3) GAC dependencies, 4) lack of minimal dependencies and uninstall issues, 5) Broken or unavailable .NET runtime, etc...). I am not an expert on this topic.
It seems to get better over time to use .NET because the runtime is now part of the OS. You can lock a setup so it won't install on downstream OS by means of Launch Conditions. And there aren't that many CLR versions - just 2 and 4 basically?
Here are two answers on using C++ and C# / .NET respectively for custom actions:

*

*How to use C++ custom actions in WiX.

*How to use C# managed code custom actions in WiX.

Remember the propaganda against custom actions. They are error prone. Very.

Links:

*

*Don't use managed code to write your custom actions!


text:
Q: Mono NotImplementedException in X509CertificateCollection I have a console application written in C# that I'm trying to run on Linux with mono 4.2.1 (also tried 4.4.1), but I'm getting a NotImplementedException when calling X509CertificateCollection.Add(). This is the offending code:
var cert = new X509Certificate2(certFilename, "");
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(cert);

I have mono-complete installed, and tried both a standard build and Xamarin build, with the same results. I also checked I have ca-certificates-mono installed based on this in the docs. I did some digging and found this in the mono code, which suggests this functionality has been implemented, but clearly is not working for me. Am I missing part of the build/deployment process here?

A: If you are getting a NotImplementedException then something is missing down the chain of your assembly dependencies. What I would do is check if your solution has the required dependencies for the X509Certificate installed in your GAC/BIN on debug. I hope this helps!


text:
Q: Angular 4 - On change component object I have a component with some dropdowns. Each dropdown is populated by an array (loaded via rest services) and sometimes these arrays could be updated.
Is there a way to call a function when these arrays changes?
Such as a listener on a variable that when is reassigned I do somethings.
Thanks
Fabrizio

A: If dropdowns are separate components and arrays are passed to them, you can use OnChanges. ngOnChanges function is called when any data-bound property of a directive changes.
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
  @Input()
  prop: number;

  ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
  }
}

There is no Angular equivalent to AngularJs' $watch.
Alternatively, you can call desired function after success data update when you call REST API.


text:
Q: Service Bus IAsyncResult I'm curently trying to make my App able to receive Asyncronously message from my Service Bus.
But, Sometimes an Exception is Throw and i don't know how to make it disapear or from what it can come from.
Here's the exception:
Exception: System.NullReferenceException: Object reference not set to an instance of an     object. at GetOffers.DbConnection.processEndReceive(IAsyncResult result);

So, I know it come from my IASync method, but I'm not able to understand where it don't work properly.
My QueueClient conf:
QClient = QueueClient.CreateFromConnectionString(connectionString, queueStr,ReceiveMode.ReceiveAndDelete);

Here my both IASync Method:
    void processEndReceive(IAsyncResult result)
    {
        try
        {
            QueueClient qc = result.AsyncState as QueueClient;
            BrokeredMessage message = qc.EndReceive(result);
            ForexData data = new ForexData();

            var newtrade = new Trade(data.OfferId, message.Properties["login"].ToString(), message.Properties["amount"].ToString(), message.Properties["instr"].ToString(), message.Properties["type"].ToString(), data.CreationDate, message.Properties["mode"].ToString(), message.Properties["accountID"].ToString(), message.Properties["idTrade"].ToString());
            //Static Variable for the WHERE (sql) in ResponseListener Line 215.
            idtradetemp = message.Properties["idTrade"].ToString();
            Console.WriteLine("Received message " + message.Label);
            if (newtrade != null)
            {
                try
                {
                    newtrades.Add(newtrade);
                }
                catch
                {
                    Console.WriteLine("Une erreur est survenue lors l'ajout du message dans la liste 'newtrades'");
                }
                Console.WriteLine("Received Delete: " + DateTime.Now);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(string.Format("Exception: {0}", e.ToString()));
            TextWriter tw = new StreamWriter("logServiceBus.txt", true);
            tw.WriteLine("Program terminated on " + DateTime.Now);
            tw.WriteLine("------------------------------------");
            tw.WriteLine(string.Format("Exception: {0}", e.ToString()));
            tw.WriteLine("------------------------------------");
            tw.Close();
        }
    }

    void processEndComplete(IAsyncResult result)
    {
        try
        {
            BrokeredMessage m = result.AsyncState as BrokeredMessage;
            m.EndComplete(result);
            Console.WriteLine("Completed message " + m.Label);
        }
        catch
        {

        }
    }

Basicaly those method are Trigger everytime he detect a new message in the ServiceBus. The thing is, I've put a Console.WriteLine("New Message"); when a new message are detected, but, this CW are trigger 2times (or more).
So One of two things:
What can cause my error ? And HOW can I make my IAsync method to just be trigger once ON THIS message.

A: Using the Begin/End pairs can be difficult to program correctly. Have you tried updating your code to use the async/await pattern? Service Bus libraries for the released service as well as for Service Bus 1.1 on server also support a Task based API. See http://www.windows-azure.net/task-based-apis-for-service-bus/ for details (I'm the author of that post). You can then use ReceiveAsync. You may also want to look at the OnMessage API which will also work. (docs are here: http://msdn.microsoft.com/en-us/library/microsoft.servicebus.messaging.queueclient.onmessage.aspx)


text:
Q: accelerometer for linear displacement I have accelerometer readings from the android device.
I would like to know what kind of acceleration this data represents(rotation or linear acceleration).
Is there anyway I can use this data to distinguish between rotation and translation(if it has both)?
I tried low-pass-filtering the data and find the distance using this code:
        oldaccel+=0.1428* (accel-oldaccel); //low pass filtering
        S+=((V*dT)+ (0.5*oldaccel*dT*dT)); //finding the distance with previous velocity
        V+=(oldaccel*dT);                  //updating the velocity

(  oldaccel-filtered data
  accel-accelerometer data
  S-distance,V-velocity,dT-sampling period)
It doesn't give me the distance expected for a linear motion(I'm guessing useful data is being eliminated along with noise?)

A: You would probably need to highpass filter to yield translational acceleration,depending on the nature of the translations you're talking about. This doesn't take into account any processing the Android already does.


text:
Q: Performance of external USB disk with ESXi5 I have a new HP DL120 G7 server with ESXi5. One VM is a Win2003 instalation and I have an external USB2.0 drive attached by USB Controller and USB Device.
I copy a 4GB file from  external USB to server disk.
In the VM that takes up to 10 minutes.
On a native Win2003 that takes aprox. 3 minutes.
I have no explaination for that diference:

*

*In any case the bottleneck is the USB connection, much slower than
the disks (SAS, RAID1).

*If the USB connection on the VM would be USB1.1 and not USB2.0 it would take much
more time.

*(The disk performance between server partitions on the VM is correct. -> see update)

*Could be that my native box is extremely fast and the VM is the normal case.

*???

Update
As mentioned, i tried with passthrough and it is much better.

A: The best performance in this scenario would be achieved by passing the USB controller to the virtual machine (VT-D). Otherwise, you'll only get USB 1.1 speeds.


text:
Q: How to list all districts of a city showing profits every month I need to list all the districts of a city showing profits every month.
I am not knowing how to tie the count values of the products with the month in the subquery.
Could someone give me a hand?
SELECT
       districts.id,
       districts.name,
       mmonth.m10
FROM districts
INNER JOIN
  (SELECT
       SUM(product_order.price_of_day * product_order.amount) AS m10
   FROM product_order
   INNER JOIN orders ON product_order.order_id = orders.id
   WHERE MONTH(orders.date_time) = 10 ) mmonth
INNER JOIN cities ON cities.id = districts.city_id
WHERE cities.id = 2;

http://sqlfiddle.com/#!2/8fb34/4
Look what I need.
| id |     name   | m10 | m11 | m12 |
------------------------------------
|  3 | district 3 | 730 | 360 | 453 |
------------------------------------
|  4 | district 4 | 730 | 250 | 856 |
-------------------------------------

How would I sum the months like this?
| id |     name   | m10 | m11 | m12 | total |
---------------------------------------------
|  3 | district 3 | 730 | 360 | 453 | 1543  |
---------------------------------------------
|  4 | district 4 | 730 | 250 | 856 | 1836  |
---------------------------------------------

A: EDIT:
This should do it:
SELECT
       districts.id,
       districts.name,
       SUM(IF(MONTH(orders.date_time) = 10, product_order.price_of_day * product_order.amount, 0)) AS m10,
       SUM(IF(MONTH(orders.date_time) = 11, product_order.price_of_day * product_order.amount, 0)) AS m11,
       SUM(IF(MONTH(orders.date_time) = 12, product_order.price_of_day * product_order.amount, 0)) AS m12,
       SUM(product_order.price_of_day * product_order.amount) AS total
FROM cities
LEFT JOIN districts ON cities.id = districts.city_id
LEFT JOIN orders ON orders.district_id = districts.id
LEFT JOIN product_order ON product_order.order_id = orders.id
WHERE cities.id = 2
GROUP BY districts.id;

A: You should be using GROUP BY (see: http://technet.microsoft.com/en-us/library/ms177673.aspx)
SELECT
    [IdentifyingDataColumnName]
    ...
    ,[IdentifyingDataColumnName1]
    ,[CalculatedField] =  SUM(<column name(/s) / Calculation to sum>)
FROM
    Table 1
    LEFT JOIN 2
GROUP BY
    [IdentifyingDataColumnName]
    ...
    ,[IdentifyingDataColumnName1]
HAVING
    SUM(<column name(/s) / Calculation to sum>) > 0

Having re-read your question (and realising I'd completely mis-read it!) you could do the following:
SELECT
    districts.id
    ,districts.name
    ,SUM(CASE WHEN MONTH(orders.date_time) = 10 THEN (product_order.price_of_day * product_order.amount) ELSE 0 END) AS m10
    ,SUM(CASE WHEN MONTH(orders.date_time) = 11 THEN (product_order.price_of_day * product_order.amount) ELSE 0 END) AS m11
    ,SUM(CASE WHEN MONTH(orders.date_time) = 12 THEN (product_order.price_of_day * product_order.amount) ELSE 0 END) AS m12
FROM
    districts
    INNER JOIN cities ON cities.id = districts.city_id
    INNER JOIN orders ON districts.id = orders.district_id
    INNER JOIN product_order ON product_order.order_id = orders.id
WHERE
    cities.id = 2
GROUP BY
    districts.id
    ,districts.name

Adding a total column couldn't be easier, you just remove the CASE... WHEN... THEN... ELSE... END and it will sum them all; the below code has also been modified to use a LEFT JOIN in order to ensure that should a district exist for the city without orders it will still be listed with monthly values of 0 (For more information see: http://technet.microsoft.com/en-us/library/aa178429(v=SQL.80).aspx)
SELECT
    districts.id
    ,districts.name
    ,SUM(CASE WHEN MONTH(orders.date_time) = 10 THEN (product_order.price_of_day * product_order.amount) ELSE 0 END) AS m10
    ,SUM(CASE WHEN MONTH(orders.date_time) = 11 THEN (product_order.price_of_day * product_order.amount) ELSE 0 END) AS m11
    ,SUM(CASE WHEN MONTH(orders.date_time) = 12 THEN (product_order.price_of_day * product_order.amount) ELSE 0 END) AS m12
    ,SUM(product_order.price_of_day * product_order.amount) AS Total
FROM
    districts
    INNER JOIN cities ON cities.id = districts.city_id
    LEFT JOIN orders ON districts.id = orders.district_id
    LEFT JOIN product_order ON product_order.order_id = orders.id
WHERE
    cities.id = 2
GROUP BY
    districts.id
    ,districts.name


text:
Q: What does <<>> mean between the function name and its arguments? I am learning caffe(bvlc).
When I analyzed code, I found strange code I didn't know.
like this :
im2col_gpu_kernel<Dtype><<<CAFFE_GET_BLOCKS(num_kernels),
                         CAFFE_CUDA_NUM_THREADS>>>(
  num_kernels, data_im, height, width, kernel_h, kernel_w, pad_h,
  pad_w, stride_h, stride_w, dilation_h, dilation_w, height_col,
  width_col, data_col);

When I commentted to im2col_gpu_kernel func, I found tons of calling about that func.
So I guessed "<<< >>>" this code conducting loop(like for, while) calling about func.
Is it? or Is there another role?
and Is this code c++ std library?

A: This triple angled-bracket notation is part of CUDA runtime syntaxic sugar. It is a placehoder to configure a device call execution - see CUDA programming model for details.


text:
Q: Is this #define equivalent to this variable definition in C? Consider this #define:
#define msd_buffer              ((volatile char *) MSD_BUFFER_ADDRESS)

and this variable definition:
volatile char *msd_buffer = MSD_BUFFER_ADDRESS;

Are the two definitions of msd_buffer — as variable and as macro — equivalent?

A: A #define is a macro. It acts as a direct copy-pasta of what you pass into it. So, msd_buffer is not a variable, it is a cast to a volatile char array.
Assuming example usage like this:
msd_buffer[160] = 0xFF;

It would be the same as using it as a variable. However, it doesn't have all the features of a variable, such as assignment:
msd_buffer = NEW_BUFFER_ADDRESS; // invalid!

Or address taking:
my_func(&msd_buffer); // invalid!

If you understand these drawbacks (and perhaps there are more), then you are on your way to using a macro like this.

A: A define statement is just a textual substitution. Nothing more. So in your case, not really.


text:
Q: From character to dates-time in R using decimal hours I'm trying to convert characters to dates in R.
My data as the following format:
df <- data.frame(Date = c("23Jul2019 11:51:09 AM","23Jul2019 11:53:09 AM","19Jul2019 2:30:06 PM","01Aug2019 3:00:17 PM"))

Based on the solution found here:
Convert character to Date in R
I could use
> as.Date(df$Date, "%d/%b/%Y %I:%M:%S %p")
[1] NA NA NA NA

%I is for decimal hour (12h) and %p Locale-specific AM/PM (https://www.stat.berkeley.edu/~s133/dates.html) but for some reason, it returns NAs.
My goal is to sort the rows of a dataframe by date and time once dates in the character format converted to Dates in R.
What is the issue with the code I'm using?

A: This should solve it
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#>     date
df <- data.frame(Date = c("23Jul2019 11:51:09 AM","23Jul2019 11:53:09 AM","19Jul2019 2:30:06 PM","01Aug2019 3:00:17 PM"))

df %>%
  mutate(r_date_time = Date %>% dmy_hms)
#>                    Date         r_date_time
#> 1 23Jul2019 11:51:09 AM 2019-07-23 11:51:09
#> 2 23Jul2019 11:53:09 AM 2019-07-23 11:53:09
#> 3  19Jul2019 2:30:06 PM 2019-07-19 14:30:06
#> 4  01Aug2019 3:00:17 PM 2019-08-01 15:00:17

dmy_hms(df$Date)
#> [1] "2019-07-23 11:51:09 UTC" "2019-07-23 11:53:09 UTC"
#> [3] "2019-07-19 14:30:06 UTC" "2019-08-01 15:00:17 UTC"

Created on 2020-01-14 by the reprex package (v0.3.0)


text:
Q: Tooltip/Speech bubble with a gradient background and arrow at top-center I have this shape:

and I was wondering if its possible to create it with CSS3.
This is what I have so far (click for fiddle):
HTML:

CSS:
html, body {
    height: 100%;
}
.caspSearch {
    border: 1px solid black;
    background: black;
   background: -moz-linear-gradient(top, rgba(128, 144, 152, 0.9) 0%, rgba(67, 74, 80, 0.91) 8%, rgba(54, 58, 61, 0.96) 91%, rgba(74, 81, 85, 0.9) 100%);
    /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(128, 144, 152, 0.9)), color-stop(8%, rgba(67, 74, 80, 0.91)), color-stop(91%, rgba(54, 58, 61, 0.96)), color-stop(100%, rgba(74, 81, 85, 0.9)));
    /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, rgba(128, 144, 152, 0.9) 0%, rgba(67, 74, 80, 0.91) 8%, rgba(54, 58, 61, 0.96) 91%, rgba(74, 81, 85, 0.9) 100%);
    /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, rgba(128, 144, 152, 0.9) 0%, rgba(67, 74, 80, 0.91) 8%, rgba(54, 58, 61, 0.96) 91%, rgba(74, 81, 85, 0.9) 100%);
    /* Opera 11.10+ */
    background: -ms-linear-gradient(top, rgba(128, 144, 152, 0.9) 0%, rgba(67, 74, 80, 0.91) 8%, rgba(54, 58, 61, 0.96) 91%, rgba(74, 81, 85, 0.9) 100%);
    /* IE10+ */
    background: linear-gradient(to bottom, rgba(128, 144, 152, 0.9) 0%, rgba(67, 74, 80, 0.91) 8%, rgba(54, 58, 61, 0.96) 91%, rgba(74, 81, 85, 0.9) 100%);
    /* W3C */
    width: 500px;
    height: 300px;
    border-radius: 10px;
    padding: 0 !important;
    position:relative;
    top: 30px;

}
.caspSearch:before {
    content:'';
    width: 0;
    height: 0;
    display: block;
    position: absolute;
    border-bottom: 50px solid white;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
}

I'm struggling with the triangle since it needs to be with transparent gradient and the black border needs to wrap it .

A: Is this what you are looking for?
CSS
.triangle-isosceles {
    height: 200px;
    width: 300px;
    position:relative;
    padding:15px;
    margin:1em 0 3em;
    color:#000;
    background:#f3961c;
    background:-webkit-gradient(linear, 0 0, 0 100%, from(#f9d835), to(#f3961c));
    background:-moz-linear-gradient(#f9d835, #f3961c);
    background:-o-linear-gradient(#f9d835, #f3961c);
    background:linear-gradient(#f9d835, #f3961c);
    -webkit-border-radius:10px;
    -moz-border-radius:10px;
    border-radius:10px;
}

.triangle-isosceles.top {
    background:-webkit-gradient(linear, 0 0, 0 100%, from(#f3961c), to(#f9d835));
    background:-moz-linear-gradient(#f3961c, #f9d835);
    background:-o-linear-gradient(#f3961c, #f9d835);
    background:linear-gradient(#f3961c, #f9d835);
}

.triangle-isosceles:after {
    content:"";
    position:absolute;
    bottom:-15px;
    left:50px;
    border-width:15px 15px 0;
    border-style:solid;
    border-color:#f3961c transparent;
    display:block;
    width:0;
}

.triangle-isosceles.top:after {
    top:-15px;
    right:50px;
    bottom:auto;
    left:auto;
    border-width:0 15px 15px;
    border-color:#f3961c transparent;
}

HTML

Your content.

The Fiddle
http://jsfiddle.net/sjccN/4/

A: I made a sample for you... just add your shadows and such to this and your set :)
http://jsfiddle.net/BNgTh/
#talkbubble {
   width: 120px;
   height: 80px;
    margin-top:20px;
    margin-left:40px;
   background: red;
   position: relative;
   -moz-border-radius:    10px;
   -webkit-border-radius: 10px;
   border-radius:         10px;
}
#talkbubble:before {
   content:"";
   position: absolute;
   top: -20px;
    left:40%;
   width: 0;
   height: 0;
   border-bottom: 26px solid red;
   border-right: 13px solid transparent;
   border-left: 13px solid transparent;
}

Change the top value in #talkbubble:before to make it smaller as you wish too.


text:
Q: using SqlDependency class to populate ICollectionView with EntityFramework in C# I want to refresh the ICollectionView object which has some product when a new product is added to database.
How can I achieve this in C#, I am using EntityFramework for DAL.

A: I found following post by "Harry von Borstel" very helpful


text:
Q: To prove that $L^{\infty}$ is a subspace of $L^{\Phi}$(Orlicz space) Let me define it first
Definition 1: A mapping $\Phi:\mathbb{R}\to\mathbb{R^+}\cup{\infty}$ is said to be an N function if
(1) $\Phi$ is convex
(2) $\Phi(0)=0$
(3) $\lim_{x\to \infty}\Phi(x)=\infty$
Orlicz space: Let $(\Omega,F,\mu)$ be arbitrary measure space. The $\Phi$-Orlicz space is defined as
$$\tag{1}
L^{\Phi}(\mu)=\Big\{f:\Omega \to \mathbb{R} \hspace{0.2cm} \text{such that} \int_{\Omega}\Phi(|\alpha f|)\,\mathrm d\mu<\infty \mbox{ for some } \alpha>0\Big\}
$$
What we have is that $L^{\Phi}$ is a normed linear space with the norm
$$
\|f\|_{\Phi} = \inf\Big\{k>0:\int_{\Omega}\Phi(\tfrac{f}{k})\,\mathrm d\mu\leq 1\Big\}
$$
$L^{\infty}$ space: Let $(\Omega,F,\mu)$ be a measure space then $L^{\infty}=\{f:\Omega\to \mathbb{R}\text{ such that } ||f||_{\infty}<\infty\}$
where $||f||_{\infty}=inf\{K\geq 0\text{ such that } |f(x)|\leq K \text{ a.e }\}$
I have to show that $L^{\infty}$ is a subspace of $L^{\Phi}$. What I understand is that in $L^{\infty}$ we have functions that are bounded almost everywhere. To show that it is a subspace of $L^{\Phi}$ we have to first show that $L^{\infty}\subseteq L^{\Phi}$ and in $L^{\Phi}$ we have all the measurable real-valued functions which satisfy the given integral condition. so if I pick $f\in L^{\infty}$ then how we can say that it is in $L^{\Phi}$ since bounded almost everywhere does not imply measurable? So I am stuck here and also I have no idea how do I proceed to prove other properties like scalar multiplication and how do we induce norm on $L^{\infty}$ space? Can someone help to prove this.That will be great help thanks.

A: When $\mu(\Omega)<\infty$ the statement is true: since $|f|\leq\|f\|_\infty$ $\mu$-almost surely and $\Phi$ is monotone increasing (why?)
$\Phi(|f|)\leq \Phi(\|f\|_\infty)$. Hence
$$\int\Phi(|f|)\,d\mu\leq \Phi(\|f\|_\infty)\mu(\Omega)<\infty$$
Thus, $L_\infty(\mu)\subset L_\Phi(\mu)$
Furthermore, in such a case, by choosing $a>0$ such that $0<\Phi(a)<1/\mu(\Omega)$ we have that
$\Phi\big(a\tfrac{|f|}{\|f\|_\infty}\big)\leq\Phi(a)$ $\mu$-almost surely ($\Phi$ is monotone nondecreasing) and so,
$\int\Phi\big(a\tfrac{|f|}{\|f\|_\infty}\big)\,d\mu\leq \Phi(a)\mu(\Omega)<1$ which means that
$$\|f\|_{\Phi}\leq \frac{\|f\|_\infty}{a}$$
In other words, the inclusion map $f\stackrel{\iota}{\hookrightarrow} f$ from $L_\infty(\mu)$ into $L_\Phi(\mu)$ is a continuous bounded operator.
If $\mu(\Omega)=\infty$ the inclusion $L_\infty(\mu)\subset L_\Phi(\mu)$ does not hold. For example take a function $f\in L_\infty(\mu)$ that is bounded away from zero, that is for some $\varepsilon>0$, $|f|>\varepsilon$. The $$\int\Phi(\alpha^{-1}|f|)\,d\mu\geq\int\Phi(\alpha^{-1}\varepsilon)\,d\mu=\Phi(\alpha^{-1}\varepsilon)\mu(\Omega)=\infty, \qquad \alpha>0$$


text:
Q: Get a strange "syntax error" when i'm trying to insert into a table I'm trying to add a new row into a table I have. The database is a MSSQL. I have some other tables that have been working just fine, but when I did a new one I cant add new rows to it. Instead I get this error message:
"An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'User'."
I have no idea why...
the code in VS2013 lookes like this
        public void Update_Admin(User User)
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO Admin (User, Password) VALUES (@User, @Password);", con))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@User", SqlDbType.VarChar).Value = User.UserName;
            cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = User.Password;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

I know that the values that come in is true. Anyone knows whts wrong?
the table looks like this
CREATE TABLE [dbo].[Admin] (
[Id]       INT          IDENTITY (1, 1) NOT NULL,
[User]     VARCHAR (50) NULL,
[Password] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)

);

A: You have to escape the word User:
using (SqlCommand cmd = new SqlCommand("INSERT INTO Admin ([User], Password) VALUES (@User, @Password);", con))


text:
Q: NullPointerException While adding JLabel to JPanel Im getting this strange NullpointerException whilst adding a JLabel to a JPanel:
    loadoutAdvWeaponPanels = new JPanel[4][4];
    loadoutAdvWeaponButtons = new JButton[4];
    loadoutAdvPistolLabels = new JLabel[4][8];

    //Init loadoutAdvPanels[0]

    loadoutAdvWeaponButtons[0] = new JButton("Pistols");

    loadoutAdvPistolLabels[0][0] = new JLabel("USP-S");
    loadoutAdvPistolLabels[0][1] = new JLabel("P2000");
    loadoutAdvPistolLabels[0][2] = new JLabel("Dual Berettas");
    loadoutAdvPistolLabels[0][3] = new JLabel("P250");
    loadoutAdvPistolLabels[0][4] = new JLabel("Five-SeveN");
    loadoutAdvPistolLabels[0][5] = new JLabel("CZ75-Auto");
    loadoutAdvPistolLabels[0][6] = new JLabel("Desert Eagle");
    loadoutAdvPistolLabels[0][7] = new JLabel("R8 Revolver");

    loadoutAdvWeaponPanels[0][0].add(loadoutAdvPistolLabels[0][0]);

The error occurs in the last line, but i dont know why.

A: you should initialize the array loadoutAdvWeaponPanels
    loadoutAdvWeaponPanels = new JPanel[4][4];
    for(int i = 0; i < loadoutAdvWeaponPanels.length; i++)
        for(int j = 0; j < loadoutAdvWeaponPanels[i].length; j++)
            loadoutAdvWeaponPanels[i][j] = new JPanel();

or just initialize what you need
    loadoutAdvWeaponPanels[0][0] = new JPanel();
    loadoutAdvWeaponPanels[0][0].add(loadoutAdvPistolLabels[0][0]);

A: Simple as I see!
You do not initialisized loadoutAdvWeaponPanels[0][0]
I prefer to use this:
for(int i = 0; i < loadoutAdvWeaponPanels.length; i++) {
    for(int j = 0; loadoutAdvWeaponPanels[i].length; j++) {
    {
         loadoutAdvWeaponPanels[i][j] = new JPanel();
    }
}


text:
Q: chrome started crashing all of a sundden I have Google chrome  3.0.195.27 installed on XP,  without any apparent change in my system setup it started crashing a few minutes after I start the application.    how can I resolve this problem?

A: The first thing I would try is reinstalling Chrome.


text:
Q: HTTP: Illegal chunked encoding I have a .NET client-application which uses a third-party library to access a server via http. The library throws the following error:
The server committed a protocol violation. Section=ResponseBody Detail=Response chunk format is invalid

The software is already installed dozens of times, so i think it must be an issue in the customers system, my suspicion is the proxy between.
I have used Fiddler to get a first hint. While sniffing Fiddler notice a protocol violation:
Illegal chunked encoding. 'MIME-Version: 1.0' is not a hexadecimal number.

Fiddler shows the following response:
MIME-Version: 1.0
Content-Type: Multipart/Related; boundary=MIME_boundary_RsidtvFKHs9ymusS/NI6l56qcD8r76ye; type=text/xml

--MIME_boundary_RsidtvFKHs9ymusS/NI6l56qcD8r76ye
Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: 8bit
Content-ID: <osci@message>
Content-Length: 1545

<?xml version="1.0" encoding="UTF-8"?>

<soap:Envelope xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/ soapMessageEncrypted.xsd http://www.w3.org/2000/09/xmldsig# oscisig.xsd http://www.w3.org/2001/04/xmlenc# oscienc.xsd"><soap:Body><xenc:EncryptedData MimeType="Multipart/Related"><xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></xenc:EncryptionMethod><ds:KeyInfo><xenc:EncryptedKey><xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"></xenc:EncryptionMethod><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIID0jCCArqgAwIBAgIJAMg6MGbE+zZRMA0GCSqGSIb3DQEBDQUAMIGJMQswCQYDVQQGEwJERTEf
MB0GA1UECAwWTWVja2xlbmJ1cmctVm9ycG9tbWVybjERMA8GA1UEBwwIU2Nod2VyaW4xLDAqBgNV
BAoMI0NvbXB1dGVyLUJlcm

As you can see the response stopped unexpectedly.
Does anyone know what the issue might be or how to fix em?

A:
The header of the request is as follows:
POST /osci-manager-entry/externalentry HTTP/1.0
Host: [the-host]
Content-Length: 3984
Proxy-Connection: Keep-Alive

The header of the response contains this:
HTTP/1.0 200 OK
Date: Mon, 04 Jan 2016 12:10:31 GMT
Transfer-Encoding: chunked
Content-Type: text/plain; charset=iso-8859-1
Connection: Keep-Alive

The software is already installed dozens of times, so i think it must
be an issue in the customers system, my suspicion is the proxy
between.

Most likely, the problem is caused by the usage of HTTP/1.0 in this case. Chunked transfer and Keep-Alive are not standard in HTTP/1.0.
In chunked transfer encoding, each chunk should start with a hexadecimal number indicating the size of the chunk that follows. Obviously that number is not present here: Illegal chunked encoding. 'MIME-Version: 1.0' is not a hexadecimal number.
In HTTP/1.0, Keep-Alive and chunked transfer-coding cannot be used together:

An HTTP/1.1 server may also establish persistent connections with
HTTP/1.0 clients upon receipt of a Keep-Alive connection token.
However, a persistent connection with an HTTP/1.0 client cannot make
use of the chunked transfer-coding, and therefore MUST use a
Content-Length for marking the ending boundary of each message.


text:
Q: Duda sobre la relacion de una tabla estoy haciendo un sistema de llantas y tengo una duda en la creacion de una tabla para el siguiente requerimiento:

*

*El sistema tendra un modulo de "rotacion de llantas", en la cual se ingresara 2 llantas: La llanta a rotar y la llanta por la que se va a rotar

Estuve pensando el modo de hacerlo e hice lo siguiente:

Edit-01
Explicacion

*

*"llantas_informacion": Como su nombre indica sirva para poner la informacion de la llanta: "condicion, cocada y situacion"

*"vehiculos_llantas": Aqui se pondran los vehiculos con la posicion de la llanta, la relacion seria "llantas_informacion->vehiculos_llantas", "uno-uno"

*"reg_llantas_rota_mov": Significa "registro de llantas rotacion movimiento", quiere decir que aqui estaran todas las llantas que van a rotar, la llanta uno es la llanta a rotar y la llanta dos es la llanta por la que se va a rotar

*"reg_llanta_rota": Significa "registro de llantas rotacion", sirve para guardar la informacion adicional de las llantas que se van a rotar, como la observacion y el vehiculo

Como ven, hay una tabla que dice "reg_llantas_rota_mov", en esta tabla guardo las 2 llantas que se obtienen de la tabla "llantas_informacion", mi pregunta es la siguiente:

*

*¿La relacion hecha es correcta? (Ya que en una tabla estoy guardando 2 veces el id de la tabla "llantas informacion" donde guardo las 2 llantas que necesito)

Gracias a todos!

A: Te propongo este modelo alternativo al tuyo:

En la relación llevan tendrás el registro de la rotación de todas las llantas que se han ido montando en cada vehículo.
Fíjate que, en tu propuesta, creas tablas para llantas rotas y vinculas directamente vehículos con llantas. Debes tener en cuenta que:

*

*Aunque se rompan, las llantas continúan siendo llantas. El hecho de que estén rotas es un simple atributo, como el color. Por lo tanto, no es necesario crear la entidad reg_llantas_rota.

*Por otra parte, la relación o tabla intermedia reg_llantas_rota_mov, con la que intentas llevar un registro de la rotación de las llantas, debería ir entre el vehículo y las llantas.

*Tampoco es necesario vincularla por dos campos a las llantas. Cada vez que montes una llanta en un vehículo generas un nuevo registro. Así, podrás almacenar todas las rotaciones de llantas que necesites, no únicamente dos.

*La creación de un módulo para gestionar la base de datos, no implica necesariamente la creación de nuevas tablas o entidades si lo puedes resolver añadiendo campos o atributos.

La implementación en MySQL sería algo así:
CREATE TABLE vehiculos(
  id_vehiculo int AUTO_INCREMENT PRIMARY KEY,
  placa varchar(15),
  km float
  );
CREATE TABLE llantas(
  id_llanta int AUTO_INCREMENT PRIMARY KEY,
  llanta varchar(15),
  estado varchar(15)
  );
CREATE TABLE llevan(
  id_llevan int AUTO_INCREMENT PRIMARY KEY,
  id_vehiculo int,
  id_llanta int,
  posicion varchar(2),
  fecha_montaje datetime,
  FOREIGN KEY(id_vehiculo) REFERENCES vehiculos(id_vehiculo),
  FOREIGN KEY(id_llanta) REFERENCES llantas(id_llanta)
  );

Con estos datos de muestra:
INSERT INTO vehiculos (placa, km) VALUES
  ('1234 BHJ',23500),
  ('4567 DSK',50800);
INSERT INTO llantas (llanta,estado) VALUES
  ('B','Ok'),('A','Ok'),('C','Ok'),('D','Ok'),
  ('E','Ok'),('F','Ok'),('G','Ok'),('H','Ok');
INSERT INTO llevan (id_vehiculo, id_llanta, posicion, fecha_montaje) VALUES
  (1,1,'DI',NOW()),(1,2,'DD',NOW()),(1,3,'TI',NOW()),(1,4,'TD',NOW()),
  (2,5,'DI',NOW()),(2,6,'DD',NOW()),(2,7,'TI',NOW()),(2,8,'TD',NOW()),
  (1,1,'DD',NOW()+INTERVAL 36 HOUR),
  (1,2,'DI',NOW()+INTERVAL 36 HOUR);

Y esta consulta:
SELECT placa,llanta,posicion,fecha_montaje FROM llevan
  JOIN vehiculos USING(id_vehiculo)
  JOIN llantas USING(id_llanta)
  ORDER BY placa,posicion,fecha_montaje DESC;

Obtendrás el historial de llantas montadas en cada vehículo, de más reciente a más antigua:
+----------+--------+----------+---------------------+
| placa    | llanta | posicion | fecha_montaje       |
+----------+--------+----------+---------------------+
| 1234 BHJ | B      | DD       | 2021-02-21 20:28:24 |
| 1234 BHJ | A      | DD       | 2021-02-20 08:28:24 |
| 1234 BHJ | A      | DI       | 2021-02-21 20:28:24 |
| 1234 BHJ | B      | DI       | 2021-02-20 08:28:24 |
| 1234 BHJ | D      | TD       | 2021-02-20 08:28:24 |
| 1234 BHJ | C      | TI       | 2021-02-20 08:28:24 |
| 4567 DSK | F      | DD       | 2021-02-20 08:28:24 |
| 4567 DSK | E      | DI       | 2021-02-20 08:28:24 |
| 4567 DSK | H      | TD       | 2021-02-20 08:28:24 |
| 4567 DSK | G      | TI       | 2021-02-20 08:28:24 |
+----------+--------+----------+---------------------+

En cambio, si lo que buscas es saber en dónde ha estado montada cada llanta, puedes ordenar el resultado de la misma consulta de esta forma:
SELECT placa,llanta,posicion,fecha_montaje FROM llevan
  JOIN vehiculos USING(id_vehiculo)
  JOIN llantas USING(id_llanta)
  ORDER BY llanta,fecha_montaje DESC,placa,posicion;

Obteniendo:
+----------+--------+----------+---------------------+
| placa    | llanta | posicion | fecha_montaje       |
+----------+--------+----------+---------------------+
| 1234 BHJ | A      | DI       | 2021-02-21 20:28:24 |
| 1234 BHJ | A      | DD       | 2021-02-20 08:28:24 |
| 1234 BHJ | B      | DD       | 2021-02-21 20:28:24 |
| 1234 BHJ | B      | DI       | 2021-02-20 08:28:24 |
| 1234 BHJ | C      | TI       | 2021-02-20 08:28:24 |
| 1234 BHJ | D      | TD       | 2021-02-20 08:28:24 |
| 4567 DSK | E      | DI       | 2021-02-20 08:28:24 |
| 4567 DSK | F      | DD       | 2021-02-20 08:28:24 |
| 4567 DSK | G      | TI       | 2021-02-20 08:28:24 |
| 4567 DSK | H      | TD       | 2021-02-20 08:28:24 |
+----------+--------+----------+---------------------+

La posición de la llanta en el vehículo se codifica así:
DI - delantera izquierda
DD - delantera derecha
TI - trasera izquierda
TD - trasera derecha


text:
Q: How to change Ionic Action Sheet position? The Action Sheet is a slide-up panel that lets the user choose from a set of options. I want that but I need the options to pop-up in the middle of the screen, not the bottom.
I have tried to use $ionicPopup instead but they don't offer options like an Action Sheet, just alerts and confirmation boxes.
Either I change where does the Action Sheet or I change the what the $ionicPopup display.
Any ideas?

A: Your best option may be to design an $ionicModal that has the options you are looking for.
As far as I know the Action Sheet cannot be re-positioned and the $ionicPopup seems to function like an alert or confirmation box. $ionicModal appears much more customizable.


text:
Q: jaxb:bindings, Separating classes from wsdls (the same location, and different target namespaces). What about wsdlLocation attribute? I have two wsdls: ServiceA.wsdl(with targetNamespace='targetA'), and ServiceB.wsdl(with targetNamespace='targetB'). Both of them, are located in the same location, but each of them belongs to different target namespace.
I'd like to separate java sources generated via jaxb.
I use jaxb binding file:
  <?xml version="1.0" encoding="UTF-8"?>
    <jaxws:bindings xmlns:jaxws="http://java.sun.com/xml/ns/jaxws">
    <jaxws:bindings node="wsdl:definitions[@targetNamespace='targetA']"     xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"  wsdlLocation="../my_wsdl_location/ServiceA.wsdl">
    <jaxws:package name="package.serviceA"/>
    </jaxws:bindings>
    <jaxws:bindings node="wsdl:definitions[@targetNamespace='targetB']"    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" wsdlLocation="../my_wsdl_location/ServiceB.wsdl">
    <jaxws:package name="package.serviceB"/>
    </jaxws:bindings>
    </jaxws:bindings>

But it doesn't work. I get error :
"XPath evaluation of `"wsdl:definitions[@targetNamespace='targetA']"` results in an empty target node".

I guess, JAXB tries to evaluate XPATH  >>wsdl:definitions[@targetNamespace='targetA']<< for file ServiceB.wsdl, but what about attribute >>wsdlLocation<< ?
I think, it should indicate proper wsdl.
Where is my fault ?
Thanks for help.
Best regards
mario


text:
Q: Java Virtual Machine newbie Confusion: When is the virtual machine invoked while compiling java I am just starting to learn java to get into android programming
I assumed that everything that I compile using java gets compiled to java bytecode, which has to be interpreted by the virtual machine. so javac filename.java produces filename.class, which has the bytecode to be interpreted by the JVM (at least that's what I thought, I would run this class file using java filename.class). However, if I write something like this,
public class Arrays {
  public static void main(String[] args) {
    int[] a1 = { 1, 2, 3, 4, 5 };
    int[] a2;
    a2 = a1;
    for(int i = 0; i < a2.length; i++)
      a2[i]++;
    for(int i = 0; i < a1.length; i++)
      System.out.println(
        "a1[" + i + "] = " + a1[i]);
  }
}

it just displays some messages on the console and doesn't look any different than a C/C++ output. Is this really only like a C/C++ program, or is the VM still being invoked somehow in the background by Windows? I understand that the browser needs to have the VM installed for something like this to run
import javax.swing.*;
import java.awt.*;

public class Applet1 extends JApplet {
  public void init() {
    getContentPane().add(new JLabel("Applet!"));
  }
}

but what about other basic console based programs? And again, moving on to android, where exactly does the VM get invoked in it's case? Or should we consider the android OS as a very elaborate browser where the VM is running, and anything that we execute using our java code gets executed inside this VM?

A: Javac ( compile ) does not invoke the VM, It only converts your java codes to a bytecode. while Java ( runtime ) invokes the VM.
Just think JVM as an environment where you can safely execute your java program within your Operating System. Note that your java executable is the one that invoke the VM, which will running some task in your OS ( for example, Windows/Android kernel ).
This is why Java has a slogan "write once run everywhere" because as long as there is a JVM provided for an OS, the java bytecode will able to run in that OS.

A:
Is this really only like a C/C++ program, or is the VM still being invoked somehow in the background by Windows?

When you interact with the console, you can't distinguish whether it's a Java or c/c++ program. But it's true your java source code has been compiled to byte code (.class file) and then run on JVM. You know the command javac, and there's another command called java which starts JVM and run your program.
In your case, when you run your program, the IDE invokes command java and the latter starts JVM on windows. JVM can interpret System.out.println() to show content on console by calling windows API.

I understand that the browser needs to have the VM installed for something like this to run, but what about other basic console based programs?

In fact, we MUST install JVM on each OS before we can run any java program. For browser, it's just a plugin which calls the JVM installed on the OS. Like another windows media player plugin, you have to install a suitable windows media player first.

And again, moving on to android, where exactly does the VM get invoked in it's case? Or should we consider the android OS as a very elaborate browser where the VM is running, and anything that we execute using our java code gets executed inside this VM?

So, android OS is not a browser but an OS. It has integrated JVM, for you can run java program at once.

A: Yes, the .class file is JVM bytecode. The JVM (invoked by java foo for foo.class) interprets (some JVMs JIT the bytecode into native machine code at runtime) the bytecode.

A: Java compiler (javac) is implemented in Java, it's in jdk/lib/tools.jar. When we start javac it invokes JVM (JVM is implemented in native code, in case of Windows it's jvm.dll) and runs compiler classes with it.


text:
Q: Applications not showing on kubuntu I installed the kubuntu-desktop following this site on my ubuntu os (Ubuntu 16.04.2 LTS
). Now when i use kubuntu-desktop instead of unity I cannot view my applications on start menu

A: problem solved by installing muon by running sudo apt-get install muon. Its a possibility that I just rebooted the system and solved the issue, but the first thing to do is to install muon.


text:
Q: What are the benefits of writing code like this? I am reading an article, which is about flutter bloc programming. https://bloclibrary.dev/#/flutterfirestoretodostutorial
A Todo Class is defined as below in the article.
class Todo {
  final bool complete;
  final String id;
  final String note;
  final String task;

  Todo(this.task, {this.complete = false, String note = '', String id})
      : this.note = note ?? '',
        this.id = id;

  //... other code ...

I want to know the benefits of writing constructors like above, comparing to the following way. I found lots of similar situations on that site.
Todo(this.task, {this.complete = false, this.note = '', this.id});

Thanks.


text:
Q: Bash: Having 2 files, how do I check if a certain name in the first one also appears in the second Ok so, the problem is a little more complex than that
I have 2 files, let's say file1 and file2, each with the following data:
name of the game, hours spent playing it, last 7 days

file1:
game1 100 20
game3 40   5

file2:
game1 90  25
game4 40   2

Objectives:

*

*if a game is in both files, subtract the hours spent playing of file1 - file2

*If a game is only in file1, show it, but as the original (file1 - 0)

*If a game is only in file2, show it, but as the negative of the original (0 - file2)
How can I do this in bash?

A: Off-the-cuff answer, assuming the files are sorted:
awk '{$2= -$2; $3= -$3} 1' file2 |
  join -a1 -a2 file1 - |
  awk 'NF > 3 {$2+=$4; $3+=$5; NF=3} 1'

Output on provided input:
game1 10 -5
game3 40 5
game4 -40 -2

(If the files aren't sorted, just sort them and keep them sorted.  It will make things easier.)

Note that this uses only POSIX features of join and POSIX features of Awk, so it will work nearly anywhere.

$2 in Awk is a reference to the second field.  $3 is a reference to the third field (of each line of the file processed).  1 appearing outside braces {...} just means "true," so the default action of printing the line is performed.
Essentially the first Awk command just makes the numbers in file2 into negative numbers.
The join command joins file1 to the text provided on its standard input (what it receives from Awk).  The - after file1 in the join command (rather than another file name) means "use standard input."  The options -a1 and -a2 mean that any unpairable lines in either the first or second file are output as-is.
The final Awk command takes the lines that have been paired, i.e. lines where the Number of Fields is greater than 3 (NF > 3), and adds their fourth field to their second field, adds their fifth field to their third field, and then truncates the fourth and fifth fields.
Again, the final 1 outside braces is used to trigger Awk's default action, "print."
(See this tutorial for more and to learn Awk properly.)

There is a lot going on here.  I recommend running each part of these commands before adding the next part.   First:
awk '{$2= -$2; $3= -$3} 1' file2

and study and understand that.  Then:
awk '{$2= -$2; $3= -$3} 1' file2 |
  join -a1 -a2 file1 -

And study and understand that.  (Also try leaving out the -a1 and -a2 flags, or leaving out just one of them.)
Then use the full command:
awk '{$2= -$2; $3= -$3} 1' file2 |
  join -a1 -a2 file1 - |
  awk 'NF > 3 {$2+=$4; $3+=$5; NF=3} 1'

And see if it makes more sense.

A: Inelegant bash, join, and GNU sed variant:
join -a1 -a2 -o 0 1.2,2.2,1.3,2.3 file1 <(sed 's/ \([0-9]*\)/ -\1/g' file2) | \
sed 's/ -/-/g;s/[0-9]*-[0-9]*/$((&))/g;s/.*/echo &/eg'

Output:
game1 10 -5
game3 40 5
game4 -40 -2


text:
Q: local lan server i am facing a issue, i have installed ubuntu 17 version and in my computer which act like a local lan server. I am having two lan card one is connected to my DSL router for internet and another one is a ethernet connected to switch.
Second ethernet port actually shares the net. I know how to do this in windows but i am having a confusion.
In this local server i am having two ethernet port, one is inbuild and another one is link to switch.
i am looking for any suggestion regarding this.
configuration are as follows:

*

*ethernet port connected to internet router

automatic DHCP selected

*ethernet connected to switch

ip address : 192.168.0.1
subnet : 255.255.255.0
no gateway or gateway : 192.168.1.1
if i am pinging both ethernet ip from any node then its working fine. But from local server i cant ping any node.(for instance 192.168.0.18)
Saju


text:
Q: GIT merge with conflicts generated message appears I am learning how to work with Git. On windows with VS Code. I am learning merge with conflicts. After resolving commit conflicts, I will see an auto-generated commit message containing a list of conflicting files. It opens automatically in the built-in GIT terminal. There is nothing more I can do. I press :q or :wq it does not work. Everywhere they write that you just need to save, I don't know how to do it.

I saw on YouTube how one person opens a separate window in VS Code in which he can save this message and work further, but there is no way to set it up.
Please tell me what I need to do while in the terminal or how to set up the editor for such messages.

A: Check first your git config --global core.editor value.
I have set mine to "%LOCALAPPDATA%\Programs\Microsoft VS Code\bin\code" --wait
That should avoid vim, which is not well supported in the included Terminal console of VSCode.

A: Open VS Code for any type of Git message (e.g. git merge/git commit etc.) -
git config --global core.editor 'code --wait'

Open VS Code for diff tool -
git config --global diff.tool vscode

Open VS Code for merge tool -
git config --global merge.tool vscode

For more check this life-saving article - https://www.roboleary.net/vscode/2020/09/15/vscode-git.html


text:
Q: How to set the default font for a NSTextView? I'm using a textView with "Rich Text" option disabled to display some plain text. I can't find a way to set the default font. If I put in some text in IB (which I don't want anyway) I can then set the font in IB interface, but when users delete the font and start to type, the text changes to a different font and size. I read some questions and answers here and developer documentation without find a solution.

A: If you know the exact name of the font you want to use, like for this case "AvenirNextCondensed"
let tv = NSTextView()
tv.font = NSFont(name: "AvenirNextCondensed-Regular", size: 15.0)!

If you want to use the system font of size whatever, do it like this (where size is a CGFloat)
tv.font = NSFont.systemFont(ofSize: size)


text:
Q: Save data from spinner or Edit text based on selected item so i've got 13 items in spinner. I need to save data from spinner to SQLite database, it's not a problem BUT when i press the 13th item it means it will not save data from spinner but from edit text below. I will show you my code to be more specific.
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        if (position != 12 )
        {
            String hovno = (String) spinner.getItemAtPosition(spinner.getSelectedItemPosition());
            findViewById(R.id.editTextMaterial_A).setVisibility(editTextMaterial_A.GONE);
                          spinnerString = hovno;

        }
        if (position == 12)
        {
            String hovno = (String) spinner.getItemAtPosition(spinner.getSelectedItemPosition());
            Toast.makeText(MainActivity.this,"Vybrano "+ hovno, Toast.LENGTH_SHORT).show();
            findViewById(R.id.editTextMaterial_A).setVisibility(editTextMaterial_A.VISIBLE);

        }
    }

Like it will save values from spinner for all items except the 13th value, which will make edit text visible and save data from that edit text.
Have you got any ideas please? Like my problem is how to save the data to String called material_povrchuS.


text:
Q: Parametric Equation to find the Stationary Point The Picture
In University we learn the Parametric Equation. And in order to find the Stationary Point we use this formula. Could you please give a proof of it, and explain how these formula always works


text:
Q: MSI installer, using .exe without msi I'm using a MSI installer to create a setup for my application, and it generates 2 files, .msi and .exe. Now i know that the .exe is just a bootstrapper that actually runs the .msi, but my questions is if there is a way to reduce these 2 to one file only? (I wouldn't like to use zip to store both, like i currently do)
Also, i cannot use the .msi only because it has no "Run as Administrator" option, which is needed in this case. If i try to open the .exe only, i get the "Unable to locate application file '_____.msi'."

A: it all depends on what Setup Installer software you are using.
I have experience working with Advanced Installer and Installshield and in there you can define the final form of your build : msi , exe or both.


text:
Q: My servo motor doesn't move at all in python html, how can i fix this? My servo motor doesn't move at all in python html, how can i fix this?
    from tkinter import *
from bottle import route, run
import RPi.GPIO as GPIO
import time

host = '192.168.0.103'

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 100)
pwm.start(5)

a_pin = 17
b_pin = 27

def discharge():
    GPIO.setup(a_pin, GPIO.IN)
    GPIO.setup(b_pin, GPIO.OUT)
    GPIO.output(b_pin, False)
    time.sleep(0.005)

def charge_time():
    GPIO.setup(b_pin, GPIO.IN)
    GPIO.setup(a_pin, GPIO.OUT)
    count = 0
    GPIO.output(a_pin, True)
    while not GPIO.input(b_pin):
        count = count + 1
    return count

def analog_read():
    discharge()
    return charge_time()

def ldr_status():
    if ((int(analog_read())) > 30000):
        return ('Dark , LDR reading: ' + (str(analog_read())))
    elif ((int(analog_read())) < 30000):
        return ('Bright , LDR reading: ' + (str(analog_read())))

def window_status():
    state = pwm.ChangeDutyCycle(5)
    if state == pwm.ChangeDutyCycle(5):
        return 'Opened'
    else:
        return 'Closed'

def html_for_window():
    result = "<input type='button' onClick='changed()'value='WINDOW'/>"
    return result

def update_windows():
    pwm.ChangeDutyCycle(5)
    pwm.ChangeDutyCycle(25)

@route('/')
@route('/<window>')
def index(window="n"):
    if window != "n":
        update_windows()
    response = ""
    response += '
ASSIGNMENT
'
    response += '
WINDOW = ' + window_status() + '
'
    response += '
LDR Status = ' + ldr_status() + '
'
    response += html_for_window()
    return response

run(host=host, port=80)

the program runs okay without error, but when i try to change the servo motor into direction that i have set, it doesnt move at all. im very bad at html stuff. can anyone fix this, thanks. i tried to figure it out but seems every solutions likes to use sliders while i like to use click button where it change into 2 directions only, like how led light up and turn off.


text:
Q: How can I parse human formatted and typed text tables with a lot of variation in Java, and if regex is the answer how to properly get row values? I have to parse an extremely varied user input. An example would be:
Example 1:
March
    Morning     Evening
    (Avg Count) (Avg Count)
Birds    5.6          10.35
Mammals  2.0          3.3

Example 2:
March
    Morning   Afternoon Evening
     (Num)     (Num)     (Num)
Birds    5.6       9        10
Mammals  2.0       2.5      3.3
Reptiles 1.0       5.6      1.75

Status Avg Total: Birds 24
Concerning that numbers have dwindled since last year

Example 3:
    Early     Mid       Late
    (Count)   (Count)   (Count)
Mammal   2.0       2.5      3.3  (Count)
Reptile 1.0    5.6      1.75  (Count)

Ideally user input would be standard, but that's just not
going to happen right now. In lieu of that, what would be
the best way to parse user input?
My current strategy is using Java's pattern matcher classes.
I'm using matcher.matchers() to test if the formatting of the header
is a possible format. Based on that I send the text to a method that uses matcher.find() to
get capture groups from the row. It would pull out the row name (ex. mammal) and the values
say 2.0, and 3.3 from the first example out of the text. However, the user input is so varied,
that this method is very finicky.
For instance, I initially was pulling out the Birds 24 from example
2 as a capture group, because in the text it contains a similar format as the column. So I changed it to not allow any text but the row name in the line. However, now it can't pull out rows like example
3 with (Count) next to it.
So my current approach is, check the header format using regular expressions. If a format, pull
out the row name and values. Even with that strategy, I am having trouble finding the right regex to
get the row proper row and values.
My current regex for matcher.find() is this:
(Mammal|Reptile|Bird|Mammals|Reptiles|Birds)(^a-zA-Z-]*?[0-9])\r\n|[\r\n]

Where capture group 1 would be the row name and group 2 should be the numbers
So I have two questions:
Is there a better way to approach this problem?
If there isn't a better way, what would be the right regex expression to pull out the row and it's values?

A: You could use 2 capturing groups where the first contains the row name like Birds and a repeated match for group 2 which contains the numbers using the \G anchor.
Note that you could add an optional s using s? to match Mammal or Mammals etc.
(?:^(Mammals?|Reptiles?|Birds?)|\G(?!^))\h+(\d+(?:\.\d+)?)

*

*(?: Non capturing group

*

*^ Assert start of the string

*(Mammals?|Reptiles?|Birds?) Capture group 1 match any option

*| Or

*\G(?!^) Assert the position at the end of the previous match

*) Close non capturing group

*\h+ Match 1+ horizontal whitespace chars

*( Capture group 2

*

*\d+(?:\.\d+)? Match 1+ digits and an optional part to match the decimals

*) Close group 2

Regex demo | Java demo
In Java
final String regex = "(?:^(Mammals?|Reptiles?|Birds?)|\\G(?!^))\\h+(\\d+(?:\\.\\d+)?)";

Note that instead of using \d+(?:\.\d+)? to match the digits, you could might use \S+ to create a broad match matching 1+ times a non whitespace char.


text:
Q: Using C++ but not using the language's specific features, should switch to C? I'm developing a NES emulator as a hobby, in my free time.  I use C++ because is the language I use mostly, know mostly and like mostly.
But now that I made some advance into the project I realize I'm not using almost any specific features of C++, and could have done it in plain C and getting the same result. I don't use templates, operator overloading, polymorphism, inheritance. So what would you say? should I stay in C++ or rewrite it in C?
I won't do this to gain in performance, it could come as a side effect, but the idea is why should I use C++ if I don't need it?
The only features of C++ I'm using is classes to encapsulate data and methods, but that can be done as well with structs and functions, I'm using new and delete, but could as well use malloc and free, and I'm using inheritance just for callbacks, which could be achieved with pointers to functions.
Remember, it's a hobby project, I have no deadlines, so the overhead time and work that would require a re-write are not a problem, might be fun as well. So, the question is C or C++?

A: Even if you don't use C++ specific features, a C++ compiler will catch more problems than a C one due to the stricter type system of C++.

A: I would look at it from the other direction. Will you gain anything by rewriting the code in C? Even on a purely hobbyist project, there's a cost associated with a rewrite like that. If nothing else there's what I suppose would be called opportunity cost -- i.e., the other things you could have done in that time if you weren't wasting your time rewriting it in C.
Bottom line: unless you think the code is really likely to be used in some environment where access to C++ is really limited (or nonexistent), it would be a pointless waste of time at very best. At least in my experience, it usually goes well beyond that very quickly -- thinking back over code I've written in C++ that had to be converted to C, I can pretty clearly remember that even in quite a few cases where it seemed like it should be trivial, I was using a lot more features specific to C++ than I initially realized. To have much hope of being useful at all, you'd pretty much have to target C89/90, in which case you quickly get reminded of things like having to define all variables at the beginning of a block instead of where they're actually used.
In short, unless you're pretty sure rewriting in C will provide a real benefit, there are almost inevitably a lot better things to do.

A: You aren't using it now, but the next time you leak memory or get a double delete, you'll be begging to come back to std::vector<T>, std::unique_ptr<T, Del> and std::shared_ptr<T>, which can solve those problems easily- almost trivially. That's what happens to everyone who uses C over C++, eventually, and the smarter ones just don't wait for the bugs to pop up before moving over.
Code that uses new and delete directly doesn't really belong in C++, it belongs in that kind of half house that we refer to as "C with Classes". That's where the language was circa 1985. It's not particularly similar to C++, circa 2011. In all likelihood, wherever you learned C++ simply didn't teach it very well- something that is unfortunately rather common- and with a better education, you would find use of these features.
Specifically, as I listed above, C++'s generic data structures and the resource-managing classes simply are fundamentally massively superior to anything C has to offer. If you want a dynamically allocated array, then use std::vector<T>. That's a pretty common use case. If you aren't using them, then your code is at huge risk of error unnecessarily- especially resource management related. C++ can guarantee safety and re-use code in a way that C can never touch.
However, I think that you also might be expecting too much. Writing templates and operator overloads is not common for library consumers. If your code uses std::vector<T>, you don't need to write a template to make that happen. If your code uses std::string, nobody is forcing you to overload your operators. You only have to do those things to write std::vector<T> and std::string- but you can still take full advantage of them.
Polymorphism/inheritance also only has a specific use case. If your code happens to not require you to write any templates or use virtual functions, then it doesn't, and there are programs or segments of programs where you don't need to write your own templates.
Also, there's no gain in performance in C over C++.

A: It's not easy to answer your questions, since we don't know if you are working on the project to improve your language specific skills (C vs C++) or to improve other programming skills (design, problem-solving, etc.).
"The only features of C++ I'm using is classes to encapsulate data and methods, but that can be done as well with structs and functions,". This is not true. structs in C do not support encapsulation and cannot contain functions (methods) - at least not without using techniques like pointers to functions. Also, functions in C are weaker because they cannot be overloaded.
"I'm using new and delete, but could as well use malloc and free, and I'm using inheritance just for callbacks, which could be achieved with pointers to functions.". As deadmg mentioned, using directly new and delete in C++ is not encouraged. Also, IMHO (and the GoF) inheritance in OOP should be preferred over composition only when polymorphism is required. And I don't think that it is trivial to achieve polymorphism (late binding) in C using pointers to functions.
Other than that, I'll not try to convince you that C++ is "better" than C because it's a matter of preference and it always depends on the problem that you are trying to solve (using OOP features for developing your NES emulator might be a good idea).

A: As a more general answer:
Do not switch to C++ just because you are using some of it's more unique features. One day you may need those features, and will just pound your head because you are using C.

A: For hobbyist development, I would consider switching back to plain C.  C and C-like languages are more likely to be supported on tiny hobby development modules.
Many of the answers here might be from professional software types.  As a hobbyist, you won't be coding continuously or full time.  So consider which language you are more likely to remember or forget the quirks within, if you table your project for a year and then come back and try to read your code after you have gotten rusty in coding.  C++, having a richer feature set, may take more or less time to re-acquire, depending on your coding style.

A: I am a very beginner, so here comes my 2 bits.
I am learning C and C++ at Wibit.net with some nice basic videotutorials, maybe they can help you a lot to take a overview of the "situation" (not an ad!)
I advice you to change to C, just to learn, as you are a hobbyist, this will be a pleasure, not a problem.
I advice more. Do it in both languages. Compare the way and solutions you will find and use. I am sure it will be not "so easy" as you are expecting... but sure you will learn a lot!

A: Here's pros and cons of C++ vs. C:

*

*Moving to C would make it easier to stay within the chosen C++ subset, because compiler would then give error when you go outside of it. If the main problem is with staying within decided subset, this alternative should be chosen. (why don't we have compiler support for this?)

*Once you can stay within chosen c++ feature subset, then next thing is to try to change the subset to get rid of bad conventions which break the code. This requires use of whole c++.

*Once you have both "staying inside subset" and "it's a good subset", then move outside of c++ features, and start thinking about requirements.


text:
Q: Print result at the end of mongodb query I have written this command into robomongo:
db.FinalLocation.find({UserName: null}).forEach(
function (obj)
{
    db.tempColl.save(obj)
});

Now, I want to know how many documents Have been found into FinalLocation collection and how many documents Have been inserted into tempColl collection?
I know by db.tempColl.count() can find but I want, at the end of my script appear something like this:
Total empty object : 36 ---> at FinalLocation
Total inserted object : 36 ---> at tempColl

A: I finally solved this problem:
this is my code:
var result = db.FinalLocation.find({UserName: null}).toArray()
print("Total empty object: "+ result.length);

var t = db.tempColl.insertMany(result);
print("Total inserted  object: "+ t.insertedIds.length);

This outPut:
Total empty object: 36
Total inserted  object: 36


text:
Q: Using FileHistory on Windows 8 to backup to a specific folder on a network drive How can I backup my windows 8.1 desktop to a specific folder on a network drive using the built in FileHistory? The entire drive is not just for my backup, so I want to backup under a specific folder:
Z:/mynetworkpiece/desktopBU/{BACKUP HERE}

But FileHistory seems to only lets me choose the entire drive, meaning it tries to create the backup at the root Z:/ as such
Z:/{BACKUP HERE}

A: If you have z: mapped to \\server\myshare create another mapping to the folder where you want to store the backups. For instance you can map Y: to \\server\myshare\desktopBU then configure the backup for the y: drive.

A: I am able to select or create a directory to use when adding a network location. If you're selecting an existing one try and create a new one.
Also, win8 is strange in that it has FileHistory and SystemRecovery instead of 7's Backup and Restore wizard. It sounds like its file history you want though.

A: To rephrase what @Bin said, you can map a drive deeper inside a shared path than its root.  For instance, let's say you have a server SERVER, which has a share SHARE, which has a folder FOLDER inside, which has another folder DESKTOPBU inside.  On the desktop, map Y: to \SERVER\SHARE\FOLDER\DESKTOPBU and set it to reconnect Y: every time you log in.  Now, start your FileHistory again, and tell it to use Y: .


text:
Q: Building qt creator from scratch: after mingw32-make clean step, *.pluginspec are removed I have compiled QT 2.3.1 from source. Here is the process:
cd c:\qtcreator
qmake c:\qtcreatorsrc\qtcreator.pro -o c:\qtcreater\Makefile -spec win32-g++ -r CONFIG+=release
mingw32-make release

After this, the qtcreator was compiled succesful and I was able to run it. Then I decided to clean all object files that are not needed anymore and I have done:
mingw32-make clean

After this, I was not able to start qt. The message I get is: "Failed to load core: Could not find 'Core.pluginspec' in C:\QtCreator\lib\qtcreator\plugins,C:\QtCreator\plugins"
After short investigation I have noticed that clean step has really removed all *.pluginspec files from lib\qtcreator\plugins. Is this bug in generation of makefile? Have I done something wrong?
I could skip clean step, but I see no point in keeping all object files since they occupy more then 1GB of disk space.


text:
Q: Why the python codes executed with a wrong execution sequence when use nc to connect? Here is a test.py file:
#!/usr/bin/python
print "hello"
a=raw_input()
print a

when use ./test.py to run this file,it will first print 'hello',and then ask me to input a ,and finally print a,there is nothing wrong,it works like that:
> hello
> 123
> 123

And of course it works correctly.
But when i want to use netcat to connect this py file,first i execute:
socat tcp-l:9991,fork exec:python test.py
And then i use another shell in the local machine to connect the py file:
nc 127.0.0.1 9991
Then the py file will first ask me to input a instead of printing 'hello',and after i input a,it will then print 'hello' and finally print a,it works like that:
> 123
> hello
> 123

And obviously it is a wrong execution sequence,so i wonder why this thing will happen? And what should i do to fix this problem and let it run with a correct sequence when i use nc to connect it.Thank you very much!

A: With print statement you are writing to the output stream, but you don't flush it immediately by default. Try something like this:
#!/usr/bin/python
import sys

print "hello"
sys.stdout.flush()
a=raw_input()
print a
sys.stdout.flush()

This will force it to display anything that is in stdout buffer.


text:
Q: How do I insert a javascript variable into a model in Django? I'm trying to save the longitude and latitude of a user to a model to use with various API's for things like traffic and weather and what not. I get the users latitude and longitude by using the navigator.geolocation that is in html5. What is the best way to save this info to a UserProfile model?
I've tried setting up a form to use but can't get anything to work with the check box I have that enables geolocation. I've also thought of using ajax but don't know how to pass the data to the model in django.

Notice the extra csrftoken javascript functionality.
This is just one way to do it. There are better ways of course by using the django-rest-framework


text:
Q: How to access GUI elements from a class in C#? I have windows application in C# and have a richtextbox in the GUI. I want to reach the richtextbox and append some text to it from inside a class. I thought about creating a static RichTextBox item in the form's code file and then call it like this:
public partial class Form1 : Form
{
    public static RichTextBox box;

    public Form1()
    {
        box = richtextbox_in_gui;
    }
}

public class SomeClass()
{
    Form1.box.AppendText("...");
}

Is that a safe way to do it? Or is there any other way i can do this?
Thanks

A: You don't want a static field, as that would be for all instances of Form1; it should be a normal field.
However, public fields are not a good idea, as the class can be manipulated from the outside. You'll want to encapsulate the behaviour, so the best idea is a method:
public partial class Form1 : Form
{
    public Form1()
    {
        box = richtextbox_in_gui;
    }

    public void AppendText(string text)
    {
      this.textbox.AppendText(text);
    }
}

public class SomeClass
{
  private Form1 form;

  public SomeClass(Form1 form)
  {
    this.form = form;
  }

  public void AppendHelloWorld()
  {
    this.form.AppendText("Hello World");
  }
}

Now, if you have a reference to the form object, you can use the AppendText method:
Form1 form = new Form1();
var some = new SomeClass(form);
some.AppendHelloWorld();

This style of coding is called Dependency Injection.


text:
Q: Rails select and submitting a 2nd value I am using the select method in my erb here:
<%= select(:user_action, :user_id, @basic_users.map {|v| [ v['first_name'] + ' ' + v['last_name'], v['id'] ] }) %>

...and this works great. The select box shows me the users name, and submits the id just like I want. However, I have another field in my model for the user_name that I would also like to save. Any ideas on how I might do this? Hidden field maybe? The idea is that my UI looks the same...the user would choose based on the concatenated first/last name, but on submission the id is saved to the user_id field, but the name would also be saved to the user_name field.
In my mind I'd like to add something like...
<%= hidden_field :user_action, :user_name, value: v['first_name'] %>

..but for obvious reasons this doesn't work...it doesn't know what v is.

A: You can either use javascript to update the hidden field value when you make the selection or you can handle it in your controller by looking up the user with the id you submitted.


text:
Q: Inserting a side col inside the content when going mobile (bootstrap 3) I have a layout like so in md/lg (pardon the horrible pain):

In sm/xs my designer wants it to become:

My current markup is:

        content1

        content2

      side col

      side col

      side col

      side col

      side col

      side col

      side col

Obviously with this the side col gets below the contents, not between.
I've tried a lot of things, I don't think it's doable in pure CSS/HTML, unless I use a duplicate column that's visible-xs only and make the other one hidden-xs...
Any ideas ?
Thanks!

A: Yes, you can do it, just add class pull-right and re-order your col like this

        content1

      side col

      side col

      side col

      side col

      side col

      side col

      side col

        content2

DEMO (resize the width and you can see the cols change)


text:
Q: Загрузка файлов на Google Drive по URL Подскажите, есть ли возможность грузить файлы на Google Drive прямо по URL?
К примеру есть файл http://site.ru/catalog/file.xxx
Возможно ли загрузить его сразу на Google Drive?
Из локальной понятно как, но вот как отправить ему URL и чтобы он скачал файл сразу на диск непонятно.


text:
Q: c++ header wrapper declaration in cython char array[] convert some part of C++ header files:
virtual int SubscribeMarketData(char * ppInstrumentID[], int nCount, char* pExchageID) = 0;

some part of *.pxdfiles declaration:
int SubscribeMarketData(char *ppInstrumentID[], int nCount, char *pExchageID) except +

but I can't make sure some of the c++ char * ppInstrumentID[] code declaration in cython.
What's the right code declaration?
how about in the *.pyx files?

A: cdef char[] *thing

It actually makes way more sense this way, but it's confusing to work between the two (especially as error messages use C's form!).


text:
Q: Scrollviewer not scrolling without height I am writing a Windows Phone 8.1 app (WINRT).
I have implemented a scrollviewer in page. It contains a stackpanel having richtextblock with long texts, and a button.
But the problem is that this scrollviewer is not scrolling at all. If i am manually setting a height to this scrollviewer it is scrolling but it looks ugly on higher resolutions. How to make this scrollviewer work without having manual height to it.
<ScrollViewer Name="WhyJoin_User_Content_Scroll"
                              Margin="0,10,0,10"
                              VerticalScrollBarVisibility="Auto"
                              >
<StackPanel Orientation="Vertical">
    <RichTextBlock Name="WhyJoin_User_Content_RichTextBlock"
                    FontWeight="Light"
                    Margin="20,10,20,0"
                    Foreground="{StaticResource DefaultTheme_DarkBlueColor}"
                    FontSize="19"
                    TextWrapping="Wrap"
                     TextAlignment="Justify">
        <RichTextBlock.Blocks>
            <Paragraph>
                <Paragraph.Inlines>
                    <Run Text=" Text Text Text Text Text Text Text Text ">
                    </Paragraph.Inlines>
                </Paragraph>
                <Paragraph>
                    <Paragraph.Inlines>
                        <Run Text=" Text Text Text Text Text Text Text Text ">
                        </Paragraph.Inlines>
                    </Paragraph>
                    <Paragraph>
                        <Paragraph.Inlines>
                            <Run Text=" Text Text Text Text Text Text Text Text "></Run>
                        </Paragraph.Inlines>
                    </Paragraph>
                    <Paragraph>
                        <Paragraph.Inlines>
                            <Run Text=" Text Text Text Text Text Text Text Text "></Run>
                        </Paragraph.Inlines>
                    </Paragraph>
                    <Paragraph>
                        <Paragraph.Inlines>
                            <Run Text="i: Practice work hours of experts"></Run>
                        </Paragraph.Inlines>
                    </Paragraph>
                    <Paragraph>
                        <Paragraph.Inlines>
                            <Run Text="ii: Address, Phone numbers etc."></Run>
                        </Paragraph.Inlines>
                    </Paragraph>
                    <Paragraph>
                        <Paragraph.Inlines>
                            <Run Text="iii: Appointment requests"></Run>
                        </Paragraph.Inlines>
                    </Paragraph>
                    <Paragraph>
                        <Paragraph.Inlines>
                            <Run Text=" Text Text Text Text Text Text Text Text "></Run>
                        </Paragraph.Inlines>
                    </Paragraph>
                </RichTextBlock.Blocks>
            </RichTextBlock>
            <Button
                        x:Name="ButtonWhyJoin_User_Register"
                        BorderThickness="0"
                        Width="150"
                        Height="70"
                            Margin="0,10,0,0"
                            HorizontalAlignment="Center"

                        Click="ButtonWhyJoin_User_Register_Click"
                        FontWeight="ExtraLight"
                        Background="{StaticResource DefaultTheme_DarkBlueColor}"
                        BorderBrush="{x:Null}"
                        Style="{StaticResource ButtonStyleYesNo}"
                        Foreground="{StaticResource DefaultTheme_BackgroundColor}"/>
        </StackPanel>
    </ScrollViewer>

A: The easiest way to solve your problem is to bind the height and/or width of the scroll viewer to the ContentRoot. This is easiest done in Blend, by doing this whatever the screen resolution you will automatically achieve the desired height.
http://pho.to/8kh1T
This is what the XAML would look like
<ScrollViewer HorizontalAlignment="Left" Margin="0" VerticalAlignment="Top" Width="175" Height="{Binding ActualHeight, ElementName=ContentRoot}"/>