Preciso inicializar a variável com o valor 0, por quê?

Question: import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int codigo, quantidade;
        double preco;
        Scanner sc = new Scanner(System.in);
        codigo = sc.nextInt();
        quantidade = sc.nextInt();
        sc.close();
        switch (codigo) {
        case 1:
            preco = 4.0 * quantidade;
            break;
        case 2:
            preco = 4.5 * quantidade;
            break;
        case 3:
            preco = 5.0 * quantidade;
            break;
        case 4:
            preco = 2.0 * quantidade;
            break;
        case 5:
            preco = 1.5 * quantidade;
            break;
        }

System.out.printf("Total: R$ %.2f%n", preco);
    }

}

No treco de código System.out.printf("Total: R$ %.2f%n", preco); indica um erro que no trecho de inicialização da variável preco double preco; preciso inicializar ela com o valor 0 double preco = 0 mas por que não posso inicializar ela sem o valor 0? Indica esse erro:
Exception in thread "main"
java.lang.Error: Unresolved compilation problem:
    The local variable preco may not have been initialized
at Main.main(Main.java:29)

Answer: Você não precisa inicializar preco com 0, mas você precisa garantir que essa variável será inicializada antes de você printa-la na tela.
Veja que no seu código você inicializa preco dentro de um switch, mas isso só ocorre se o valor de codigo for igual a 1, 2, 3, 4 ou 5.
E se o valor de codigo for 6? preco não será inicializado, e portanto o compilador te retorna um erro.
Você pode adicionar uma cláusula default para garantir que codigo sempre será inicializado, dessa forma o compilador irá aceitar o seu código.
switch (codigo) {
case 1:
    preco = 4.0 * quantidade;
    break;
case 2:
    preco = 4.5 * quantidade;
    break;
case 3:
    preco = 5.0 * quantidade;
    break;
case 4:
    preco = 2.0 * quantidade;
    break;
case 5:
    preco = 1.5 * quantidade;
    break;
default:
    preco = 0;
}

Você também pode tratar isso de outra forma, como retornar uma mensagem de código inválido para o usuário, apenas garanta que preco seja inicializado de alguma forma.


Value not incrementing in mongoose when creating a new object

Question: Here is my code, I want to increment the total no of counts as soon as any user gives the rating. But the $inc command is not running and result is showing the default value which I set zero.
The given is my Schema.
const mongoose = require('mongoose');

const schema = mongoose.Schema;

let Rating = new schema({
    user_id:{
        type:mongoose.Types.ObjectId
    },
    stars:{
        type:Number
    },
    ratingCount:{
        type:Number,
        default:0
    }
})

const rating = mongoose.model('Rating', Rating);
module.exports = rating;

This is the function where I want to increment the value.
const express = require('express');
const Router = express.Router();

let Rating = require('../model/rating');

Router.route('/add/:userid').post((req,res)=>{

    new Rating({
        user_id: req.params.userid,
        $inc: {ratingCount:1},
        stars: req.body.stars
    })
    .save()
    .then(rating=>res.send(rating))
    .catch(err=>console.log(err));

});

module.exports = Router;

Result showing default value of ratingCount.
Comment: Please do not include pictures, have code in text format !! Do you wanna set `req.body.stars` to `stars` & inc `ratingCount` at sametime ?
Comment: yes thats what I want
Comment: I have updated the format
Answer: You need not to use .save() instead you can simply use .findOneAndUpdate() with option { new: true } to return updated document, if it doesn't find any matching document .findOneAndUpdate() will return null.
Code :
const express = require("express");
const Router = express.Router();
let Rating = require("../model/rating");
Router.route("/add/:userid").post((req, res) => {
  Rating.findOneAndUpdate(
    { user_id: req.params.userid },
    { $inc: { ratingCount: 1 }, stars: req.body.stars },
    { new: true }
  )
    .then((rating) => res.send(rating))
    .catch((err) => console.log(err));
});
module.exports = Router;

Usually .save() will track changes to document which is returned from find call. Otherwise if it's not the mongoose document returned from .find() call if it's the mongoose object which you're forming like what you're doing now then if it finds _id in object it will update the matching doc else if no matching doc exists with _id or no _id present in request it will insert the new document.


How many times can I call Socket.BeginAccept in C#

Question: I am coming from Java programming language. I am just beginning my adventure with C# and .Net.
I am creating a Server socket application using C# - based on Microsoft example (https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example).
This is the sample code (from the page above):
while (true)
{
    // Set the event to nonsignaled state.
    allDone.Reset();

    // Start an asynchronous socket to listen for connections.
    Console.WriteLine("Waiting for a connection...");
    listener.BeginAccept(
        new AsyncCallback(AcceptCallback),
        listener);

    // Wait until a connection is made before continuing.
    allDone.WaitOne();
}

... where allDone is a ManualResetEvent defined in the class scope.
I can't understand what actually listener.BeginAccept does. For instance if I don't call method allDone.WaitOne() to wait until connection is made, then what would have happend - how many times the call to listener.BeginAccept method would execute (be successful) inside the loop until it starts waiting (or maybe it would crash eventually). I am probably missing something here. Can someone explain this to me please?
Regards,
Janusz
Comment: This is the legacy Async Mechanism. BeginAccept starts an accept asynchronously and returns immediatly. So if you leave out the WaitOne() this will spin until an exception occurs. As is, I guess the MRE will be set in the AcceptCallback, which will be called when a Client is trying to connect. I'd suggest to use the Task Async Pattern in favor of this outdated mechanism.
Comment: Couldn't delete the last sentence any more. I thought there would be a Task Async API to socket, but there isn't.
Answer: The intent here is for the AcceptCallback method to set the allDone event when a connection is accepted. The loop can then go on to accept another incoming connection while the just accepted one continues with whatever it needs to do.
You could have done other useful work on the listening thread after the call to BeginAccept, if you had any that made sense.
Oddly the documentation does not explicitly state (that I could find) what happens if you just repeatedly call BeginAccept without waiting, but my recommendation would be to not do that.
Comment: I've inadvertently found the answer for the last paragraph - if you keep calling BeginAccept you end up with a slow memory leak and eventual crash with an unmanaged exception.
Comment: Thanks for the reply. So what would you suggest to use instead of Microsoft example?
Comment: The example is fine, I think, as a guideline, just keep the event logic.
Comment: Is there a better API to use for server Socket in C# or this is the only one?


Sandbox any file access on linux

Question: Is there a program that could sandbox any file access from another program in LInux?
The equivalent of what I want in Windows are: Sandboxie.
I intended to use it to trace any files accessed/changed when I run a program on my server.
Answer: You can use strace to monitor what a program is doing. Limit the listed operations with -e trace=file and see the man page for the program. Note however, that the list will include all file operations, including the ones to read shared libraries.
Beside that, you can look into the inotify infrastructure of the kernel which is more usable for extended operations, as strace is mainly a debugging tool.
Answer: This might be case where unionfs might be useful.  With unionfs, you should be able to mount things in such a way to treat the primary filesystems as read-only and redirect all file writes/modifications into another directory or filesystem.  This is the tool commonly used on livecds to save changes to a USB stick or other storage device.
Another option if you are using LVM and you have free extents would be to take a snapshot.  Run your program, then compare everything on your filesystem against what was within the snapshot.

Sandbox any file access on linux


Google Cloud Storage Fuse vs GlusterFS, pros, cons and costs

Question: I'm setting up some web servers on Google Cloud Compute and I need a directory synced between all the servers to keep the web sites in sync.
I'd also like to use the autoscaling feature to provision new servers when needed.
I realise GlusterFS would need to know about all instances but my idea would be to setup monitoring from each server and on new/removed server events auto update the configs. (havent tried this yet though)
Has anyone had experience with either of these systems? If so, how did maintaining either go, and what costs are involved, as I'm not sure if GlusterFS would cost any extra other than the drives it's on, while Google Cloud Storage FS costs for the storage plus for the api commands it runs.
Answer: I have used GCS Fuse as a shared directory to a web server before, and I found that it's latency was unacceptably high and that it's transfer speed was a slow when serving files through nginx.
I don't have any experience with GlusterFS, but if you're trying to host shared files for a small to medium traffic website, NFS will perform faster than GCS Fuse with less configuration than GlusterFS.
I currently run a NFS v4 Container VM inside of Google Compute Engine with a persistent disk backing the /exports directory and it works very well.  The NFS VM could be implemented on a f1-micro instance with a 100GB Standard Persistent Disk for under $10/month.  I'd recommend at least a n1-standard-1 instance and consider using SSD backed Persistent Disk for production.  I've posted a gist for creating a NFS VM on GCE
Comment: Had to modify `privileged.sh` to `sed -i 's/DAEMON_ARGS="/DAEMON_ARGS="--cloud-provider=gce --allow-privileged=true /g' /etc/default/kubelet` to get around this: [Container-VM Image with GPD Volumes fails with "Failed to get GCE Cloud Provider. plugin.host.GetCloudProvider returned  instead"](http://stackoverflow.com/questions/37421540/container-vm-image-with-gpd-volumes-fails-with-failed-to-get-gce-cloud-provider)


Is it possible to upgrade entry level guitar to a professional one?

Question: I have old Ibanez GIO Fat-Strat copy and I somewhat like it (the colour and body shape). The frets are worn and keys (tuning machines) are bad quality. Will replacing whole neck (with keys and nut) and electronics with professional quality parts make it feel and sound like expensive one?
By this I mean, will it have good sound clarity, low string action and will I be able to use the tremolo bridge without detuning guitar?
Regarding the question about motivation: I would like to upgrade the guitar in steps and not spend a whole bunch of money at once.
Comment: Upgrading the pickups will certainly make it sound better. I don't think changing the neck will do much for the sound. It will make it feel better.
Comment: If you spend that much money replacing the neck and the electronics, why not just buy a new or higher quality used guitar?  Of course the guitar will sound different with different electronics and play different with a new neck.  Not so sure about the tremolo system.
Comment: @RockinCowboy I had bad luck on second hand market while buying things. Anyway used guitars are quite expensive in place I live (90% of shop price)
Comment: IMO, the neck is a major part of the playability of the instrument. If you're generally comfortable with the neck you have (width, profile, finish), I would recommend that you take the instrument to a luthier and have him do a fret job - grinding down the frets until they're level again, or putting in new ones if needed. A professional fret treatment is what allows for low action without excessive fret buzz, and there's no guarantee that a new neck will have come with a good fret setup. Replacing the tuners afterwards is a low-risk affair.
Answer: Short answer: Yes, but...
The first guitar I bought was a Peavey Predator, a bottom-of-the-line, budget Strat clone. Several years later I came across a good deal on Fender Custom Shop Strat pickups, so I got them to put in the Predator. Yes, it did improve the sound a lot, but like your guitar the frets were very worn, the tuning machines were terrible, and the sound still wasn't quite right. So, I bought a new neck online and new locking tuning machines. That improved the playability and feel a lot, although it didn't do much for the tone. But now I play that guitar a lot more often than I used to and I've used it on stage and in recordings before.
So yes, you can piecemeal upgrade a Strat copy and get incremental improvements as you go.
There are some caveats, though:

Parts won't always fit just right. I had to play around with the pickup covers on the Fender Custom Shop pickups because they didn't quite fit in the Peavey pick guard slots and the Peavey pickup covers wouldn't fit over the Fender pickups. I also had to shape and trim a piece of wood to go between the neck and body because the Peavey neck slot is about 3/8" deeper than a Fender Strat neck slot.
The tone is better, but not yet where I want it to be. Everything affects tone, so I would have to replace the bridge, pick guard, electronics, and body before I would really get a huge improvement in sound. That's the same as a whole new guitar.
The neck I bought came with a pre-slotted nut (not all do) but the slots were cut very shallow (very high action) since the neck manufacturer has no idea what kind of action people want or need or what works for the guitar. I actually have played around with guitar building so I had some nut slot files and I was able to deepen the nut slots fairly well to make the action playable. Others may have to take the new neck to a pro to have the nut slots adjusted which adds to the cost of buying a neck.
In your particular situation, if you buy a standard Strat clone neck, it won't help very much, if at all, with detuning when you use the vibrato tailpiece. Using locking tuners and getting very smooth string trees would help more, as would a graphite nut (which would probably have to be professionally shaped). Or you could get a neck with a Floyd-Rose style locking nut and that would make a huge difference in tuning stability, but you'd probably have to replace the bridge also, since locking nuts require tuning adjustment at the bridge.
In the end, once you have replaced all of the parts of the guitar, it probably won't be quite as good as if you had saved up and bought a higher end guitar all at once, and it will cost about the same or even a little more (based on some math I've done over the years to see if it's really worth it). If that's a concern for you, I would suggest you make your own calculations, but I think you'll find it's not the best possible way to end up with a better overall guitar.
Comment: Thanks for answer. I will do hybrid solution. I will fix the most terrible things: tuners and the nut and save some money for second guitar
Answer: If you LOVE the guitar getting it set up properly and fitting new parts will improve its playability. But it will still be a cheap guitar.
PS even cheap guitars can sound wonderful played by the right guitarist.
Answer: I am "mainly" a bassist, however, I also play guitar and a few other instruments. I prefer mid to higher end instruments and over the years I have been blessed enough to acquire a decent home studio and some very nice equipment and instruments. My American Standard Strat is my favorite electric guitar. So here is why I'm replying.... my Mom is a 78 year old widow who leads a very active life. Her favorite hobby is thrift shopping, buying and reselling used items, others peoples junk... whatever you wanna call it. A couple of years ago she ran up on an old "Spectrum" strat copy for $5. Since is was so cheap she just HAD to buy it for me. She was SOOO proud of her self. Well... it instantly became sentimental to me so I decided to upgrade it no matter the cost. Long story short, I was experimenting, so I decided to start out spending as little as possible. I wound up spending less than $200 for Floyd Rose Tremolo Bridge system with locking nut, new pups, new tuners, and new hardware. The guitar now can hold its own with any of the guitars in my studio ranging from $600 to $2000 in cost. I couldn't be happier with the results. So I would say YES. If you like the guitar, go for it. You ABSOLUTELY can upgrade the guitar and make it sound, play and look better. ...and I disagree with the guy who said it will "still" be a cheap guitar... in a few short weeks mine went from a $5 guitar to a $205 guitar. If I want it to be, it can be a $2005 guitar.... see where I'm going with this? But yeah... go for it man. Start out cheap on ebay or whatever, and see where it takes you. In the end, when you get it kickin ass like you want, you can say you "built" it and no one else has one like it. Good Luck Bro.... and keep on modding! ...Bullet


Perturbative Solution to Boundary-layers Problem

Question: Could anyone help me with the part marked in red? Why do we have a series expansion in there? And why does the limit epsilon -> 0 gives eq_in = Y''(w)+Y'(w)=0
Answer: I don't know if this should be a comment but what is wrong with multiplying through by $\epsilon$ and then taking the limit?
Comment: are you referring to the second output marked in red?
Comment: Either will do. You then have a term with no $\epsilon$ and a term with $\epsilon$.
Comment: Okay it's a bit clearer now. But I'm not very familiar with that big-O notation. What happens when you multiply ϵ to it.

Also why do we do series expansion in the first place?
Comment: $\epsilon \times O(\epsilon)$ is $O(\epsilon^2)$
Comment: I see. Thanks!
_
Comment: One more question: when we multiply ϵ through, we will have the term ϵ(Y[w] + Y'[w]). How do you deal with it?


Where are the three extra cards coming from for this Texas Hold Em hand?

Question: I've recently gotten into odds/probabilities, and even though I don't fully grasp the concept of binomial coefficients/Combinatorics, I'm still trying to figure out some probabilities using good old fashioned.. probabilities. The scenario that I'm currently dealing with is a standard Texas Hold Em game, right before the River. The following cards are in hand and in the communal:

Hand: Ace of Clubs; 2 of Clubs
Community: 5 of Clubs; 4 of Spades; 8 of Diamonds; 6 of Clubs

Currently, I am trying to calculate the odds of the next community card creating a one pair with the current cards.
I created and ran a simulation 100,000 times, tracking the percentage of one pairs encountered, which was 46.238%
This is pretty close to the original probability that I generated prior, which was 6/13, or ~46.153%. The way that I came to this number, was that I had 13 ranks, and 6 of those ranks had a chance of producing a card that would actually complete my one pair.
Thinking about this, I realized I should be able to expand that information to the entirety of the deck.
There are 6 cards currently in play, which leaves us with 52-6=46 cards to be able to draw from. There are 6 ranks that can produce a one pair, with 3 cards that satisfy each rank. This should equate to 18/46 ~= 39.13%.
Unfortunately, that number is off. I took 6*(46/13) ~= 21.23. So the proper ratio is about 21/46.
So, my ultimate question is:

Where are these extra 3 possibilities coming from?
Comment: Can anyone explain the downvotes to the question? I apologize if this has been asked before; I searched and while I did find similar questions, I did not find a duplicate. Although that could be chalked up to poor searching skills.
Comment: Your simulation is probably what is incorrect.  Make sure that it is not drawing the final card from a full deck.  Notice that $\frac{24}{52}\approx 0.461538$ which is very similar to the value your simulation is producing would be the correct probability if we are drawing the final river card from a fresh deck with the possibility to duplicate one of the already in play cards.  The correct probability is indeed supposed to be $\frac{18}{46}$
Answer: Elaborating on my comment, there is every reason to believe that your "simulation" was written incorrectly, most likely by not taking suits into account or drawing the river card from a full deck or drawing from a deck of only thirteen cards.
Your initial solution of $\frac{6}{13}$ is incorrect.  Although there are indeed six ranks which will produce a pair out of the 13 available ranks, these ranks are not equally likely to be drawn in this scenario.  There are fewer aces available in the deck than there are kings for example.
For extreme example, I have a sock drawer filled with two thousand white socks and only two black socks.  I draw one sock uniformly at random.  The probability that I draw a black sock is not going to be $\frac{1}{2}$ even though there are only two colors available and one of them is what I wanted, the probability of drawing a black sock has to do with the ratio of how many black socks there are over the total number of socks (not the total number of types of socks).  The probability here will in fact be $\frac{2}{2002}$.
Remember that the common practice of $Pr(E)=\frac{|E|}{|S|}$, the probability being the ratio of number of desired outcomes over total number of outcomes, is only valid when the sample space is equiprobable.  In common discrete probability questions like this, we must take extra care to ensure that the way in which we describe the sample space is in fact going to result in each outcome being equally likely.  To ensure this is the case, we can often arbitrarily assign labels or colors to various objects (such as when rolling two dice, imagine one of the dice is red and the other is blue, or when selecting socks imagine a tag on each with a unique identification number) so that we may tell them apart.  The existence (or nonexistence) of such a method of labeling won't affect the probabilities in any way, so we are free to have done so.

Your second solutions is in fact the correct one.  As there are 46 cards left in the deck, each of which are equally likely to be drawn for the river card, and 18 of those will result in a pair (6 ranks which result in a pair, 3 unused suits for the selected rank), the probability is going to be $\frac{18}{46}$.
There are no "extra three possibilities" that are missing.
Comment: Hmm, I'm not quite sure what it was about poker that made my brain forget how probabilities worked. I reworked my simulation and it's giving 39.2% now when ran. The only thing I did different was modify the proximity of the ranks of the cards already known. Strange, but whatever works I guess. To be honest, I'm not even sure where I came up with 6/13 to begin with. I kept feeling like that wasn't right. Thank you so much for taking the time to write out and explain for me!


How to send forget pass email programatically?

Question: I implemented Decoupled Drupal in one of my projects, one of the features I need to implement is a forget password feature. So I created a custom route to listen to reset password requested.
I know I can create a reset password URL with user_pass_reset_url(); I can generate this link and programmatically set the email to that user, but I am looking for a service or Drupal core functionality to achieve this job.
How can I programmatically send a reset password email?
Comment: The way to send a reset password email programmatically is to create a module to change the host and path of the URL so that it links to your app instead, and then provide an endpoint to handle ingesting the user pass reset URL parts. There is no core functionality for this. In Drupal 7, I found it easier to redirect the user from the back end site to the front end app after visiting the /user page
Answer: With  some reverse engineering on core user module  the solution is :
    $name = \Drupal::request()->get("name");
    $langcode =  \Drupal::languageManager()->getCurrentLanguage()->getId();
    // Try to load by email.
    $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(array('mail' => $name));
    if (empty($users)) {
        // No success, try to load by name.
        $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(array('name' => $name));
    }
    $account = reset($users);
    // Mail one time login URL and instructions using current language.
    $mail = _user_mail_notify('password_reset', $account, $langcode);

Comment: @AbdulSadikYalcin `reset` get the first item
Comment: Thank you @Yusef for example. I created this module for the self project:
https://github.com/ivan-berezhnov/drupal-8-recipes/tree/master/Roles_and_Permissions/user_password_reset#user-password-reset-by-link
Comment: @Yuseferi What does `reset($users)` do?


OxyPlot AutoScale

Question: AutoScale OxyPlot Chart.
For example i have something like this.
using OxyPlot;
using OxyPlot.Axes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using OxyPlot.Wpf;
using PlotControllerTest.Properties;
using System.Diagnostics;
namespace PlotControllerTest
{
///
/// Interaction logic for MainWindow.xaml
///
///
public class Chart
{
    public PlotController myController { get; set; }
    private OxyPlot.Series.LineSeries LS;
    OxyPlot.Axes.LinearAxis LAY;
    OxyPlot.Axes.LinearAxis LAX;
    private int i = 0;
    public PlotModel PlotModel {get;set;}
    public Chart()
    {

        PlotModel = new PlotModel();
        myController = new PlotController();
        myController.UnbindAll();
        myController.BindMouseDown(OxyMouseButton.Left, OxyPlot.PlotCommands.PanAt);
        LS = new OxyPlot.Series.LineSeries();
        LAY = new OxyPlot.Axes.LinearAxis()
        {
            Position = OxyPlot.Axes.AxisPosition.Left,
            AbsoluteMaximum = 100,
            AbsoluteMinimum = 1,
        };
        LAX = new OxyPlot.Axes.LinearAxis()
        {
            Position = OxyPlot.Axes.AxisPosition.Bottom,
            AbsoluteMaximum = 200,
            AbsoluteMinimum = 1,
            MinorStep=5,
        };
        PlotModel.Series.Add(LS);
        PlotModel.Axes.Add(LAY);
        PlotModel.Axes.Add(LAX);
    }
    public void BeginAddPoints()
    {
        Random rnd = new Random();
        do
        {
            int temp=rnd.Next(1, 100);
            LS.Points.Add(new DataPoint( ++i,temp));
            System.Threading.Thread.Sleep(100);

            Update();
        } while (i<30);
        Update();
    }
    public void Update()
    {
        PlotModel.InvalidatePlot(true);
    }
}
public partial class MainWindow : Window
{
    Chart TChart;
    delegate void BeginUpdate();
    private Stopwatch stopwatch = new Stopwatch();
    private long lastUpdateMilliSeconds;
    public MainWindow()
    {

        TChart = new Chart();
        BeginUpdate BU = new BeginUpdate(TChart.BeginAddPoints);
        IAsyncResult result = BU.BeginInvoke(null,null);
        DataContext = TChart;
        CompositionTarget.Rendering += CompositionTargetRendering;
        InitializeComponent();
    }
    private void CompositionTargetRendering(object sender, EventArgs e)
    {
        if (stopwatch.ElapsedMilliseconds > lastUpdateMilliSeconds + 300)
        {
            TChart.Update();
        }
    }
}

}
Xaml code look's like
<Window x:Class="PlotControllerTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:oxy="http://oxyplot.org/wpf"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <oxy:PlotView Model="{Binding PlotModel}" DefaultTrackerTemplate="{x:Null}" Controller="{Binding myController}"></oxy:PlotView>
</Grid>

How to implement autoscale of Y Axes after dragging? For example when i drag chart in window, and there appears only one Line ((1,2),(4,4)). Y axis will show from 2 to 4.Thanks.
Comment: I know how to do it with a candlestick serie but not with a line serie. I am lacking a method to calculate ymax = max(f(x)) based on a range of x (1 <= x <= 4) i will try to sort this out and post you something.
Comment: I just created a project with your code, I am not sure to understand what you mean by dragging. Your project auto adjust the x axis to show from 0 to max(x) (native function of oxyplot), and as it also does the same on your y axis, you always see all values.
Answer: If you would like to reset just the Y Axis, you would need to set a Key to your Y-Axis first.
 LAX = new OxyPlot.Axes.LinearAxis()
    {
        Key = "YAxis",
        Position = OxyPlot.Axes.AxisPosition.Bottom,
        AbsoluteMaximum = 200,
        AbsoluteMinimum = 1,
        MinorStep=5,
    };

Then you could get a reference to it by using LINQ. Call the following after your dragging event.
 Axis yAxis = PlotModel.Axes.FirstOrDefault(s => s.Key == "YAxis");
 yAxis.Reset();

If you would like to reset both the X and Y Axis then, you could just call
PlotModel.ResetAllAxes();

Answer: First thing, you will not have anything to rescale with the controller you are using as it blocks any panning/zooming abilities. By default panning is on the right click and zooming on mouse wheel. Also you plotmodel at creation will automatically plot all your points, so there is nothing to rescale. But let's assume you have a way to pan and zoom, what you can do to auto recalculate the maximum values you should have on your y axis is as following :
Let's first create a AdustYExtent method :
private void AdjustYExtent(OxyPlot.Series.LineSeries lserie, OxyPlot.Axes.LinearAxis xaxis, OxyPlot.Axes.LinearAxis yaxis)
    {
        if (xaxis != null && yaxis != null && lserie.Points.Count() != 0)
        {
            double istart = xaxis.ActualMinimum;
            double iend = xaxis.ActualMaximum;

            var ptlist = lserie.Points.FindAll(p => p.X >= istart && p.X <= iend);

            double ymin = double.MaxValue;
            double ymax = double.MinValue;
            for (int i = 0; i <= ptlist.Count()-1; i++)
            {
                ymin = Math.Min(ymin, ptlist[i].Y);
                ymax = Math.Max(ymax, ptlist[i].Y);
            }

            var extent = ymax - ymin;
            var margin = extent * 0; //change the 0 by a value to add some extra up and down margin

            yaxis.Zoom(ymin - margin, ymax + margin);
        }
    }

What it does is first to find all your points that fit in the XAxis range currently seen and store them in the ptlist value. Then it iterates this list and find the corresponding max and min y. Then you just have to apply those maximum and minimum to your y axis. Note the margin value that I use to allow to put extra space on top and bottom.
Now you have to bind this method to the AxisChanged event of the x axis. In Chart() before adding your axes to the plot, add
LAX.AxisChanged += (sender, e) => AdjustYExtent(LS, LAX, LAY); ;

It should now auto scale your y axis depending on your x axis.

OxyPlot AutoScale


How to unbind an arbitrary listener in jquery/javascript?

Question: If there is some library (blackbox) that is putting a click listener on an a tag, that does something like do an alert in this case, it is also blocking the actual href navigation from working.
Is there a way in javascript/jquery to unbind that specific click listener and make the href clicking to work?
Note: I don't have the reference to the actual click function.
Thanks
Comment: add your own event listener as well. both (yours and library one) will fire
Comment: No. however, i guess you could remove and replace the anchor tag. the  new one of course won't have the listener.
Comment: Have you tried [capturing the event](https://javascript.info/bubbling-and-capturing#capturing) and stopping it's propagation toward the target. It won't unbind the event in the library, but it could help you achieve roughly the same thing. I haven't used it since my flash days, so I don't know exactly how much browser support it has. A quick google suggested it was supported since IE9 and stopPropagation works in both bubble and capture. However, I have not tested it so far.
Answer: What about
$(document).on('click','a',function(){$(this).preventDefault();console.log('a click'); return false;});

as a way to "disable" all present and yet to be generated  tags?
Comment: Just noticed, you do want the default action to take place. In that case my suggestion will not help you ;-)


How to write stream to S3 with year, month and day of the day when records were received?

Question: I have a simple streams that reads some data from a Kafka topic:
 val ds = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", "host1:port1")
      .option("subscribe", "topic1")
      .option("startingOffsets", "earliest")
      .load()

val df = ds.selectExpr("cast (value as string) as json")
      .select(from_json($"json", schema).as("data"))
      .select("data.*")

I want to store this data in S3 based on the day it's received, so something like:
s3_bucket/year/month/day/data.json

When I want to write the data I do:
df.writeStream
  .format("json")
  .outputMode("append")
  .option("path", s3_path)
  .start()

But if I do this I get to only specify one path. Is there a way to change the s3 path dynamically based on the date?
Comment: If you will partition by time, consider how you'll query. The problem with the usual year, month, day path nesting is that it makes certain types of queries quite difficult. It is usually preferable to partition along a single axis, e.g., s3_bucket/table_name/ts=yyyymmddhhmm/*.json, which allows for fast range queries. See https://spark-summit.org/east-2017/events/bulletproof-jobs-patterns-for-large-scale-spark-processing/
Answer: Use partitionBy clause:
import org.apache.spark.sql.functions._

df.select(
    dayofmonth(current_date()) as "day",
    month(current_date()) as "month",
    year(current_date()) as "year",
    $"*")
  .writeStream
  .partitionBy("year", "month", "day")
  ... // all other options


Alert dialog showing only after second click

Question: I have try to show Yes No dialog after clicking a button and send a message in case Yes has been pressed.
my problem is that the Alert showing only after the second click on the button.
the button xml
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/clrTotalButton"

    android:clickable="false"
    android:enabled="true"
    android:onClick="dialogevent"
    android:layout_alignParentStart="false"
    android:layout_alignParentEnd="false"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="25dp"
    android:focusable="true"
    android:background="@drawable/clrtotal_btn" /

the button definition :
public static View clrTotalBtn;

and the alert window and command:
  public void dialogevent(View view){

    clrTotalBtn = (Button) findViewById(R.id.clrTotalButton);
    clrTotalBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder altdial = new AlertDialog.Builder(DeviceControlActivity.this);
            altdial.setMessage("ARE YOU SURE TO CLEAR TOTAL?").setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            writeClrTotal();
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert = altdial.create();
            alert.setTitle("Warning!");
            alert.show();
        }
    });
}

Many Thanks!
Comment: Why you have added `android:clickable="false"` ?
Comment: that's an old definition , I missed it.. thanks
Answer: remove this
clrTotalBtn = (Button) findViewById(R.id.clrTotalButton);
clrTotalBtn.setOnClickListener(new View.OnClickListener() {

it should be like this:
 public void dialogevent(View view){
     AlertDialog.Builder altdial = new AlertDialog.Builder(DeviceControlActivity.this);
        altdial.setMessage("ARE YOU SURE TO CLEAR TOTAL?").setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        writeClrTotal();
                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert = altdial.create();
        alert.setTitle("Warning!");
        alert.show();
 }

Because you define an onClickListener again on first click and second showing dialog. If you define click event in xml it is needed to set click listener anymore.
Answer: You have to set the OnClickListener before clicking the Button. Currently you register the listener when clicking the button so you have to click it twice before the action happens. If you want to do it in code you have to register e.g. during onCreate. If you want to go with the xml way you can just remove the code registering the Listener and only leave the content of the actual listener there:
public void dialogevent(View view){

    AlertDialog.Builder altdial = new AlertDialog.Builder(DeviceControlActivity.this);
    altdial.setMessage("ARE YOU SURE TO CLEAR TOTAL?").setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            writeClrTotal();
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert = altdial.create();
            alert.setTitle("Warning!");
            alert.show();
}

edit:
and of course clean up your Button XML:
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/clrTotalButton"
    android:onClick="dialogevent"
    android:layout_alignParentStart="false"
    android:layout_alignParentEnd="false"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="25dp"
    android:background="@drawable/clrtotal_btn" />

Answer: This is because you are defining the OnClick twice. Once in your xml, and once that is clicked, you are defining a new OnClickListener which needs to be clicked in order to show the overlay.
Use this code:
  public void dialogevent(View view){
        AlertDialog.Builder altdial = new AlertDialog.Builder(DeviceControlActivity.this);
        altdial.setMessage("ARE YOU SURE TO CLEAR TOTAL?").setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        writeClrTotal();
                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert = altdial.create();
        alert.setTitle("Warning!");
        alert.show();
    }

Answer: Remove button onClickListener from dialogevent(View ) method.
public void dialogevent(View view){

        AlertDialog.Builder altdial = new AlertDialog.Builder(DeviceControlActivity.this);
        altdial.setMessage("ARE YOU SURE TO CLEAR TOTAL?").setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        writeClrTotal();
                    }
                })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert = altdial.create();
        alert.setTitle("Warning!");
        alert.show();
    }
});}

Answer: You can done by using this code
XML Button Code
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/clrTotalButton"
    android:onClick="dialogevent"
    android:layout_alignParentStart="false"
    android:layout_alignParentEnd="false"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="25dp"
    android:focusable="true"
    android:background="@drawable/clrtotal_btn" /

Java Code
public void dialogevent(View view){

            AlertDialog.Builder altdial = new AlertDialog.Builder(DeviceControlActivity.this);
            altdial.setMessage("ARE YOU SURE TO CLEAR TOTAL?").setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            writeClrTotal();
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });

            AlertDialog alert = altdial.create();
            alert.setTitle("Warning!");
            alert.show();

}

In your code alrady apply onClick code on XML.
Answer: I think removing
android:focusable="true"

from xml file will solve your problem.


How do I configure routing for non-knative service in a Knative & Istio installed k8 cluster?

Question: I have a Knative installed with Istio as networking layer (without injection)
The kubernetes cluster is using Istio ingress gateway as default ingress.
Most Knative service's routing are managed automatically by Knative & Istio.
However I am trying to run a nifi native kubernetes services on the same cluster, how do I setup the ingress configuration on Istio ingress gateway for the services. Any reference to share?
Or is it possible to setup 2 ingress (1 Istio, 1 nginx) in the cluster, and have the native k8 service uses the nginx ingress?
I'm doing that cause istio is quite new to me and Knative abstracted the Istio networking element when deploying knative services but not the native k8 services.
Hope my question makes sense. Thank you.
Comment: Hello @Darkbluelion. Does any of the below answers helped you?
Answer: You should be able to use the standard Istio VirtualService object to map domains to Kubernetes Services (as described in the Istio documentation), assuming that you don't overlap with a domain already being served by Knative.
Answer:
How do I configure routing for non-knative service in a Knative & Istio installed k8 cluster?

Just like you would in istio-only cluster (without knative).
knative works like an addon; it adds some functionality; it does not remove/hide any istio functionality. Same is with istio - it adds more functionality to k8s and does not remove any k8s core functionality. You can use all the features of istio and k8s all the time.

how do I setup the ingress configuration on Istio ingress gateway for the services

Check out the bookinfo example. This example deploys a sample application composed of four separate microservices used to demonstrate various Istio features. Try to analyze it.

is it possible to setup 2 ingress (1 Istio, 1 nginx) in the cluster, and have the native k8 service uses the nginx ingress?

Yes. It is possible.


Configure user login and stored procedures permissions on SQL Server

Question: I'm a software developer finishing a web application. The app uses the database "DB1" in my SQL Server 2008 "SQLServer_1".
I would like to create a limited user that the web app will use in its connection string. This users will be allow to execute a list of stored procedures, nothing else. So the user shouldn't be allowed to execute adhoc SQL or other stored procedures out of that list.
I have a little mess between "user" and "login", I don't really know where should I create the new "account".
Which are the steps I should follow?
Thanks in advance.
Answer: It all comes down to scope.  A login is a server-level account and a user is a database-level account.  The user needs to be mapped to a login, so you'll create your login first (while at the same time creating a way for it to authenticate to the server).  Next, in your application's database, you'll create the user.  When you do this, you'll be given a choice of which login this user represents.  You'll pick the login that you previously created.  You can then assign permissions to the stored procedures that you want it to be able to execute.  Of course, there's a less clickety-clack way of doing this:
<code>create login [your login name here] from windows; --if the login is a Windows account
create login [your login name here] with password 'some super secret password'; --if not a Windwos account
use [DB1];
create user [your login name here] for login [your login name here];
grant execute on [your stored procedure here] to [your login name here];
grant execute on [another stored procedure here] to [your login name here];
...
</code>
Comment: Thanks, that explanation is exactly what I was looking for. Thanks so much for the SQL lines indeed :)
Answer: I'm not sure what you mean? If you don't know the differences between "User", "Login" and "Role" then follow the excellent documentation from Microsoft. From there you can reach any other related topic like granting execution rights for stored procedures.
Comment: In the MSSMS, there are two "Security" folders, one is in the root node, and other is inside your database. You can create a Login in the first, and a User in the second, but I don't know what is what I need.
Comment: That's the global context and the database context. Put it wherever you need it.


Multiple files upload - Blueimp jQuery uploader

Question: I use a jquery plugin name "blueimp jquery file upload" - https://github.com/blueimp/jQuery-File-Upload.
I was wondering how can i add dropdown values to the database for each file when uploading multiple files.
I have used the original javascript template for uploading files and i modified it a little. It looks like this.

I am trying to make it to work. I spend a lot of time today but don't want to gave up. If someone had expericne with this, please help me, give me direction.
i have found this but i cant figure it out how to make it work
https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-Form-Data
Thanks
Best Regards,
Darko
Answer: See server/php/UploadHandler.php in function handle_file_upload try connect to db and save files details in database
Comment: There is already title atribute that i want tu use as you can see in the dropdown above :)


mysqldump doing a partial backup - incomplete table dump

Question: I have a database of about 6GB in size and it has a table with 12.6 million rows. I tried to export the database into a SQL dump by:
mysqldump -u root -p db_name > db_name.sql
When the command finishes, the exported SQL dump file is just about 2GB and the primary table got exported only about 1 million rows.
What could possibly be wrong?
Answer: There is a 2GB filesize limit for some reason, the easiest way to get around this is using split:
mysqldump ... | split -b 250m - filename.sql-

You can also compress the files like this:
mysqldump ... | gzip -9c | split -b 250m - filename.sql.gz-

To restore from a non-compressed file, do this:
cat filename.sql-* | mysql ...

For a compressed file:
cat filename.sql-* | zcat | mysql ...

Of course if you want a single file, you can then tar the result.
Obviously you can replace the 250m with a different size if you wish.
Comment: This is a great workaround in the meantime, but I highly suggest you dump your data to a location that will handle files of any size.  Otherwise, you are looking for headaches.  It should be as simple as reformatting with a filesystem that handles larger files.
Comment: the `...` in the commands is connecting to the database and selecting the table like you have in your original post.
Comment: i am not sure if reformatting the filesystem is always a very easy option.
Answer: Your filesystem probably is limited to 2gb files.
Comment: that may not compress it enough
Answer: It's happen because some SQL Dump have limited size for dumping data.
you could not dump the database if it over the limit.
If you really want to do this you must compress the database.By using ZIP,GZIP,etc. Before dumping data.
Answer: I had similar, though all the tables were exported up to a certain point.
I'd removed a column on which an old redundant View depended, and mysqldump quietly choked trying to 'export' the View


Spring: Disable caching of template and static files

Question: While using Spring Boot v2.6.3, Spring v5.3.15 and Java 17.0.2,
I put the devtools dependency in pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

In application.yml, I have this:
spring:
  thymeleaf:
    cache: false
  cache:
    type: none
  devtools:
    restart:
      enabled: true

If I do a change (java, template or static css file), I have to rebuild the project for the new content to appear in the browser.
Is there a way to prevent Spring from caching the templates and the static files?
Comment: Which IDE are you using? when using devtools caching is disabled by default.
Comment: IntelliJ, so I understand I have to rebuild the project after Java code changes. Though, during development, I don't need CSS and templates to be chached.
Comment: Intellij needs some additional configuration to automatically (re)build after changes, if not those changes aren't picked up.
Answer: When it comes to spring-boot, by default the template options such as Thymeleaf and FreeMarker are configured to be cached. It is done in that way because the template parsing don't need to be reparsed with every request they serve. Even that is useful in production cached templates are not so great at development time. Cached templates will still be in use until you restart the application.
DevTools addresses this issue by automatically disabling all template caching. However as you explained it didn't work for you. Therefore I suggest you remove using DevTools and use the below mentioned application property.
To disable the caching all you need to do is set a template-appropriate caching property to false. I will mention different properties for different templates for disable the caching.
FreeMarker          spring.freemarker.cache
Groovy Templates    spring.groovy.template.cache
Mustache            spring.mustache.cache
Thymeleaf           spring.thymeleaf.cache

By default, all of these properties are set to true to enable caching. You can disable caching for your chosen template engine by setting its cache property to false.
For testing purpose, just remove the spring configuration you mentioned in your question and just add the following.
spring:
  thymeleaf:
    cache: false

This works for me and if this doesn't work for you then if should be a different problem.
Comment: Removing devtools and disable caching won't help. ONe needs to configure Intellij to automatically build and update classes and resources. This way content gets copied to the output folder and devtools can detect/reload that. Else they remain in the source tree.
Comment: I tried removing DevTools, but no luck. `spring.thymeleaf.cache` was already in the application.yml file.


Right intonation

Question: What mean to play in tune? In melodic aspect it's not so difficult to respond. All played notes must to keep the same frequencies all long the interpretation.Harmonicaly the upper note in the accord or the double strings must follow the same way like a part of the melody. One exemple of perfect temperament with fixed notes used by this great guitar player is here:

 Do you have an idea what K(half tone) is used in this guitare to sound so good?
Comment: Please could you develop your question? Currently it is not clear.
Comment: (Finally: If my understanding is right, then this is only considering "vertical" tuning—the tuning of notes against others within the same instant. There's also the topic of "horizontal" tuning, comparing a note to those before or after it. Anyone who's heard a beginning violin recital can attest that even a solo monophonic performer can be "out of tune.")
Comment: It seems like you're thinking of a certain instrument, or ensemble of instruments playing together. Please edit to explain more about that. This simple question treads some thin ice over a deep cultural-practical-philosophical chasm involving aesthetics, temperaments, abilities, etc. Narrowing to a particular genre might help keep it within bounds.
Comment: (And, as a spoiler: the simplest answer to such a complex question is "It can mean very different things for different times, places, performers, and audiences.")
Comment: (Also: it might be easier to answer "what counts as 'out of tune.'" Because sometimes there are aesthetic reasons to alter the tuning of certain pitches even from what is expected within the parameters of the music-culture, or to avoid exact, precise duplication within a unison, but skipping these alterations wouldn't be called "out of tune.")
Comment: Also, your English is much better than any of my secondary languages, but there might be some confusion due to a language gap. Here's a proposed rewording of what I _think_ you're asking; if I've got your meaning correctly, feel free to edit to use it: "What does it mean to play in tune? For unison melodic playing it's not so difficult to answer. All played notes must match each other's frequencies all through the performance. For supporting harmonic parts, the upper note in the chord, or anything doubling the melody, must match the melody in the same way. Do you not think so?"
Comment: Ok, in the vertical tuning the highest note must be conforme with the horizontal tuning in the used temperament. The classic TET12 can be changed to a better one where only the unisson will be perfect.
Comment: Given your video, do not assume its value of K is constant. It's very possible that the strings of the guitar are not tuned against each other with the same value of K as the frets (e.g. each individual string is 12TET, the bottom E and A strings are tuned precisely to a 4:3 ratio).
Answer: It ain't necessarily so! It will depend on whether the melody is being played (sung) on infinitely variable pitch instruments. When they're accompanied by fixed pitch (piano, etc) then they will follow those pitches. But played (or sung) acapella, they will move slightly, and I don't mean move to a slightly different key, but sing more 'in tune' than they would with 12tet instruments to guide them. If that's what your question is about...
Comment: The right intonation don't depend of wich instrument or voice is used!
Comment: I believe it does. In 12 tet, there are many note pitches which vary slightly from other temperaments, which is what I mean in my answer. Maybe poor translation is getting in the way!

Right intonation


Freefall motion with air resistance ordinary differential equation

Question: I'm stuck in finding the general solution for this DE because I'm not sure what technique I should use:
$$\frac{dv}{dx}=\frac{g}{v}-\frac{k}{m}$$
Where g, k and m are constants.
I'm not sure if I can really use substitution method here. I've also tried long division but I always end up having a higher degree of the numerator. Partial fractions also doesn't seem to work as the denominator is not factorable when considered as a separable equation.
Comment: Do you want to find a solution or a differential equation? It is not clear from your question.
Comment: Sorry for the confusion. Yes I want to find the general solution for this, I just want to really know what technique I should use.
Comment: This isn't the correct equation of motion for a free-falling object.
Answer: The correct equation of motion for a free-falling object as written in the OP is incorrect.  Rather, we have
$$m\frac{dv}{dt}=mg-kv^2 \tag 1$$
Dividing by $v=\frac{dx}{dt}$ reveals that
$$\frac{dv}{dx}=\frac{g}{v}-\frac{k}m v$$
Then, we have
$$\int_{x_0}^x dx' = \frac{m}{k}\int_{v_0}^v \frac{\nu}{\frac{mg}k-\nu^2}\,d\nu \tag 2$$
where we note that the integration limits cannot embed $v=\sqrt{mg/k}=v_{\infty}$, which is the terminal velocity.  Aside, in $(2)$, $v_0$ is the speed of the object when $x=x_0$.
The solution to $(2)$ is given by

$$x=x_0+\frac{m}{2k}\log\left|\frac{v_{\infty}^2-v_0^2}{v_{\infty}^2-v^2}\right| \tag 3$$

Unfortunately, $(3)$ does not provide much insight into the dynamics of the free-falling object.  It provides only a relationship between the position of the object and its speed at that position.
It is better to rearrange $(1)$ as
$$\int_{0}^t d\tau =\frac{m}{k}\int_{v(0)}^{v(t)} \frac{1}{v_{\infty}^2-\nu^2}\,d\nu \tag 4$$
We can evaluate the integral on the right-hand side of $(4)$ by enforcing the substitution $\nu = v_{\infty}\tanh(z)$.  Proceeding we find that
$$t=\sqrt{\frac{m}{kg}} \left(\text{artanh}(v(t)/v_{\infty})-\text{artanh}(v(0)/v_{\infty})\right)\tag 5$$
Solving $(5)$ for $v(t)$ reveals

$$v(t)=v_{\infty}\left(\frac{\frac{1+v(0)/v_{\infty}}{1-v(0)/v_{\infty}}e^{2t/\sqrt{mg/k}}-1}{\frac{1+v(0)/v_{\infty}}{1-v(0)/v_{\infty}}e^{2t/\sqrt{mg/k}}+1}\right)$$

which provides a more useful form than $(3)$.  For example, we see from $(5)$ that if $v(0)>v_{\infty}$, then $v(t)$ decreases to $v_{\infty}$ while if $v(0)<v_{\infty}$, then $v(t)$ increases to $v_{\infty}$.
Comment: Please let me know how I can improve my answer.  I really want to give you the best answer I can. -Mark
Answer: This equation is separable. You write:
$$dv = \left(\frac{g}{v} -\frac{k}{m}\right)\cdot dx $$
$$ \Rightarrow \frac{dv}{\frac{g}{v} -\frac{k}{m}} = dx$$
$$ \Rightarrow \int_{v_0}^{v} \frac{dv}{\frac{g}{v} -\frac{k}{m}} = \int_0^xdx$$
$$\Rightarrow \int_{v_0}^{v} \frac{v}{g-\frac{k}{m}v} dv = x $$
Now you have to look up this integral on some integral table and solve for $x$.
Comment: So I can let some variable u to the denominator then integrate by substitution?
Comment: Yes. You can define $u = g-\frac{k}{m}v$. Then you have $du= \frac{k}{m}dv$ and $v=\frac{g - u}{\frac{k}{m}}$.
Comment: Is this the only way I can find the general solution or is still there another technique?
Comment: The ODE is not the correct equation of motion for a free-falling mass.
Answer: The answer on your question is given by @JakobElias. But I want to give some extra information.
When we have an oject falling vertically and we have drag we can use the following system of equations:
$$
\begin{cases}
\text{g}=\frac{\text{d}^2\space\text{h}\left(t\right)}{\text{d}\space t^2}+\frac{\rho\cdot\text{A}\cdot\text{C}_\text{d}}{2\cdot\text{m}}\cdot\left(\frac{\text{d}\space\text{h}\left(t\right)}{\text{d}\space t}\right)^2\\
\\
\text{V}_\text{T}=\sqrt{\frac{2\cdot\text{m}\cdot\text{g}}{\rho\cdot\text{A}\cdot\text{C}_\text{d}}}\\
\\
\text{C}_\text{d}=\frac{\text{F}_\text{d}}{\frac{1}{2}\cdot\rho_\text{m}\cdot\text{u}^2\cdot\text{A}_\text{m}}
\end{cases}\tag1
$$
Where $\text{h}$ is the fall distance, $\rho$ is the fluid density, $\text{m}$ is the mass, $\text{C}_\text{d}$ is the drag coefficient, $\text{A}$ is the projected surface area, $\text{g}$ is the gravitational acceleration, $t$ is time, $\text{V}_\text{T}$ is the terminal velocity, $\text{F}_\text{d}$ is the drag force, $\rho_\text{m}$ is the mass density, $\text{u}$ is the characteristic speed and $\text{A}_\text{m}$ is the area.


Accordion - Don't want to make first cell active

Question: Well I am using jQuery accordion. Below is what I have
<code>$(document).ready(function(){
    $("#accordion001").accordion({
        collapsible: true,
        autoHeight: false,
        navigation: true
    });
});
</code>
The problem is that it always shows the first link data by default.
<code>+++++++++++++++++++++++++++++++++++++++
+   Link 1                            +
+     Link 1 line 1                   +
+     Link 1 line 2                   +
+     Link 1 line 3                   +
+   Link 2                            +
+   Link 3                            +
+   Link 4                            +
+++++++++++++++++++++++++++++++++++++++
</code>
I don't want to show first link data. I just want to show all available links as below.
<code>+++++++++++++++++++++++++++++++++++++++
+   Link 1                            +
+   Link 2                            +
+   Link 3                            +
+   Link 4                            +
+++++++++++++++++++++++++++++++++++++++
</code>
Is it doable? What option do I need to write?
Answer: <code>$("#accordion001").accordion({
        collapsible: true,
        autoHeight: false,
        navigation: true,
        active:false,
    });
</code>
this should work.
Comment: could you please take a look at http://stackoverflow.com/questions/12622069/jquery-accordian-de-collapse
Answer: $( "#accordion001" ).accordion( "option", "active", 2 );
and it will be opened in load time.


Decomposition of characters of infinite product of abelian groups

Question: I am reading papers about cellular automata and for some reason, the same result claim is made in all of them and is never proven; I assume that it might be easy to prove, but I cannot see how. Here is the claim:
Let $G$ be an finite abelian group. We denote by $\widehat{G}$ the set of characters of this group, that is to say homomorphisms $\chi : G \to S^1$.
Let $\mathbb{M}$ be a monoid (what really interests me is the case where $\mathbb{M} = \mathbb{Z}$ so if the proof is simpler in this special case, I'm fine with it !)
Then, $\widehat{G^\mathbb{M}}$ is (apparently) isomorphic to the set of sequences $\widehat{G}^\mathbb{M}$ with finitely-many non trivial characters (i.e which are not constant equal to $1$).
In the case of finite products I know that we have $\widehat{G \times G} \cong \widehat{G} \times \widehat{G}$ but I don't understand why we have to restrict ourselves to finite-support sequences in the case of a general $\widehat{G^\mathbb{M}}$.
Edit: For reference, here is one of the papers https://arxiv.org/pdf/math/0108082.pdf , on the 3rd page.
Comment: What does $G^\mathbb M$ mean?
Comment: That is simply the set of functions from $\mathbb{M}$ to $G$ ! In the case of $\mathbb{M} = \mathbb{N}$ or $\mathbb{Z}$, then this can be seen as the set of (bi-)infinite sequences of elements of $G$.
Comment: Okay, then I think you mean it is the group of all functions $|\mathbb M| \to G$ with pointwise addition
Answer: It's because $\hat G$ is not just a group but a topological group, and it isn't defined to be all homomorphisms, only continuous ones.
This doesn't matter at first because $G$ is finite so its a discrete group, and all homomorphisms are continuous. But $G^I$ is only a compact group, so its dual will be affected. (I'll use $I$ as an index set instead of $\mathbb M$ or $\mathbb Z$, feel free to substitute.)
Note that finitely supported functions is a direct sum (coproduct)  whereas all functions is a direct product: $$C = \bigoplus_{i\in I}G, \hspace{1em} P = \prod_{i\in I} G$$
The goal is then to see $\widehat P \cong C$, but by general nonsense you can see $$\widehat C = Hom(\coprod_{i\in I} G, S^1) = \prod_{i\in I} Hom(G,S^1) \cong P$$
and then apply pontrjagin duality.
For more details see these notes https://www.maths.ed.ac.uk/~cbarwick/papers/suppprobsLCA.pdf in which your problem is Exercise 4.10.


Counting all possible arrangements

Question: I try to solve the following counting problem:
We consider a new type of gamble. In this one there are 7 red balls, 5 blue balls and 3 purple balls. The presenter now rolls a 4-sided die for each red ball, an 8-sided die for each blue ball, and a 12-sided die for each purple ball, and writes the result on the ball. The 15 balls are then placed together in a box. How many possible arrangements of the balls can be created in this way when drawing? Assume that the balls cannot be distinguished by handwriting.
What I did so far:
First, I counted the number of possibilities in which the balls can be numbered. I think there are $12^3\cdot 8^5\cdot 4^7$ possibilities. Now it only remains to count the possible arrangements of the balls.
If any two balls would always be distinguishable, we would have $15!$ possibilities. Thus the answer would be $n:=15!\cdot 12^3\cdot 8^5\cdot 4^7$. But unfortunately it may happen that the balls are indistinguishable (when their color and number coincide). So the answer must be less than $n$, because we effectively counted some events multiple times. But in my head everything becomes so foggy at this point. How to deal with those cases?
Answer: The answer to your problem is
$$n=\frac{15!}{3!\cdot5!\cdot7!}\cdot 12^3\cdot 8^5\cdot 4^7.\tag1$$
A simple argument leading to (1) is the following. First arrange the unnumbered balls and then number them choosing the range according to the color.
The same result may be obtained in a much more complicated algebraic way as follows.
After numbering the balls they have two properties: color and number. Two balls which share both color and number are indistinguishable and we will denote the number of such balls as $k_{ij}$, where $i$ and $j$ stay for color and number respectively. $k_{ij}$ can be arbitrary non-negative integer numbers subject to the condition
$$
\sum_{j=1}^{J_i} k_{ij}=K_i\tag2,
$$
where $K_i$ and $J_i$ are the number of balls of the $i$-th color and the range of numbers which can be assigned to these balls, respectively.
With these definitions the total number of possible combinations is ($m$ is the number of colors, $K=\sum_{i=1}^m K_m$ is the number of balls):
$$\begin{align}
n&=\sum_{k_{ij}}^{(2)}\frac{K!}{\prod\limits_{i=1}^m\prod\limits_{j=1}^{J_i} k_{ij}!}\\
&=\sum_{k_{ij}}^{(2)}\frac{K!}{\prod\limits_{i=1}^m K_i!}
\prod\limits_{i=1}^m\frac{K_i!}{\prod\limits_{j=1}^{J_i} k_{ij}!}\\
&=\frac{K!}{\prod\limits_{i=1}^m K_i!}
\prod\limits_{i=1}^m\sum_{k_{ij}}^{(2)}\frac{K_i!}{\prod\limits_{j=1}^{J_i} k_{ij}!}\\
&=\frac{K!}{\prod\limits_{i=1}^m K_i!}\prod\limits_{i=1}^m J_i^{K_i}.\tag3
\end{align}$$
Answer: Maybe this: Let's handle each color separately-
Look on a random permutation of the $15$ balls we have:
3 balls are going to be purple, 5 are going to be blue and 7 are going to be red,
hence there are
$${15\choose3}{12\choose5}$$
possibilities to select places for the balls, by color.
Then, you would like to use
$$Select(n,k) ={k+n-1 \choose k}$$ that is the number to choose $k$ items out of $n$ with the possibility to choose again, and with no importance of order
That gives us the number of possibilities to select each group of balls, and now we only need to plug everything together to get:
$${15\choose3}{12\choose5}\cdot{3+12-1\choose3}{5+8-1\choose5}{4+7-1\choose4} \\
={15 \choose3}{12\choose5}\cdot{14\choose3}{12\choose5}{10\choose4}$$

Counting all possible arrangements


Exibir div após um certo tempo, com setTimeout

Question: Estou tentando colocar setTimeOut em uma div em javascript, mas não estou conseguindo de jeito nenhum!
Meu código :

Estou querendo que isso apareça depois um certo tempo, e a única function que eu acho que serve para isso é a setTimeOut, já tentei de diversos modos mas nenhum resultado, tentei assim :
setTimeout('document.getElementById('mime')', 60000);

document.getElementById('mime').setTimeout(60000);

Answer:

Comment: De certo cara, obrigado !


c++ class function friend to another class

Question: I'm trying to specify a class member function as a friend of another class,
but it gives me only access to the public members not the protected or private members. It's working fine with free functions.
Visual Studio Errors:
member "Class1::protected_int" (declared at line 9) is inaccessible
member "Class1::private_int" (declared at line 11) is inaccessible

class Class2;

class Class1 {
    friend void Class2::TEST(const Class1& ex);
    friend void TEST(const Class1& ex);

public:
    int public_int;
protected:
    int protected_int;
private:
    int private_int;
};

class Class2{
public:
    void TEST(const Class1& ex);
};

void Class2::TEST(const Class1& ex){
    int pub = ex.public_int;
    int pro = ex.protected_int;
    int pri = ex.private_int;
}

void TEST(const Class1& ex){
    int pub = ex.public_int;
    int pro = ex.protected_int;
    int pri = ex.private_int;
}

Image
Answer: The program is already ill-formed here:
friend void Class2::TEST(const Class1& ex);

Class2 is incomplete, so you cannot access members of it yet. If you reorder your code such that everything is complete when it needs to be:
class Class1;

class Class2{
public:
    void TEST(const Class1& ex);
};

class Class1{
    friend void Class2::TEST(const Class1& ex);
    friend void TEST(const Class1& ex);

    // ...
};

then everything compiles fine.
Comment: This is what I found myself as well; however, this does not help when there's 'circular friendship' between `Class1` and `Class2`..


Why Backpropagation is in negative

Question: New to Backpropagation.
In this example here and in all other example we calculate new weights by finding the derivative of the sigmoid
https://repl.it/@vzhou842/An-Introduction-to-Neural-Networks
I know that derivatives can show the changing rate. like if we change the value of the variable the amount will change based on the derivative rate.
Now
the new weight is
<code>    # --- Update weights and biases
    # Neuron h1
    self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1
    self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2
    self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1

    # Neuron h2
    self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3
    self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4
    self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2

    # Neuron o1
    self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5
    self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6
    self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3
</code>
Why the new weight is minus the derivative?
why it is not to add
i mean to be something like this
<code>    # --- Update weights and biases
    # Neuron h1
    self.w1 += learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1
    self.w2 += learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2
    self.b1 += learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1

    # Neuron h2
    self.w3 += learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3
    self.w4 += learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4
    self.b2 += learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2

    # Neuron o1
    self.w5 += learn_rate * d_L_d_ypred * d_ypred_d_w5
    self.w6 += learn_rate * d_L_d_ypred * d_ypred_d_w6
    self.b3 += learn_rate * d_L_d_ypred * d_ypred_d_b3
</code>
Answer: Basically, it's an efficient implementation of the gradient descent algorithm. Gradient of a function points towards the steepest increase direction. So, the inverse of it is the steepest decrease direction. By moving towards the negative gradient (with a suitable learning rate), your cost function will decrease. If we were maximizing maximizing, we'd go towards the positive gradient. That's why if you negate your loss function, treat it as a gain function, you can actually add the gradient instead of subtracting it. Note that, the two minus signs will cancel out each other and you'll arrive at the same solution, if the procedure is deterministic, e.g. doesn't contain random interference, shuffling etc.
Comment: Thanks, but the steep down is for the MSE function, we may reach the minimal of MSE by having a higher weight w1, w2,...  still confused
Comment: steepest down is not specific to any loss function, such as mse. If we have a differentiable $f(x)$ to be minimized, and a starting point $x_0$, the gradient descent is basically applying the following $$x_1=x_0-c\nabla f(x)|_{x=x_0}$$
Comment: Thanks again, can you point me to any materials that explains this further?
Comment: I think the wiki page description is quite useful, you can go over lots of materials (videos maybe useful) online for having the intuition (and think about 1D first, draw the derivatives yourself) and then you may want to review the gradient descent section of Stepten Boyd's Convex Opt. book. Although it focuses on convex opt. problems, I find it illuminating.

Why Backpropagation is in negative


Passando uma id para server socket

Question: Cada cliente contem uma id fixa teria como eu amndar essa id para o server para depois poder mandar menssagens para clientes com ids especificos?
Server:
<code>    import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Server {

    List<PrintWriter> writers = new ArrayList<>();
    List<Thread> clients = new ArrayList<>();
    Thread t;

    public Server() {
        ServerSocket server;
        try {
            server = new ServerSocket(6000);
            while (true) {
                Socket socket = server.accept();
                t = new Thread(new listenClient(socket));
                t.setName(socket.getInetAddress().toString());
                clients.add(t);
                t.start();
                PrintWriter p = new PrintWriter(socket.getOutputStream());
                writers.add(p);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void sendAll(String text) {
        for (PrintWriter w : writers) {
            w.println(text);
            w.flush();
        }
    }

    private class listenClient implements Runnable {
        Scanner scan;

        public listenClient(Socket socket) {
            try {
            scan = new Scanner(socket.getInputStream());
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            String text;

            while ((text = scan.nextLine()) != null) {
                sendAll(text);
                System.out.println(text);
            }

        }

    }

    public static void main(String[] args) {
        new Server();

    }
</code>
Esta bem simples e como podem ver tentei fazer algo por ip mas percebi que daria conflito mais para frente e teria que ser por id mesmo passada pelo cliente
Answer: Não sei bem qual é o uso futuro do programa mas se cada cliente pudesse entrar com um nome e tu valida-ses esse nome para nunca ser repetido tinhas um bom "ID"para gerir mensagens.
Algumas linhas de codigo para dar exemplo a ver se consegues perceber:
<code>    //************ Metodos connetar | isconnect |
        public void Connect() {

            if (!Login.isEmpty()) {
                //message é uma classe onde envio toda a informação que quero enviar
                this.message = new Chatmessage();
                this.message.setAction(Action.CONNECT); //no servidor tenho um "Case" que //consoante a "action" diferente, faz diferentes usos
// exemplos de "action": CONNECT, DISCONNECT, SENDONE,SENDALL;
                this.message.setName(Login);
                this.message.setcodigo(codigo);
                this.socket =connect();

                new Thread(new ListenerSocket(this.socket)).start();

                send(message);
            }

        }
</code>
Depois no servidor tenho:
<code>while ((message = (Chatmessage) input.readObject()) != null || stop == false) {
                    Action action = message.getAction();
                    if (action.equals(Action.CONNECT)) {
                        boolean isConnect = connect(message, output);// verifica se o //cliente novo que chegou ao server se pode connetar, se a resposta for "sim" continua no //programa  se a resposta for "nao" o server nao deixa entrar:
                        if (isConnect) {
                            System.out.println(""+ message.getName());
                            if (message.getAdmin()) {
//********************** Guarda os ADMINS
                                Admins.put(message.getcodigo(), output);
//********************** Guarda em cada codigo que user é que está logado
                                mapUsercodigo.put(message.getcodigo(), message.getName());
//********************** Guarda para cada codigo o socket, que é usado para cada computador
                                mapcodigosOnlines.put(message.getcodigo(), output);
                            } else {
//********************** Guarda os USERS
                                Users.put(message.getcodigo(), output);
                                mapcodigo.put(message.getcodigo(), codigo);
                                sendonlines();

                            }

                        } else {
                            return;
                        }
                    } else if (action.equals(Action.DISCONNECT)) {
                        disconnect(message, output);
                        sendonlines();
                        return;
                    }
</code>
Esta implementação já tem muitas mudanças mas foi praticamente toda ela criada a partir deste excelente tutorial
Link

Passando uma id para server socket


Could any one help me how to stop and start azure webjobs through vsts?

Question: I have found one plugin azure app service webjob start in VSTS but I can't start/stop the webjob.Please help me guys. I am getting the below error while running the task in VSTS.
Error:
2017-09-25T12:26:37.3203696Z Preparing task execution handler.
2017-09-25T12:26:43.2660796Z Executing the powershell script:
 d:\a\_tasks\Start_cbebb02b-11c6-4e24-b5a8-0b51366d51b7\0.2.5\Start.ps1
2017-09-25T12:26:43.6830868Z ##
[error]System.Management.Automation.ParentContainsErrorRecordException: At
D:\a\_tasks\Start_cbebb02b-11c6-4e24-b5a8-0b51366d51b7\0.2.5\Start.ps1:13
char:16
2017-09-25T12:26:43.6830868Z +     $WebAppName
2017-09-25T12:26:43.6830868Z +                ~
2017-09-25T12:26:43.6830868Z Missing ')' in function parameter list.
2017-09-25T12:26:43.6830868Z
2017-09-25T12:26:43.6830868Z At D:\a\_tasks\Start_cbebb02b-11c6-4e24-b5a8-
0b51366d51b7\0.2.5\Start.ps1:17 char:1
2017-09-25T12:26:43.6830868Z + )
2017-09-25T12:26:43.6830868Z + ~
2017-09-25T12:26:43.6830868Z Unexpected token ')' in expression or
statement.

Comment: First, the ResourceGroupName is incorrect ('/' is invalid), check it in your azure portal. Secondly, The ResourceType is incorrect, it should be Microsoft.Web/sites/TriggeredWebJob or Microsoft.Web/sites/ContinuousWebJobs. On the other hand, is name of your web job called webjobname?
Comment: Thanks a lot for your help starain-MSFT. It worked well now.Really appreciating.
Comment: Hi MSFT, I have 10 continuous and 10 triggered webjobs so how can I build the code.Currently I am running the script which you provided.
 Invoke-AzureRmResourceAction -ResourceGroupName XXX -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName [web app name]/[web job name] -Action run -ApiVersion 2015-08-01 -force....So I want to stop/start multiple webjobs and my azure power shell task is not supporting more than 5 lines to run this command individually for each webjob.So please help me out.
Comment: You can pass them through the parameter and iterate the array, check the update of my answer.
Answer: Using Invoke-AzureRMResourceAction command:

Add Azure PowerShell task to build/release definition

Code:
Triggered WebJob:
Invoke-AzureRmResourceAction -ResourceGroupName XXX -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName [web app name]/[web job name] -Action run -ApiVersion 2015-08-01 -force

Continuous WebJob:
Invoke-AzureRmResourceAction -ResourceGroupName XXX -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName [web app name]/[web job name] -Action [start/stop] -ApiVersion 2015-08-01 -Force

Simple sample script with multiple webjobs:
param(
    [object[]]$webjobs,
    [string]$website,
    [string]$rg
)
foreach($wj in $webjobs){
 if($wj.typeName -eq "continuous")
 {
 Invoke-AzureRmResourceAction -ResourceGroupName $rg -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName "$website/$($wj.name)" -Action start -ApiVersion 2015-08-01 -Force
 }
 else{
  Invoke-AzureRmResourceAction -ResourceGroupName $rg -ResourceType Microsoft.Web/sites/TriggeredWebJobs -ResourceName "$website/$($wj.name)" -Action run -ApiVersion 2015-08-01 -force
 }
}

Specify parameter:
-webjobs @(@{"name"="webjob1";"typeName"='continuous'},@{"name"="webjob2";"typeName"='continuous'},@{"name"="webjob3";"typeName"='triggered '}) -website XX -rg XX

Comment: Can you please tell me where and how can I include this step as I am running only this below command :                                                            Invoke-AzureRmResourceAction -ResourceGroupName XXX -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName [web app name]/[web job name] -Action [start/stop] -ApiVersion 2015-08-01 -Force...so how can I relate the above script which you have given now.I have azure powershell plugin in that I can see 2 steps :1.inline script 2.Script arguments.So,Please help me out pal because I am new to powershell script.So asking doubts.
Comment: Is it possible to share your mail ID or contact so that I can reach out to you please ? Please help me out pal,how can I include the above script which you have given and with that script how can I stop all the web jobs.
Comment: @PDBRPRAVEEN Which point you do not clear? I update the script. If the PowerShell script is too long, you can try to remove the whitespace or you can use File Path type and specify the PowerShell script file.
Comment: Really appreciating you..It worked now..Great man..Thanks a lot for helping me in these things..
Comment: Hi MSFT, I got requirement from team like ,currently they are running the triggered jobs at particular intervals by setting up the schedule.They have setup schedule ,so as per the scheduled time those triggered jobs will run but at the time of deploy we must make sure the triggered jobs shouldn't run as it will not accept the deploy jar's into azure.So I want to run webjobs continuous jobs stop and as well as triggered jobs shouldn't run.It should check the triggered job running at the time of deploy if its running we can't deploy jar's even though if u stop continuous jobs.Please help me.
Comment: How to accomplish the above task? whether we need to add any script to check triggered jobs running or not if it runs how to deploy jar's.
Comment: And other requirement is like,currently we are passing the parameters like   -webjobs @(@{"name"="abc";"typeName"='continuous'},@{"name"="def";"typeName"='continuous'}) -website kgh -rg ghi....But team want these parameters will be passed in a separate file.So that when they add new web job they can add in a file itself.how can I call if I put the parameter script in a separate file and pass to the webjobs script.
Comment: @PDBRPRAVEEN I'd suggest asking separate questions in new forum threads.
Comment: I have opened separate forum for this request. Please help me pal.
Answer:         public static string token = System.Configuration.ConfigurationManager.AppSettings["token"];
        public static string continuouswebjobs = System.Configuration.ConfigurationManager.AppSettings["continuouswebjobs"];
        public static string triggeredwebjobs = System.Configuration.ConfigurationManager.AppSettings["triggeredwebjobs"];
        public static string hostName = System.Configuration.ConfigurationManager.AppSettings["DLUHostName"];

        public static void StopContinuousWebJob(TextWriter log)
        {
            HttpClient request = new HttpClient();
            request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
            request.DefaultRequestHeaders.Add("Authorization", token);
            if (!string.IsNullOrEmpty(continuouswebjobs))
            {
                string[] jobsArray = continuouswebjobs.Split(',');
                for (int i = 0; i < jobsArray.Length; i++)
                {
                    HttpResponseMessage response = request.PostAsync(new Uri(hostName + "continuouswebjobs/" + jobsArray[i] + "/stop"), null).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine("Job " + jobsArray[i] + " stopped  successfully.");
                    }
                }
            }
        }

Comment: Please, format your code as code (this would be virtually impossible to follow) and include a bit more of explanation along.


Showing message to the user during a Debian unattended preseeded installation

Question: During the late_command step of an unattended installation, I'm running a shell script :
d-i preseed/late_command string in-target /bin/sh -c './execute-script.sh'
When the late_command step is reached, the UI (blue background, grey window) displays a "Running preseed..." message :

I'm wondering if there is any way to lively displaying other messages based on what the execute-script.sh is doing.
I naively thought that using the regular STDOUT with echoes would do the trick but it seems more complicated.
My searches so far brought to my attention a potential use of debconf but I haven't been able to find any way.
Current version of my script reshaped according to @Andrew answer :
#!/bin/sh

. /usr/share/debconf/confmodule
. "./variables.sh"

logFile="/target${INSTALLATION_LOG_LOCATION}"
templatePath="/target/tmp/deployment_progress_tracker.templates"

cat > "${templatePath}" << 'EOF'
Template: deployment_progress_tracker/progress/fallback
Type: text
Description: ${STEP}...
EOF

debconf-loadtemplate deployment_progress_tracker "${templatePath}"
db_progress START 0 1 deployment_progress_tracker/progress

watchLogs () {
  deploymentDone=false
  while ! $deploymentDone
  do
    if [ -f "${logFile}" ]; then
      step=$(grep -E -o -a -h "Progress-step: .*" "${logFile}" | tail -1 | sed 's/Progress-step: //')
      if [ -z "${step##*$DEPLOYMENT_FINISHED*}" ]; then
        deploymentDone=true
      elif [ -n "${step}" ]; then
        db_subst deployment_progress_tracker/progress/fallback STEP "${step}"
        db_progress INFO deployment_progress_tracker/progress/fallback
      fi
    fi
    sleep 3
  done
}

(
  watchLogs;
  rm -f "${templatePath}";
  db_progress SET 1;
  sleep 1;
  db_progress STOP;
  db_unregister deployment_progress_tracker/progress;
) &

The previous script will result in the following :

And leads back to the installer menu (choosing Finish the installation will actually run again the preseeded part and fail, choosing Abort will not unmount the ISO and reboot, anyways, I'm trying to have both the unmounting and the reboot automically done) :
Answer: You will be pretty limited by debconf and it may not be worth the effort.  I don't think you'll be able to do it at all with a script run in-target.  I did have success using the following preseed snippet and script with Debian Buster.  It changes the text where Running Preseed... is displayed three times.  It will show

Step A
Step B
Running c... (the "fallback" option)

Partial preseed file to download and run a script.
d-i preseed/late_command string \
  wget -P /run http://REDACTED/my_script.sh ; \
  chmod 755 /run/my_script.sh ; \
  /run/my_script.sh

Contents of my_script.sh.
#!/bin/sh

. /usr/share/debconf/confmodule

set -e

# create a templates file with the strings for debconf to display
cat > /run/my_script.templates << 'EOF'
Template: my_script/progress/a
Type: text
Description: Step A

Template: my_script/progress/b
Type: text
Description: Step B

Template: my_script/progress/fallback
Type: text
Description: Running ${STEP}...
EOF

# use the utility to load the generated template file
debconf-loadtemplate my_script /run/my_script.templates

# pause just to show "Running Preseed..."
sleep 2

# foreach 3 steps tell debconf which template string to display
for step in a b c; do

    if ! db_progress INFO my_script/progress/$step; then
        db_subst my_script/progress/fallback STEP "$step"
        db_progress INFO my_script/progress/fallback
    fi

    case $step in
        "a")
            # run commands or scripts in the installer environment (this uses the sleep command in the installer environment)
            sleep 10
            ;;
        "b")
            # run commands or scripts in the chroot environment (this uses the sleep command from the installed system)
            in-target sleep 10
            ;;
        "c")
            # just another sample step
            sleep 10
            ;;
    esac
done

The script and the templates file generated are based on the finish-install (debian-installer package) script and templates.
Comment: @Bil5 that might work but sounds very complicated.  I would have the `logs-observer.sh` script call `in-target ./my-target-script.sh` inside of it.  `in-target` is simply a script in the installer environment that wraps a command inside some chroot setup.  It can be called from your script and does not have to be called directory from `late_command`
Comment: I guess it depends how specific you want the UI updates to be. I added to the sample script to show how it can update the UI and then run a command or script.  This includes the ability to run a command or script `in-target`.  The UI can only be updated again after the command or script finishes.
Comment: Thanks for the great idea, based on it, why the following would not work?

`d-i preseed/late_command string /bin/sh logs-observer.sh &; in-target --pass-stdout /bin/sh -c './my-target-script.sh > outputlog'`

 - `myscript.sh` would echoe the different steps a, b, c... they would be saved to `outputlog`
 - `logs-observer.sh` would run an infinite loop (until he reads "DONE") and read the last step wrote in the "shared" `outputlog` and update the message accordingly.

Of course, the steps would be defined beforehand in `logs-observer.sh`, likewise you did in your `my-script.sh` file.
Comment: your suggestion works flawlessly many thanks, however, doing the way you said (`in-target ./my-target-script.sh` and from it calling `/bin/sh logs-observer.sh`), I'm unable to make work any `db_progress INFO` command when calling it directly from the `logs-observer.sh` (having of course sourced `confmodule` & generated the template beforehand). The only way I found, is doing it directly from `my-target-script.sh`, and thus both scripts have to communicate each other and a log file is the only way I found. Any thought?
Comment: I can confirm that this way works well, and I figured out a way to call every debconf command from the installer script. I'm now facing another tough issue, after I'm done with the script, instead of automatically exiting the installer, ejecting the cdrom and rebooting (as configured in the preseed and successfully tested before debconf stuff), it goes back to the installer menu and doesn't allow to simply reboot without relaunching the installation.  I noticed this message in syslog: `Menu item 'finish-install' succeeded but requested to be left Unconfigured`
Comment: I added the current version of the script I'm trying out in my first comment so we can discuss it.
Comment: After reflection it might be out of the scope of my initial question, I wanted here to see some messages in the installer, and thanks to your answer it works. It sounds cleaner to create another subject for my new concern. Thank you again. https://serverfault.com/questions/1074794/debian-installer-wont-exit-after-preseeded-installation


importlib.metadata error on pre-commit tool

Question: I have installed pre-commit 3.0.1 via asdf. When I try to run pre-commit -v throwing the following error
Traceback (most recent call last):
  File "/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/python", line 47, in <module>
    raise SystemExit(main())
  File "/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/python", line 34, in main
    runpy.run_module(args.m, run_name='__main__', alter_sys=True)
  File "/Users/san/.pyenv/versions/3.7.9/lib/python3.7/runpy.py", line 205, in run_module
    return _run_module_code(code, init_globals, run_name, mod_spec)
  File "/Users/san/.pyenv/versions/3.7.9/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/Users/san/.pyenv/versions/3.7.9/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/wheels/pre_commit-3.0.1-py2.py3-none-any.whl/pre_commit/__main__.py", line 3, in <module>

  File "/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/wheels/pre_commit-3.0.1-py2.py3-none-any.whl/pre_commit/main.py", line 9, in <module>
  File "/Users/san/.cache/pre-commit-zipapp/6Bkef3U7os33XPapd4VZ7HEfyUexbeBTjOn51afz0r8/wheels/pre_commit-3.0.1-py2.py3-none-any.whl/pre_commit/constants.py", line 3, in <module>
ModuleNotFoundError: No module named 'importlib.metadata'

Python version: 3.7.9
asdf version: v0.11.1
Answer: you've forced the installation of pre-commit 3.x to a version which it does not support
pre-commit is python3.8+ only (it uses python_requires>=3.8 in the metadata).  pip refuses to install the version on older python's so somehow you've bypassed that safeguard

disclaimer: I wrote pre-commit
Answer: Upgrading the python to version 3.8.7 solved the issue, since for the pre-commit minimum required Python version is 3.8.
Answer: Pre-commit's PyPi page states that the minimum required Python version is 3.8.
Requires: Python >=3.8
Answer: If you want to use python version under 3.8, install version 4.x of importlib-metadata.
Example work with me: python 3.7.10 and importlib-metadata == 4.10.0


Regex to select csv values from string

Question: I typically have a string that might look like the following and I would like to extract the contents and parse it into an array by splitting the values.
COUNT(123,453,123)

For validation reasons it might so happen that a comma is left on the end of contents like so.
COUNT(123,453,123,)

My code so far is as follows.
Regex.Match(testString, @"(?<=\().+?(?=\))").ToString().Split(',').Select(int.Parse).ToList();

It works fine for the first case but will throw an exception on the latter case.
Exception
input string was not in a correct format
How can I make the regex ignore a comma if there is no additional number after it?
Answer: (?<=\().+?(?=,?\))

             ^^

Just add that to lookahead.See demo.
https://regex101.com/r/rO0yD8/14

Regex to select csv values from string