text:
Q: Unable to rename the resource class name in Visual Studio Unable to rename the resource class name. For the following example (picture below), Resource2 can't be renamed in any way. Either in props, in place in the Solution Explorer or elsewhere.
Could it be a bug in Visual Studio 17.3.5 ?
Please note it seems resources has received some changes between 17.3.4 and 17.3.5.
Anybody has an idea on how to do it?

A: I just found it. It could only be changes through the "Class View".


text:
Q: Remastersys and Hostname An unsuccessful installation attempt of Remastersys installation changed my ubuntu 12.04 precise desktop hostname.
Am unable to revert to my original hostname of my desktop. Changing /etc/hostname ; /etc/hosts ; sysctl kernel.hostname and restarting the services did not help.
After reboot something rewrite my hostname to "custom".
Appreciate all your comments and help.

A: As you can read here:

The host name is usually set once at system startup in /etc/rc.d/rc.inet1 or /etc/init.d/boot (normally by reading the contents of a file which contains the host name, e.g. /etc/hostname).

So you only have to set it in /etc/hostname

redpajama_set_name: RedPajamaStackExchange


text:
Q: What exactly is meant by "observed" when talking about the wave-particle duality? When talking about the wave-particle duality, teachers and books say that when you send a single photon through a slit, it makes a wave pattern. But if you send that particle through the slit and "you observe it directly", then it appears as a single point (a particle).
What is meant by "observe"? Is that like with your eyeballs? Or is that with some measuring device? It's unclear what that word means, it could mean anything haha.
One reason I am wondering is because, it seems like the act of trying to measure it directly (if "measure with a device" is what is meant by observe) would mean sending out some sort of radiation or particle itself, so yes, that would mess with the experiment. But maybe I just don't quite understand yet, so looking forward to a bit of clarification.

A: Suppose we represent the wavefunction of the photon as $\psi_p$ and the wavefunction of the observer as $\psi_o$. As long as the photon and observer do not interact in any way we can write the total wavefunction as a product:
$$ \Psi = \psi_p\psi_o \tag{1} $$
The trouble is that you can't make any measurement of the photon without interacting with it, and as soon as you do this you become entangled with the photon. Entanglement means the total wavefunction of you and the photon is no longer separable into a product as in equation (1).
Exactly what happens next depends on what interpretation of wavefunction collapse you favour. My own preferred interpretation is decoherence/many worlds, and viewed in this way after the interaction the total wavefunction evolves to become roughly separable again so you once again get:
$$ \Psi' = \psi'_p\psi'_o $$
But the wavefunction of the photon has been changed by the interaction, so $\psi_p \ne \psi'_p$, and this will affect the subsequent evolution of $\psi'_p$ as the photon passes through the slits and it will therefore affect the diffraction pattern produced.
Exactly what happens will depend on the strength of the interaction, because this will determine how much the wavefunction is changed. It is possible to make the measurement a very weak interaction, in which case you get a weak measurement and the diffraction pattern wouldn't be affected. However in these sorts of arguments the measurement is usually taken to be one that tells you the particle position, and in that case the interaction would have to be strong enough to significantly reduce the uncertainty in the particle position so it's no surprise that this significantly changes the diffraction pattern.
Note that I haven't assumed anything about the observer other than that it can be described by a wavefunction and that it interacts with the photon. So many systems can be observers - the effect they have just depends on the strength of the interaction.

A: I would generally support Ayesha's answer, in that it explains that decoherence is instigated by the microscopic interacting with the macroscopic.
As with many things in Quantum Physics, this is evidently true at the extremes (e.g. putting a detector in the path of a photon in the dual slit experiment), but it is not clear when something is considered macroscopic. For example, somewhere between coupling an atomic spin to a single other atom and coupling to a million other atoms, we (and presumably the universe) say that decoherence has occurred, and the wavefunction has collapsed.
One answer is to look at the Density matrix. Consider that a pair of photons have a 2x2 density matrix. If we entangle the photon polarisations like-for-like, then we have either HH or VV, which would be a density matrix thus:
     H    V
  H  0.5  0
  V  0    0.5

Von Neumann tells us that measurement always increases entropy inside the system, thus decreasing the quantum information contained in it. So even if we perform a measurement that is unrelated, like checking for HV states, we start to corrupt the matrix. So perhaps it becomes:
               First
               H     V
Second     H  0.44   0
           V  0.1    0.46

Suppose we further entangle this pair with another pair (still in its clean state), such that if the second photon of the first pair is V, then so is the first photon of the second pair (and the same for H):
                First pair
                  HH       HV      VH       VV
            HH   0.44
Second      HV
 Pair       VH
            VV            0.1              0.46

If that second pair was a bit sullied, and looked more like:
HH 0.48, HV 0.03, VH 0.07, VV 0.42

Then we have:
       HH          HV        VH       VV
  HH  0.48x0.44            0.48x0
  HV  0.03x0.44            0.03x0
  VH             0.07x0.1          0.07x0.46
  VV             0.42x0.1          0.42x0.46

Renormalised (/0.4988):
       HH       HV     VH    VV
  HH  .4234
  HV  .0265
  VH          .0140         .0646
  VV          .0842         .3873

We can see how the original purity of the superposition is being polluted by the entropy, and as the space increases with the addition of more particles, this will further erode the original state. Note in particular how the HHHH state has P=42.34%, while the VVVV state has P=38.73%. Clearly this erosion will erode one of the original states more than the other, so after a few interactions we might expect one to disappear below the noise floor, leaving a single preferred state. In the experiment, this would come out as a 'decoherence' in which the increasing interaction with the environment dissipates the original superposition through an ever larger space until random noise takes over.
The signal vs noise metaphor is apt, in that it appears to be the quantum information stored in the states that it eroded. This is the origin of the Quantum Error Correction methods designed to use encodings to sustain a coherent state for longer.
Thus, 'observation' really means the coupling of a quantum state to a much larger system, and in doing so polluting the quantum information stored within with entropy and thus undergoing decoherence.

A: I'll illustrate by referring to the Schrodinger's cat thought experiment. The experiment consists of a cat in a box, to which is attached a small amount of a radioactive substance. In the course of an hour, the substance may or may not emit a particle. If it does, then a Geiger counter triggers a can of cyanide, killing the cat. After an hour, the cat's wave function has the form $$\psi_{cat} = \frac{1}{\sqrt{2}}\left( \psi_{alive} + \psi_{dead}  \right)$$
Now, herein we see the flaw of the term "measurement" - it suggests involvement by a human observer. Prior to your observation of the cat, the cat is neither alive nor dead, but rather a linear combination of the two states, and if the cat is indeed dead, you killed her by looking in the window.
This of course sounds inherently absurd. We resolve the paradox by considering the triggering of the Geiger counter the "measurement," not the intervention of the human observer. A measurement, here, then, consists of an interaction between the microscopic system (the decaying particle) and the macroscopic system (the triggering of the Geiger counter). All in all, "measurement" is a rather poor term, as it inherently suggests the presence of a human observer. Heisenberg suggested the term "event" instead.
(In some formulations of quantum mechanics, it is even possible to dispense with the concept of "measurement" entirely, and instead have the "measuring" apparatus and the system itself be described by a wave function).

A: To also give a more direct reply to your photon in a slit example, in simple words:
Observing the photon passing through the slit is not just a conceptual act, it  means placing a photon detector at the slit and as the photon passes through, its state is measured and since a measurement in quantum mechanics comes at the cost of perturbing the original state of the system, (here meaning whatever mechanism the detector uses, it will have an influence on the state of the photon, e.g. light momentum is transferred to electrons).
Consequently the photon will collapse into one of its eigenstates (on which one will depend on its initial state of superposition) and will not be in an unknown state anymore (i.e. a superposition of states), meaning its state is perfectly known and you will not observe an interference for its intensity spectrum, all the fringes disappear.
Finally let's say if you keep measuring (i.e. in your words observing) the collapsed photon, using the same detector, you will observe the same state for the photon, but if you change detectors (like changing angle of polarizer, simply a different basis) then you may further change the state of the photon, by the same principles.
In order to get used to these ideas, it's best if you start by reading examples of measurement of photon polarization which will also introduce you to Dirac's bra-ket notation in a rather straightforward manner.


text:
Q: findOne use in mapreduce mongodb I want to use findOne in map reduce. What is wrong with my code? My error is:
Command 'mapreduce' failed: exception: map invoke failed: JS Error: TypeError: user has no properties nofile_b:3 (response: { "errmsg" : "exception: map invoke failed: JS Error: TypeError: user has no properties nofile_b:3", "code" : 9014, "ok" : 0.0 })
string map = @"
function() {
    var movie = this;
    var user = db.users.findOne({UserId : parseInt(movie.UserId)});
    emit( movie.UserId, {Name:user.Name});
}";

string reduce = @"
function(key, values) {
    var result =values;
    return result;
}";

string finalize = @"
function(key, value){
  return value;

}";

Under c# code
var collection = database.GetCollection("movies");
var options = new MapReduceOptionsBuilder();
options.SetFinalize(finalize);
options.SetOutput(MapReduceOutput.Inline);
var results = collection.MapReduce(map, reduce, options);
lbResultList.Items.Clear();
foreach (var result in results.GetResults())
{
     lbResultList.Items.Add(result.ToJson());
}

I solve my problem map function change
function () {

var user = db.users.find({UserId:this.UserId});
var userName ='';
var userSurName ='';
user.forEach(function(u) {
    userName = u.Name;
    userSurName = u.SurName;
});
emit(
    this._id,
    {title: this.Title,category:this.Category,UserName: userName,UserSurName: userSurName}
);

}
I think it is not logical,like sub query this solve. What can I do this case?

A: It looks like you're trying to do an SQL JOIN.  MapReduce is the wrong tool for that.  You'll actually want to just break this into an aggregate operation to get an array of UserID's and a query operation to get the names of users:
Something like this in mongo shell:
var UserIDArray = [];
movieCollection.aggregate({$group: {_id: "$UserId"}}).forEach(function (v) {
    UserIDArray.push(v._id);
});

UserIDNamePairs = userCollection.find({_id : {$in: UserIdArray}}, {_id: "$name"}).toArray();


text:
Q: jQuery show and hide PHP generated content I am a total jQuery noob. But I need to use it for a script in combination with PHP. The idea is that people can add a new lawyer on the backend and that a button and content are added to the page. On the site you would then be able to cycle through the lawyers by using the buttons as in the example below.
http://strak-design.com/varlaw/team
Here is the site in question and how I would like it to work. Right now it's simply smoke and mirrors for my clients and if I add and remove lawyers dynamically it obviously breaks.
Here's my HTML/PHP. Any ideas? In don't even know where to start...
<?php foreach ($team as $lawyer) { ?>
<div id="<?php echo $lawyer->id?>_button" class="lawyer_title_small title-<?php echo $lawyer->title_colour;?>">

<?php echo $lawyer->name?>

<?php }?>

<?php foreach ($team as $lawyer) { ?>
<div id="<?php echo $lawyer->id;?>" class="team_info">

        <img src="img/team/<?php echo $lawyer->picture;?>"/>

                TEL:
                <?php echo $lawyer->tel;?>

                GSM:
                <?php echo $lawyer->gsm;?>

                MAIL:
                <?php echo $lawyer->mail;?>

OVER <?php echo $lawyer->name;?>

        <?php echo $lawyer->about;?>

VOORKEURKENNIS:

        <?php echo $lawyer->knowledge;?>

<?php }?>

If it isn't clear, I'll try to explain further. Thanks a lot!

A: The more relevant code is the javascript in /varlaw/js/main.js, though it is also useful to have seen the PHP.
First, in PHP, build the lawyer buttons inside a containing div as follows :

    <?php foreach ($team as $lawyer) { ?>
    <div id="<?php echo $lawyer->id?>_button" class="lawyer_title_small title-<?php echo $lawyer->title_colour;?>">

<?php echo $lawyer->name?>

    <?php }?>

Second, in PHP build the "team_info" divs inside a containing div as follows :

    <?php foreach ($team as $lawyer) { ?>
    <div id="<?php echo $lawyer->id;?>" class="team_info">

            <img src="img/team/<?php echo $lawyer->picture;?>"/>

                    TEL:
                    <?php echo $lawyer->tel;?>

                    GSM:
                    <?php echo $lawyer->gsm;?>

                    MAIL:
                    <?php echo $lawyer->mail;?>

OVER <?php echo $lawyer->name;?>

            <?php echo $lawyer->about;?>

VOORKEURKENNIS:

            <?php echo $lawyer->knowledge;?>

    <?php }?>

You now have two congruent structural divs; corresponding child elements of these divs have the same index within their parent div. This is important as it allows for very simple, efficient javaScript.
Third, in javaScript replace all the $("#marc_button")..., $("#dirk_button")... etc. code with :
$(".lawyer_title_small").on("click", function() {
    var $this = $(this);
    if ($this.hasClass("lawyer_title_main")) { //this trap may be unnecessary
        return;
    } else {
        //hide all lawyer divs, then selectively show the appropriate lawyer div
        //ie. the div with the same index as the button that was clicked
        $(".team_info").hide().eq($this.index()).show();
    }
});

If the trap is indeed unnecessary, then the click handler will simplify to :
$(".lawyer_title_small").on("click", function() {
    $(".team_info").hide().eq($(this).index()).show();
});

Now, your PHP can build the page with as few or as many Lawyers as it likes and the javascript will handle them.


text:
Q: Как написать с помощью RxJava2 простую итерацию как в примере Вот есть такой метод который я использую для того, чтоб при получении ответа с сервера сделать парс сразу в енам
@JsonCreator
    public static eTaxCode getTaxCodeByIdOrDefault(int iTaxCode)
    {
        eTaxCode result = DEFAULT;

        for (eTaxCode tmp : eTaxCode.values())
        {
            if (tmp.getTaxCodeId() == iTaxCode)
            {
                result = tmp;
                break;
            }
        }

        return result;
    }

Все просто я беру значения енама прохожу по каждому и если есть совпадение, то возвращаю это значение если нет, то возвращаю дефолтное значение.
Теперь хочу сделать тоже самое с помощью RxJava2 (знаю, что возможно это не тот случай и что стандартный подход очень крутой, но интересно понять как это сделать)
Я пробовал сделать как то так(на таком же примере)
@JsonCreator
    public static eSingDetails getSingDetails(int iSignDtls)
    {
        eSingDetails result = DEFAULT;

        Observable.fromArray(eSingDetails.values())//
                  .filter(iValue -> iValue.getSignDtls() == iSignDtls)//
                  .isEmpty()//
                  .subscribe(iIsEmpty ->
                  {
                      if (iIsEmpty)
                      {

                      }
                      else
                      {

                      }
                  });

        return result;
    }

Но все равно не то, что то получается...
Как это правильно сделать?

A: Сама функция может выглядеть так:
public static Single<eTaxCode> getTaxCodeByIdOrDefault(int iTaxCode)
{
   return Flowable.fromIterable(eTaxCode.values())
                  .takeUntil(value -> {
                     return value.getTaxCodeId() == iTaxCode;
                  })
                  .filter(value -> value.getTaxCodeId() == iTaxCode)
                  .single(DEFAULT);
}

А вызов соответственно так:
getTaxCodeByIdOrDefault(taxCodeId)
   .subscribe(taxCode -> {
      // что-то делаем
   });

Документация по оператору takeUntil
Документация по Single


text:
Q: My iPhone XR keeps making emergency calls without any interaction from me This is really weird: three times within the past week, my iPhone XR has called my mother-in-law via the Emergency Call feature, without any apparent interaction from me.
Each time this has happened, the phone has been in my pocket. When I realize that it's calling (because I can faintly hear the phone ringing over the internal speaker), I've taken it out of my pocket and it's on an "Emergency Call" screen (white background with red text) and is dialing my mother-in-law's number.
I do have my mother-in-law listed as an emergency contact in my iPhone's Medical ID, but my mother and wife are also listed there as emergency contacts, and it's never called either of them.
I don't know of any way to dial an emergency contact other than to press and hold the side and volume buttons, then choose Medical ID, then scroll down and tap an emergency contact. I can't possibly be doing that by accident while the phone is in my pocket, so I have no idea how this is getting triggered.
Is it possible Siri is mishearing something and thinking I want to make an emergency call? (I do have "Hey Siri" turned on).
Any ideas? And how do I get it to stop?


text:
Q: Maven release plugin - pom.xml update via service account I am trying to do Continuous integration

*

*Created stage checkout

*created stage build sh "mvn -Dmaven.test.skip=true clean deploy -Dusername=${username} -Dpassword=${password}"

*Created stage release sh "mvn release:prepare release:perform -Dusername=${username} -Dpassword=${password}" -Dscmusername${username} -Dscmpassword=${password}"

*At release stage I am reading the version from pom.xml to append in the path of generated artefacts at artifactory.

*I need to place the jars in the path where the version number is mentioned in the path as a folder – eg dev/version/modules/jar

*Here the pom.xml gets updated via a service account while performing maven release- Is there a way that I get the right version to be appended in the folder path of artifactory without doing any commits to pom.xml via service account


text:
Q: Have a div cling to top of screen if scrolled down past it I have a div which, when my page is first loaded, is about 100px from the top (it holds some buttons etc. for the page).
When a user scrolls past it, I would like the div to "follow" the user in that it attaches to the top of the screen. When the user returns to the top of the page, I want it back in its original position.
Visualization - xxxxx is the div:

Default (page load)          User vertically scrolled well past it
---------                    ---------
|       |                    |xxxxxxx| < after div reaches top of screen when
|xxxxxxx|                    |       |   page is scrolled vertically, it stays
|       |                    |       |   there
---------                    ---------

A: The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.
Derived from the code viixii.com uses I ended up using this:
function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.
Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.
Just place an empty div with a class acting like an anchor just above the element you want to have fixed.
Like so:

Your sticky content

All credit for the code goes to viixii.com

A: There was a previous question today (no answers) that gave a good example of this functionality.  You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

*

*Page loads and element is position: static

*On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

A: The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
   // Cache selectors outside callback for performance.
   var $window = $(window),
       $stickyEl = $('#the-sticky-div'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    });

This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
  #the-sticky-div.sticky {
     position: fixed;
     top: 0;
  }

EDIT- Modified code to cache jQuery objects, faster now.

A: Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

Some buttons


text:
Q: In SE's "All Network Sites", what does "answered" statistic mean? Does it mean have non-zero answers or does it mean have accepted answers?

A: From OK, Now Define "Answered", answered questions are those that have at least one answer with one upvote (or accepted).  Any other questions (with no upvoted or accepted answers) will appear in the Unanswered tab.


text:
Q: Global Picklists: Apex assignment I'm currently developing an update to our application inside a sandbox using the new feature of Global Picklists. Unfortunately I can't simply assign one exact picklist value (exposed as a string) in Apex to the field associated with the global picklist, as it throws the error:

INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST


text:
Q: Quadprog to constrain coefficients of linear regression I need some help. I need to fit a linear model (y ~ X1) with the following constraints:
Intercept + Beta1 <= 1; and both Intercept and Beta1 need to belong to [0,1]
After looking how to do this in R, I found that Quadprog seems like the best option. However, I do not fully understand how to set those constraints. I take an example form a webpage (http://zoonek.free.fr/blosxom/R/2012-06-01_Optimization.html) to adapted to my needs, but the sum of coefficients are greater than 1 in some cases (by teh way, I have to run this model on different data frames, and in some the constraint is ok, but in some cases Intercept + beta1 > 1).
My script is:
n <- 100
x1 <- rnorm(n)
y <- .3 * x1 + .2 * x2 + .5*x3 + rnorm(n)
X <- cbind(1, x1)
Mod <- solve.QP(t(X) %*% X, t(y) %*% X, cbind(matrix(1, nr=2, nc=1),
          diag(2),
          -diag(2)),
          c(1, 0, 0, -1,-1),
          meq = 1) ""

As I told before, my problem is that in some cases, intercept plus beta1 are greater than 1, and I do not understand how to set that constraint in Quadprog with that matrix type.


text:
Q: Fixing the value of template parameter Is the following permissible when using templates.
template <typename PAR1 = X,
          typename PAR2 = Y,
          typename PAR3 = Z>
class Base {
   //some stuff inside
};

template <typename PAR1
          typename PAR2 = Z>
class Derived : public Base <PAR1,Y,PAR2> {
   //some stuff here
};

what i want here is that Derived class should always have the PAR2 type as Y.
Can we fix the parameter value when others parameters after it as optional while inheriting ?

A: I hope you wanted something like this. So, it is possible
class X{};
class Y{};
class Z{};

template <typename PAR1 = X,
          typename PAR2 = Y,
          typename PAR3 = Z>
class Base {
   //some stuff inside
};

template <typename PAR1, typename PAR3>
class Derived : public Base <PAR1,Y,PAR3> {
};

int main()
{
    Derived<X, Z> d;
}

EDIT 2:
Though unrelated to the OP, it is good to know that in partial specialization, the partial specialized class template parameters have the default value of the primary template
class X{};
class Y{};
class Z{};

template <typename PAR1 = X, typename PAR2 = Y, typename PAR3 = Z>
class Base {
public:
    void f() {
        std::cout << typeid(PAR1).name() << " " << typeid(PAR2).name() << " " << typeid(PAR3).name() << std::endl;
        std::cout << 1;
    }
};

template<typename PAR2, typename PAR3> class Base<X, PAR2, PAR3>
{
public:
    void f() {
        // PAR2 is by default Y and PAR3 is by default Z
        std::cout << typeid(PAR2).name() << " " << typeid(PAR3).name() << std::endl;
        std::cout << 2;
    }
};

int main()
{
    Base<X> b;   // instantiation of partially specialized template
    b.f();
}

A: I guess you are confused by template default value and partial specialization. Because Base takes 3 parameters with default value, you could instantiate Base with from 0 to 3 parameters.
Base<> b1;              #1, PAR1=X,   PAR2=Y,   PAR3=Z
Base<int> b2;           #2  Par1=int, PAR2=Y,   PAR3=Z
Base<int, int> b3;      #3  PAR1=int, PAR2=int, PAR3=Z
Base<int, int, int> b4; #4  PAR1=int, PAR2=int, PAR3=int

In Derived class, you are inheriting from situation #4 which is of course valid.
So you can inherit from any form of Base above.
Base template parameter can be independent type(value) or passed from template <typename PAR1, typename PAR2 = Y>
template <typename PAR1,
          typename PAR2 = Y>
class Derived : public Base <> {
};

OR
template <typename PAR1,
          typename PAR2 = Y>
class Derived : public Base <PAR1> {
};

OR
template <typename PAR1,
          typename PAR2 = Y>
class Derived : public Base <PAR1, PAR2> {
};


text:
Q: Выделение кривой области WPF Здравствуйте, есть карта страны(изображение). Нужно обработать клик по областям. Никогда не работал на WPF, по координатам получится криво, уже пробовал, что можно еще сделать?
Нужно обработать клик по области, ну и при наведении мыши на область подсветку границы области.
<Image Height="204" HorizontalAlignment="Left" Margin="226,21,0,0" Name="image2" Stretch="Fill" VerticalAlignment="Top" Width="352" Source="/Belarus;component/Images/3.png" ImageFailed="image2_ImageFailed" MouseUp="Clicked" />

    private void Clicked(object sender, MouseButtonEventArgs e)
    {
        //string pos = "X - " + e.GetPosition(this).X + " Y - " + e.GetPosition(this).Y;
        //MessageBox.Show(pos);
        //if (e.GetPosition(this).X >= 232 && e.GetPosition(this).X <= 566 &&
            //e.GetPosition(this).Y >= 27 && e.GetPosition(this).Y <= 147)
        //MessageBox.Show(e.Source.ToString());
    }

все что у меня есть

A: Этого можно добиться, хотя и не совсем просто.
Для начала, вам нужно получить картинки каждой из областей. Обратитесь за этим к вашему граф. дизайнеру. На картинке должна быть только область, а остальное обязано быть транспарентным.
Теперь, нам нужно определить клик на нетранспарентной области. Для этого проще всего использовать специализированный контрол, и переопределить hit testing.
Тогда мы сможем воспользоваться встроенными в WPF процедурами.
Наследуемся от Image:
public class OpaqueClickableImage : Image
{
    static int transparentAlpha = 128;

    protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
    {
        if (Source == null)
            return null;
        var source = Source as BitmapSource;
        if (source == null)
            throw new NotSupportedException("Need BitmapSource");
        if (source.Format != PixelFormats.Bgra32)
            throw new NotSupportedException("Need 32-bit pixel format with alpha channel");

        // Get the pixel of the source that was hit
        var x = (int)(hitTestParameters.HitPoint.X / ActualWidth * source.PixelWidth);
        var y = (int)(hitTestParameters.HitPoint.Y / ActualHeight * source.PixelHeight);

        var pixel = new byte[4];
        source.CopyPixels(new Int32Rect(x, y, 1, 1), pixel, 4, 0);

        if (pixel[3] < transparentAlpha)
            return null;

        return new PointHitTestResult(this, hitTestParameters.HitPoint);
    }
}

(Код украден с благодарностью украден здесь.)
Отлично, попробуем использовать. На клик навесим наш обработчик, а на IsMouseOver добавим glow-эффект через стиль.
<Window.Resources>
    <Style TargetType="Image" x:Key="ImageWithGlow">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Effect">
                    <Setter.Value>
                        <DropShadowEffect
                            ShadowDepth="0" Color="White"
                            Opacity="0.8" BlurRadius="8"/>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid Background="Red">
    <local:OpaqueClickableImage
        Source="transparentheart.png" Style="{StaticResource ImageWithGlow}"
        MouseLeftButtonDown="OnImageClick"/>
</Grid>

(Я специально нарисовал картинку с сердечком, можно использовать на 8-ое марта.)
Результат (на второй анимации для примера несколько одинаковых картинок рядом):


text:
Q: Unable to connect to online mysql database using javaFX I recently made a project which involved connecting to a mysql database online using Swing in java. I then decided to convert the project to javaFX and tried to replicate the code to connect to a mysql database.
This is my code:
package virtlib;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import java.sql.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/**
 *
 * @author param
 */
public class FXMLDocumentController implements Initializable {
    private Connection con;
    private Statement st;
    private ResultSet rs;
     private ResultSet rs2;
    private Stage stage;
    @FXML
    private Label label;
    @FXML
    private Button login;
    @FXML
    private PasswordField password;
    @FXML
    private TextField username;

    @FXML
    private void handleButtonAction(ActionEvent event) {

        try{

            Class.forName("com.mysql.cj.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://db4free.net:3306/parambase","theboss12k","Password");//Password has been changed
            st=con.createStatement();
            label.setText("Connection success !");

        }
        catch(Exception ae){
           label.setText("We are unable to connect to our servers. Please check your internet connection and restart the app !");
        }

    }
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

}

This is the code of the FXML file
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.Pane?>

<AnchorPane id="AnchorPane" prefHeight="494.0" prefWidth="409.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/16" fx:controller="virtlib.FXMLDocumentController">
    <children>
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" prefHeight="18.0" prefWidth="276.0" />
      <Pane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="297.0" prefWidth="410.0" style="-fx-background-color: white;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
              <Button fx:id="login" layoutX="129.0" layoutY="331.0" onAction="#handleButtonAction" prefHeight="26.0" prefWidth="70.0" text="Login" />
            <PasswordField fx:id="password" layoutX="129.0" layoutY="276.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="26.0" prefWidth="222.0" />
            <TextField fx:id="username" layoutX="129.0" layoutY="229.0" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="26.0" prefWidth="222.0" />
            <Label layoutX="40.0" layoutY="280.0" text="Password" />
            <Label layoutX="38.0" layoutY="233.0" text="Username" />
            <Label layoutX="129.0" layoutY="400.0" prefHeight="17.0" prefWidth="222.0" textFill="#e70d1b" />
         </children>
      </Pane>
    </children>
</AnchorPane>

However, when I hit run, it just crashes, and I get the error that "Java SE Binary platform has stopped working". It was working perfectly in my previous application using swing. The only change I made when switching to javafx was that I used jdk 1.8 instead of jdk 11, as I was forced to use netbeans 8.2, and netbeans 8.2 doesn't seem to support jdk 11 (Using which my previous project was developed).

A: I just went through the same issue and rewrote my SQL connection lib.
Maybe you can use it for your project, it works for me both local and online.
My HandleSqlBdSimple class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;

public class HandleSqlDbSimple {

    private Connection connection = null;
    private Statement statement;
    private ResultSet resultSet;
    private boolean isConnected = false;

    // Creating objects for connection
    private String aHost;
    private String aPort;
    private String aDatabase;
    private String aUser;
    private String aPassword;
    private String aDriver;
    private String aPrefix;

    public HandleSqlDbSimple(String host, String port, String database, String user, String psw, String driver, String prefix){
        this.aHost = host;
        this.aPort = port;
        this.aDatabase = database;
        this.aUser = user;
        this.aPassword = psw;
        this.aDriver = driver;
        this.aPrefix = prefix;

        //      Connection example:
        //      aHost = "localhost";
        //      aPort = "3306";
        //      aDatabase = "testdb";
        //      aUser = "root";
        //      aPassword = "kungfu";
        //      aDriver = "com.mysql.jdbc.Driver";
        //      aPrefix = "jdbc:mysql:";
    }

    private synchronized void loadConnection(){

        try {
            Class.forName(aDriver);

            connection = DriverManager.getConnection(aPrefix + "//" + aHost + ":" + aPort + "/" + aDatabase +
                    "?user=" + aUser + "&password=" + aPassword);

            isConnected = true;

        } catch (ClassNotFoundException e) {
            isConnected=false;
            e.printStackTrace();
        } catch (SQLException e) {
            isConnected=false;
            e.printStackTrace();
        }

        if(isConnected){
            try {
                connection.setAutoCommit(false);
                statement = connection.createStatement();
                statement.setFetchSize(100000);
                System.out.println("Connection open!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("Is not connected!");
        }
    }

    private synchronized void closeConnection(){
        if (isConnected) {
            try {
                if (resultSet != null){
                    resultSet.close();
                };
                statement.close();
                connection.close();
                System.out.println("Connection Closed!");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("My Error in connection close: " + e);
            }
        }
    }

    public boolean writeToDB(String stmt){
        boolean aResult = false;

        // Open the connection to the database
        loadConnection();

        try {
            if(isConnected){
                statement.executeUpdate(stmt);
                connection.commit();

                aResult = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // Close the DB again
        closeConnection();

        return aResult;
    }

    public String[][] readFromDB(String stmt) {
        String[][] data = null;
        Vector<String[]> aVectorBuffer = new Vector<String[]>();
        String[] colData = null;

        loadConnection();

        if(isConnected){

            try {
                resultSet = statement.executeQuery(stmt);
                ResultSetMetaData aResultSetMetaData = resultSet.getMetaData();

                // Get number of columns
                int aColCount = aResultSetMetaData.getColumnCount();
                colData = new String[aColCount];

                while (resultSet.next()) {

                    for(int col=0; col<aColCount; col++){

                        colData[col] = resultSet.getString(col+1);

                    }

                    aVectorBuffer.add(colData);
                    colData = new String[aColCount];
                }

                closeConnection();

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        data = new String[aVectorBuffer.size()][colData.length];

        for(int row=0;row<aVectorBuffer.size(); row++){
            for(int col=0;col<colData.length; col++){

                data[row][col] = aVectorBuffer.get(row)[col];

            }
        }

        return data;
    }

}

Remember to include the mysql .jar file ofcourse. I use the "mysql-connector-java-8.0.26.jar". But i see you already have this.
Then you could use a method something like this..
@FXML
    private void handleButtonAction(ActionEvent event) {

        HandleSqlDbSimple db = new HandleSqlDbSimple("host", "port", "database", "user", "psw", "driver", "prefix");

        db.writeToDB("your write statement");

        String[][] result = db.readFromDB("your read statement here");

    }

Hope it helps ;)


text:
Q: jQuery Full Calendar UnblockUI I sucessfully block the UI while events are loading.  I try to un-block the UI when all events are rendered with no luck..  Is there a better place to call Unblock?
    function getCalendar() {
    $("#calendar").fullCalendar({
        loading: function (bool) {

            $.blockUI();
        },
    eventAfterAllRender: function(view)
        {
            $.unblockUI();
        },
     });


text:
Q: PHP: Remove line ending with ( and remove line starting with ) and grab second word of every line I have a sample string as shown below. In the string, how can I remove line ending with ( and remove line starting with ) and grab second word of every line?
This is some text (
some more text,
one line text,
more and more text available,
this one is even longer and even more text is available,
) this is the last line;

This is also some more text (
Second time some more text,
one line text second time ,
Once again more and more text available,
finally this one is even longer and even more text is available,
) this is the last line;

The string shown above comes from a text file. Can be either pasted in a textarea or a file could be uploaded and this text will be read from the file. So in the example shown above, expected output is:
some more text,
one line text,
more and more text available,
this one is even longer and even more text is available,

Second time some more text,
one line text second time ,
Once again more and more text available,
finally this one is even longer and even more text is available,

//words are
more
line
and
one
time
line
again
this

How to do the above in PHP?

A: You can use the explode, array_map, and array_filter functions to do what you want.
First you have to define functions to filter out the ( and ) lines, and to extract the second word of each line.
function filter_line($line) {
    //the regular expression detects a line ending with a ( or beginning with a )
    if(preg_match('/(^\)|\($)/', trim($line))) return false;
    if(empty($line)) return false;
    return true;
}

function map_line($line) {
    //the regular expression here splits the line into pieces at any whitespace
    //in case they used multiple spaces or a tab
    $split = preg_split('/\s+/', trim($line));

    //if there are one or zero words on this line then remove it from the result
    if(count($split) < 2) return false;

    //return the second word
    return $split[1];
}

Now that you have that, the rest is easy:
//this will split the whole text into an array of lines
$array = explode("\n", $myTextGoesHere);

//this will return an array of entries that are either the second word or false
$filtered = array_filter($array, 'filter_line');

//at this point $filtered contains the first step.
print_r($filtered);

//finally, this will extract the second word from each line
//and eliminate lines with less than two words
$result = array_filter(array_map('map_line', $filtered));

//$result contains the output
print_r($result);

All done.
Incidentally, it's clear you are trying to get type values from a CREATE TABLE statement - you might have to be a little more careful about how you parse that depending on your RDBMS.

A: //Assumes text is in $text

//Some preparations
$lines=explode("\n",$text);
$output=array();
$words=array();
$recording=false;

//Cycle lines
foreach ($lines as $line) {
  //Empty lines: Keep
  if ($line=='') {
    $output[]='';
    continue;
  }

  //Not recording: Wait for '('
  if (!$recording) {
    if (substr($line,-1)=='(') $recording=true;
    continue;
  }

  //Recording: Ending?
  if (substr($line,0,1)==')') {
    $recording=false;
    continue;
  }

  //Recording: Keep line
  $output[]=$line;

  //Recording: Keep 2nd word
  $line=preg_split('/\s+/', trim($line));
  if (sizeof($line)>1) $words[]=$line[1];
  //Remove next line if you want to ignore 1-word lines
  else $words[]='--no-second-word--';

}


text:
Q: Problem Integrating Java EE 7, Spring Security and EclipseLink fellow developers. Hope you are having a great day today.
I am facing a problem which I do not know how to solve, been at it for a while now. I am trying to integrate Java EE 7, Spring Security and EclipseLink to do form base authentication for an application that is to be hosted on a Payara Server.
I am going to list the artifacts corresponding to my current implementation:

pom.xml

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-bom</artifactId>
                <version>5.1.5.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>

<dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>
<!--        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.2</version>
            <scope>provided</scope>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
</dependencies>

Note: as you can see in the pom.xml file, I had to comment out the modelgen processor of EclipseLink as the project won't compile with it. So I have to un-comment it whenever I am doing reverse engineering to generate the entities from my database, and comment it again for building and running the application. It seems that the CanonicalModelProcessor (EclipseLink's modelgen that is used to generate type-safe JPAQueries) has problems if Spring Security is also present in the project. I found this on StackOverflow that proves this point as another user had the same problem as I.

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
@ComponentScan("com.myapp.testapp.security")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/Views/**").hasAnyRole("ADMIN","USER")
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin()
                .and().exceptionHandling().accessDeniedPage("/Views/accesodenegado.xhtml");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(customAuthenticationProvider);
    }
}

CustomAuthenticationProvider.java

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Inject
    private UsuarioFacade usuarioFacade;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        System.out.println(password);

        boolean authenticationIsSuccessful = WsAutenticacion.login(username, password);

        if (authenticationIsSuccessful) {
            System.out.println("Authentication successful");

            Usuario usuario = usuarioFacade.obtenerUsuario(username);

            return new UsernamePasswordAuthenticationToken(username, password, usuario.authorities);
        }

        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

UsuarioFacade.java

@Stateless
public class UsuarioFacade extends AbstractFacade<Usuario> {

    @PersistenceContext(unitName = "com.myapp.testapp_war_1.0PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UsuarioFacade() {
        super(Usuario.class);
    }

    public Usuario obtenerUsuario(String username) {
        String qlString = "SELECT u FROM Usuario u JOIN u.perfil p WHERE u.username = :username";
        Usuario usuario = (Usuario) getEntityManager().createQuery(qlString).setParameter("username", username).getSingleResult();

        return usuario;
    }

}

As you can see, I am using a custom AuthenticationProvider class as, per requirements, the authentication must be performed by sending the username and password to a SOAP service which returns true or false depending on whether the principal and credentials exist in Active Directory, which the webservice queries whenever you use this service. As the authorities are not stored in Active Directory, I need to query a database which has them for a specific user --- I am using EclipseLink for this step.
The problem I am having is that I am trying to inject the Facade into the custom AuthorizationProvider, and the application crashes with the following error:
Severe:   Exception during cleanup after start failed
org.apache.catalina.LifecycleException: Manager has not yet been started
    at org.apache.catalina.session.StandardManager.stop(StandardManager.java:867)
    at org.apache.catalina.core.StandardContext.stop(StandardContext.java:5735)
    at com.sun.enterprise.web.WebModule.stop(WebModule.java:551)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5552)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:522)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2057)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1703)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:353)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:501)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:220)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:487)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)

Severe:   ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'customAuthenticationProvider'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAuthenticationProvider': Unsatisfied dependency expressed through field 'usuarioFacade'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.testapp.facade.UsuarioFacade' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5556)
    at com.sun.enterprise.web.WebModule.start(WebModule.java:522)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:900)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:684)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2057)
    at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1703)
    at com.sun.enterprise.web.WebApplication.start(WebApplication.java:107)
    at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122)
    at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291)
    at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:353)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:501)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:220)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:487)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:189)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig': Unsatisfied dependency expressed through field 'customAuthenticationProvider'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAuthenticationProvider': Unsatisfied dependency expressed through field 'usuarioFacade'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.testapp.facade.UsuarioFacade' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:4965)
    at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:574)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:5534)
    ... 49 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customAuthenticationProvider': Unsatisfied dependency expressed through field 'usuarioFacade'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.testapp.facade.UsuarioFacade' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 67 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myapp.testapp.facade.UsuarioFacade' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.inject.Inject()}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 80 more

I know that if I remove the injected stateless EJB, the application runs smoothly, but then I would have no way of loading the authorities for a specific user. Can any of you guys teach me how to make use of EclipseLink to load the authorities of the user by injecting it into my custom AuthenticationProvider, or if there is another way that I could load these authorities?
Thank you in advance for any and all replies guys.

A: I see you are mixing spring bean annotations and CDI/EJB annotations. The error basically says that there is no bean of type UsuarioFacade available to inject into the CustomAuthenticationProvider. Are you sure UsuarioFacade is picked up as a Bean/EJB?
Since it is Spring doing the injecting, it needs to pickup the EJB annotation @Stateless. Is this stateless session bean in the package that Spring component scans?
I haven't been able to find an example of getting spring to work with this annotation, are you sure Spring picks it up?
What if your stateless bean extends AbstractStatelessSessionBean?
Or another try, what if it is annotated with the spring @Singleton annotation?


text:
Q: MS Access ADP Connection Error I inherited a Microsoft Access 2000 ADP project a while back. For a long time it ran successfully on Windows XP, but we recently began upgrading to Windows 7 workstations. I was able to get the ADE file produced from building the ADP project working, however I cannot seem to open the ADP file without error.
The error message I am getting is below. The ADP project uses SQL Server 2008 R2 for the back end and I am using Access 2010 to open it on my Windows 7 (64 bit) workstation.

My connection string is below (with values substituted for the actual server and database):
PROVIDER=SQLOLEDB.1;INTEGRATED SECURITY=SSPI;PERSIST SECURITY INFO=FALSE;INITIAL CATALOG=database;DATA SOURCE=server

Any assistance in debugging this error is greatly appreciated.

A: I think it was just a bad ADP file. I downloaded the same code from a different location and it worked.


text:
Q: Parameter undefined in method of an object I can't seem to add a parameter to my function in my object. My object needs to receive outside information from my function but it's telling me that the parameter is undefined.
This is the object
const data = {
  labels: GenerateAllQuantities(QuantityPerOrder)
}

And the function is:
function GenerateAllQuantities(QuantityPerOrder) {
    var TotalQuantityPerAmmount = [QuantityPerOrder];
    var AmmountsOfOrder = QuantityPerOrder / 8;

    for(var i = 1; i < 8; i++) {
        let OrderQuantity = TotalQuantityPerAmmount[0] - AmmountsOfOrder;
        TotalQuantityPerAmmount.unshift(OrderQuantity)
    }

    return TotalQuantityPerAmmount;
}

When I write directly:
const data = {
  labels: GenerateAllQuantities(80)

I get my answer directly, the issue is the parameter.

A: Perhaps try:
const data = {
  labels: GenerateAllQuantities
}

Then when you want to use it (in this example, with a parameter of 60), you will invoke the function by doing the following:
let myFunctionReturn = data.labels(60)

If you always want your parameter to be 80, then have your object's labels key point to an invoked function with 80 wrapped by a non-invoked anonymous pointer function:
const data = {
  labels: () => GenerateAllQuantitiest(80)
}

This will ensure that when your labels function does run, it runs with the parameter 80.
To run the "always 80" version of your function, do the following:
let myFunctionReturn = data.labels()

In your code when you had
const data = {
  labels: GenerateAllQuantitiest(80)
}

the function ran immediately, and then data.labels was no longer a function, but turned into whatever the return of your function was.


text:
Q: Saving a JSON object as the entire model in DJANGO I want to save the information that my front sends me in the database (I receive a JSON), the problem is that there are foreign keys in the model and these may or may not be filled and when I try to save some data with the empty FK I receive the 'matching' error query does not exist.' or other errors related to the 'key' not existing in the database. What occurs to me is to remove it from the front before it is sent to DJANGO and save the object as such but I don't know if it's possible, if you also have another solution I would greatly appreciate it
Add
def agregarIniciativa(request):

  if request.user.is_authenticated:
        if request.method =='POST':
            try:
                data = json.load(request)
                iniciativa = Iniciativa(
                    iniciativa = data['nombre'],
                    fecha_inicio = data['fecha_inicio'],
                    fecha_final = data['fecha_final'],
                    canal=Canales.objects.get(id=int(data['canal'])),
                    territorio = data['territorios'],
                    audiencia = AudienciaDirigida.objects.get(id=int(data['audiencia'])),
                    bigbet = BigBet.objects.get(id=int(data['bigBet'])),
                    marca = Marcas.objects.get(id=int(data['marca'])),
                    fgp = float(data['fgp']),
                    objetivo = data['objetivo'],
                    call2action = data['call2Action'],
                    dialogo_valor = data['dialogoValor'],
                    cobertura = data['cobertura'],
                    volumen_datos = data['volumen'],
                    kpi_medicion = data['kpi'],
                    inversion_datos = data['inversion'],
                    beneficio_datos = data['beneficio'],
                    volumen_total = int(data['total_vol']),
                    inversion_total = int(data['total_inv']),
                    beneficio_total = int(data['total_ben']),
                    marcas = data['marcas'],
                    fgp_datos = data['fgpDatos']
                )
                iniciativa.save()
                return JsonResponse({
                    "msg": "Guardado"
                })

            except Exception as e:
                 print('Error: Agregar iniciativa')
                 print(str(e))
                 return HttpResponseBadRequest('Error al agregar iniciativa.', format(request.method), status=400)
    else:
        return HttpResponseBadRequest('Favor de ingresar sesión en el sistema.', format(request.method), status=401)

Model.py
class Iniciativa(models.Model):
    iniciativa      = models.CharField(max_length=150)
    fecha_inicio    = models.DateField(blank=True, null=True)
    fecha_final     = models.DateField(blank=True, null=True)
    canal           = models.ForeignKey(Canales, blank=True, null=True, on_delete=models.CASCADE)
    territorio      = models.JSONField(default=dict, blank=True, null=True)
    audiencia       = models.ForeignKey(AudienciaDirigida, blank=True, null=True, on_delete=models.CASCADE)
    bigbet          = models.ForeignKey(BigBet, blank=True, null=True, on_delete=models.CASCADE)
    marca           = models.ForeignKey(Marcas, blank=True, null=True, on_delete=models.CASCADE)
    fgp             = models.FloatField(blank=True, null=True)
    objetivo        = models.TextField(blank=True, null=True)
    call2action     = models.TextField(blank=True, null=True)
    dialogo_valor   = models.TextField(blank=True, null=True)
    cobertura       = models.TextField(blank=True, null=True)
    kpi_medicion    = models.TextField(blank=True, null=True)

    volumen_datos   = models.JSONField(default=dict, blank=True, null=True)

    inversion_datos = models.JSONField(default=dict, blank=True, null=True)

    beneficio_datos = models.JSONField(default=dict, blank=True, null=True)

    avance_captura = models.IntegerField(default=0)
    observaciones  = models.IntegerField(default=0)
    observaciones_solventadas  = models.IntegerField(default=0)
    aprobada       = models.BooleanField(default=False)
    ranking        = models.IntegerField(default=0)
    ranking_temp   = models.IntegerField(default=0)

    volumen_total   = models.DecimalField(max_digits=30, decimal_places=15, default=0.0, null=True)
    inversion_total = models.DecimalField(max_digits=30, decimal_places=15, default=0.0, null=True)
    beneficio_total = models.DecimalField(max_digits=30, decimal_places=15, default=0.0, null=True)
    fgp_datos       = models.JSONField(default=dict, blank=True, null=True)
    marcas          = models.JSONField(default=dict, blank=True, null=True)
    estatus         = models.IntegerField(choices=ESTATUS,default=0)

    class Meta:
        verbose_name='Iniciativa'
        verbose_name_plural='Iniciativas'
        ordering=('id',)

    def __str__(self) -> str:
        return self.iniciativa


text:
Q: How to save many h:inputText value of DATATABLE in Database In the web page, I use <h:dataTable> to present them.
Example of the JSF page :
<h:dataTable value="#{bean.scores}" rowIndexvar="index">
    <h:column>
      <h:outputText value="#{index+1}" />
    </h:column>
    <h:column>
      <h:outputText value="#{score.studentId}" />
    </h:column>
    <h:column>
       <h:inputText value="#{score.teacherScore}" />
    </h:column>
</h:dataTable>

<h:commandButton value="Save" action="#{useMB.save}" />
<h:messages />

The questions are about my ManagedBean : useMB.java
1.What getter and setter method do I need to write to store
 <h:inputText value="#{score.marks}" />  value in database?
2.How  to save in database different student marks for same subject using dataTable, JSF and java?
3.What change do I need to do in xhtml page?

A: You will need to use a collection in the managed bean to hold the values for the rows in the table. Each of the rows in the table will represent a single element from the collection and every element will be accessible in the dataTable by the alias name, given in the var attribute.
<h:dataTable value="#{bean.scores}" rowIndexvar="index" var="score">
    <h:column>
      <h:outputText value="#{index+1}" />
    </h:column>
    <h:column>
      <h:outputText value="#{score.studentId}" />
    </h:column>
    <h:column>
       <h:inputText value="#{score.teacherScore}" />
    </h:column>
</h:dataTable>

In the managed bean you will need to have a Collection (or Array) of element, each of them having members with names studentId and teacherScore and accessors for them.
public class ManagedBean {
    private Score[] scores;

    public Score[] getScores() { return scores; }

    public void setScores(Score[] scores) {
        this.scores = scores;
    }
}

The Score class should look (at least) like this:
public class Score {
    private String studentId;

    private String teacherScore;

    public String getStudentId() { return studentId; }

    public void setStudentId(String studentId) { this.studentId = studentId; }

    public String getTearcherScore() { retyrn teacherScore; }

    public void setTeacherScore(String tearcherScore) { this.tearcherScore = tearcherScore; }
}


text:
Q: cURL php in live server Amazon Web Service not working I don't know what's the problem with this. But my curl doesn't work. I tried everything research everywhere and my last option is this, I tried to remove all my code and remain only this
echo "before curl";
$curl_handle=curl_init();
echo "after curl";

Then my output is only
"before curl", so therefore there's a problem with my curl and not other codes.
Someone help me. I deployed it on Amazon Web Service.

Is it possible that it doesn't accept request from CURL? or do I need to install any library?
CURL is working on my local.


text:
Q: Slow Outlook email sends with Graph API We have an application that sends mail merge campaigns via Graph API. In the app, we keep track of the timings and benchmarks per campaign. We found that some of our users will run into an issue where their mail merge campaign is sending very slow sometimes. Normally for a campaign with about 1k recipients, the average send per email will be less than 1-2 seconds. But sometimes we get averaging around 17-30 seconds per email send with Graph API. For a total of 1k recipients, this is a long time to process a mail merge campaign. More often than not, this causes the total time for a mail merge campaign to finish between 2-4 hours. Note, it's not necessarily because of the number of emails / recipients. We've seen this happen when the recipients range from 500 to 2k even.
I'm not too sure whether the issue here is with Graph API or the user's mailbox throttling (sending limits). I suspect it's the prior because, often, users will resend the same campaign when they see that the first campaign is very slow. What ends up happening is that the second campaign will actually finish very quickly, even before the slow campaign has processed half of them.
It almost seems like the server processing my first set of Graph API requests is warming up. Is there any configuration that I can set in the API request that may help with this? I couldn't find anything in the documentation referencing this.
Has anyone else had experience with this issue? Is there some configuration that the tenant can adjust or review that may be a root cause of this?


text:
Q: How do I limit a gnuplot polar to a 180 degree range? I am attempting to use gnuplot to plot the off axis response of a loudspeaker in the range +/- 90 degrees. I have this working nicely, almost entirely as a result of Creating a microphone polar pattern plot in gnuplot
I would like to extend this so it presents the forward" 180 range only however I don't know how to do this & would appreciate some pointers.
This is my code so far
gnuplot <<EOF
set terminal pngcairo size ${WIDTH}/2,${HEIGHT}/2 font ',10'

set polar
set angle degrees
set size ratio 1
set tmargin 3
set bmargin 3

set style line 11 lc rgb 'gray80' lt -1
set grid polar ls 11

unset border
unset xtics
unset ytics

set xrange [-30:30]
set yrange [-30:30]
set key

r=1
set rrange [0:r]
set rtics 0.166 format '' scale 0
set label '0°' center at first 0, first r*1.05
set label '180°' center at first 0, first -r*1.05
set label '-90°' right at first -r*1.05, 0
set label '+90°' left at first r*1.05, 0

set for [i=1:5] label at first r*0.02, first r*((i/6.0) + 0.03) sprintf("%d dB", -30+(i*5))
unset raxis

set key outside top right
set style line 11 lw 2

set output '${PREFIX}_polar.png'
set multiplot layout 1,2 title "Circular Polar Response"
set title "Normalised"
plot '${PREFIX}_norm_polar_1000.txt' t '1k'  w lp ls 11 lt 1 pt -1 , \
     '${PREFIX}_norm_polar_2000.txt' t '2k'  w lp ls 11 lt 2 pt -1 , \
     '${PREFIX}_norm_polar_4000.txt' t '4k'  w lp ls 11 lt 3 pt -1 , \
     '${PREFIX}_norm_polar_8000.txt' t '8k'  w lp ls 11 lt 4 pt -1 , \
     '${PREFIX}_norm_polar_16000.txt' t '16k' w lp ls 11 lt 5 pt -1
set title "Unnormalised"
plot '${PREFIX}_polar_1000.txt' t '1k'  w lp ls 11 lt 1 pt -1 , \
     '${PREFIX}_polar_2000.txt' t '2k'  w lp ls 11 lt 2 pt -1 , \
     '${PREFIX}_polar_4000.txt' t '4k'  w lp ls 11 lt 3 pt -1 , \
     '${PREFIX}_polar_8000.txt' t '8k'  w lp ls 11 lt 4 pt -1 , \
     '${PREFIX}_polar_16000.txt' t '16k' w lp ls 11 lt 5 pt -1

EOF

the outcome is

the data looks like this (this is the 1k line in the example picture)
180 0.657067
172.5 0.6832
165 0.717767
157.5 0.7461
150 0.7747
142.5 0.806167
135 0.835633
127.5 0.865167
120 0.890533
112.5 0.918133
105 0.929633
97.5 0.9566
90 0.9632
82.5 0.9566
75 0.929633
67.5 0.918133
60 0.890533
52.5 0.865167
45 0.835633
37.5 0.806167
30 0.7747
22.5 0.7461
15 0.717767
7.5 0.6832
0 0.657067

A: Gnuplot gets confused if you use xrange and yrange setting which contradict the rrange setting. Thats probably why the yrange settings are ignored.
Then, you must also use set size ratio -1 in order to get the same scaling in x and yrange. When plotting only the upper two quadrants, you would get a wrong aspect ratio with set size square.
set terminal pngcairo font ',10'

set polar
set angle degrees
set size ratio 1
set lmargin 8
set style line 11 lc rgb 'gray80' lt -1
set grid polar ls 11

unset border
unset tics

set xrange [-1:1]
set yrange [0:1]
set size ratio -1

r = 1
set rtics 0.166 format '' scale 0
set label '0°' center at first 0, first r*1.05
set label '-90°' right at first -r*1.05, 0
set label '+90°' left at first r*1.05, 0

set for [i=1:5] label at first r*0.02, first r*((i/6.0) + 0.03) sprintf("%d dB", -30+(i*5))
unset raxis

set key outside top right

set output 'polar.png'
plot 'norm_polar_1000.txt' w lp ls 1 t '1k'


text:
Q: Play Framework SSE Closing Chunked Response I'm trying to implement Server-Side Events server in Play Framework 1.2.5
How can I know if the client called EventSource.close() (or closed its browser window, for example)? This is a simplified piece of server code I'm using:
public class SSE extends Controller {

  public static void updater() {
    response.contentType = "text/event-stream";
    response.encoding = "UTF-8";
    response.status = 200;
    response.chunked = true;

    while (true) {
      Promise<String> promise = Producer.getNextMessage();
      String msg = await(promise);
      response.writeChunk("data: " + msg + "\n\n");
    }
  }
}

Producer should deal with queuing, Promise objects, and produce the output, but I should know when to stop it (filling its queue). I would expect some exception thrown by response.writeChunk() if the output stream is closed, but there's no any.
There's a similar example that does not deal with SSE, but only chunks instead, at http://www.playframework.com/documentation/1.2.5/asynchronous#HTTPresponsestreaming

A: Since play.mvc.Controller doesn't let me know if the output stream is closed during the execution, I solved the problem through the Producer itself:

*

*In Producer.getNextMessage(), the current time is remembered.

*In Producer.putMessage(String), the time since last 'get' is checked. If it's greater than some threshold, we can consider that SSE channel is closed.

There's also this class play.libs.F.EventStream which can be useful within the Producer.
Plus, Producer might not be the right name here, since it's more of a dispatching queue...


text:
Q: Displaying only the first paragraph of a body of text in a Django template If I have a large body of text, e.g. a blog post, how could I display the entire first paragraph of each text on the blog's home page, instead of breaking it on a random letter in a random word with the following?
  <p>{{ post.text|linebreaksbr|slice:":400" }}</p>

A: Try avoiding this type of operations in your templates, they are not designed for that. Instead, implement that functionality in your models.py or views.py with the appropriate split('\n')
Have a look at Django templates - split string to array.


text:
Q: Appropriate base resistor for BJT switch driving a motor In the following circuit, the BJT is used as a switch, controlled by in. The load is a motor. I've added a few diodes for safety, as recommended here; you can safely ignore them.

simulate this circuit – Schematic created using CircuitLab
in is connected to a digital pin of Arduino, so the voltage is 5V when high, and the current should not exceed 40mA.
My motor's input voltage is 12V, and its rated current is 0.45A. I think it yields a maximum resistance of 26.67Ω. I'm using this figure to model the load resistance.
Based on these, I'm explaining my approach, to show what have and haven't I considered. When in is high as 5V, the BJT should be saturated. The spec. of 2N2222 says \$\rm V_{be(sat)}\$ is:

*

*1.3V at \$\rm I_C\$=150 mA, \$\rm I_B\$=15 mA

*2.6V at \$\rm I_C\$=500 mA, \$\rm I_B\$=50 mA

Since I'm looking for about 450mA, I'll just take \$\rm V_B\$=2.6V. Now the volt. diff. across the base resistor becomes 2.4V. By Arduino's 40 mA limit, I see the resistance must be ≥ 60Ω.
By deciding \$\rm I_B\$, I would be able to decide the appropriate resistance. But I'm perfectly stuck here. I've seen some articles saying "take β≒10 for saturation", but I'm confused since \$\rm I_C\$ does not increase while \$\rm I_B\$ increase there, so doesn't β vary?
As Vcc is fixed to 12V, the equation \$\rm V_C+I_C \cdot R_{load} = 12\:V\$ draws a line in Ic vs. Vce plot. Does it help?

A: A MOSFET if really best for turning on high current loads, esp motors that, as part of their nature, have a very heavy start current that you do not want to accidentally limit.
Using a BJT means whatever is driving this circuit does, in turn, need to supply enough current to drive the base, so you end up passing the problem backwards. A MOSFET, being voltage activated, is much more suitable to be controlled by logic circuits.
Choose a MOSFET that has:

*

*Enough current capability to handle the full start-up motor current indefinitely.

*A Vgs threshold no more than 1/3rd of your logic output level and make the gate resistor small... ~50R.

*An RDS_ON value that is very small. They come in all shapes and sizes, and the lower the RDS_ON the less power and heat will be wasted/dissipated in the MOSFET.

*Is in the right package to not be overly hot when running, or can be attached easily to a heat-sink. (Do the math to figure out if you need one, and add it, BEFORE you power it up.)


text:
Q: SQL parameter table I suspect this question is already well-answered but perhaps due to limited SQL vocabulary I have not managed to find what I need. I have a database with many code:description mappings in a single 'parameter' table. I would like to define a query or procedure to return the descriptions for all (or an arbitrary list of) coded values in a given 'content' table with their descriptions from the parameter table. I don't want to alter the original data, I just want to display friendly results.

*

*Is there a standard way to do this?

*Can it be accomplished with SELECT or are other statements required?

Here is a sample query for a single coded field:
SELECT TOP (5)
    newid() as id,
    B.BRIDGE_STATUS,
    P.SHORTDESC
FROM
    BRIDGE B
    LEFT JOIN PARAMTRS P ON P.TABLE_NAME = 'BRIDGE'
    AND P.FIELD_NAME = 'BRIDGE_STATUS'
    AND P.PARMVALUE = B.BRIDGE_STATUS
ORDER BY
    id

I want to produce 'decoded' results like:
| id                                   | BRIDGE_STATUS |
|--------------------------------------|------------   |
| BABCEC1E-5FE2-46FA-9763-000131F2F688 |  Active       |
| 758F5201-4742-43C6-8550-000571875265 |  Active       |
| 5E51634C-4DD9-4B0A-BBF5-00087DF71C8B |  Active       |
| 0A4EA521-DE70-4D04-93B8-000CD12B7F55 |  Inactive     |
| 815C6C66-8995-4893-9A1B-000F00F839A4 |  Proposed     |

Rather than original, coded data like:
| id                                   | BRIDGE_STATUS |
|--------------------------------------|---------------|
| F50214D7-F726-4996-9C0C-00021BD681A4 | 3             |
| 4F173E40-54DC-495E-9B84-000B446F09C3 | 3             |
| F9C216CD-0453-434B-AFA0-000C39EFA0FB | 3             |
| 5D09554E-201D-4208-A786-000C537759A1 | 1             |
| F0BDB9A4-E796-4786-8781-000FC60E200C | 4             |

but for an arbitrary number of columns.


text:
Q: A guide to the right path on accomplishing the haskell commands I am totally newbie on haskell. My java know how just isnt helping me alot.
i need any help or guide on finishing the code. I have tried most of the parts and also indicated comments on what i tend to achieve.
A DFA has been defined as follows
(original image of DFA definition):
Q = {q1,q2,q3,q4,q5}
qs = q1
F = {q4}
delta = {
  <q1,0,q2>,<q1,1,q2>,<q1,.,q3>,
  <q2,0,q2>,<q2,1,q2>,<q2,.,q4>,
  <q3,0,q4>,<q3,1,q4>,<q3,.,q5>,
  <q4,0,q4>,<q4,1,q4>,<q4,.,q5>,
  <q5,0,q5>,<q5,1,q5>,<q5,.,q5>
  }
Sigma = {0,1,.}

task:

*

*Create a Haskell language program that can be used to execute any arbitrary
Deterministic Finite Automaton corresponding to the FDA definition above. Represent
the DFA as a four-tuple
a. represent each state with its name as a String
b. represents all states as a list of states
c. represent each transition as three tuple and the list of transitions as a
list.

*To assist you, implement the following functions in your solution:
a. stateFactory – returns a DFA definition (i.e. a four tuple)
b. allStates, firstState, finalStates, and allTransitions – take a DFA and return the
corresponding component of the DFA. For example, in the above DFA instance,
allStates would return the list of states, q₁, q₂, q₃, q₄, and q₅.
c. transFrom, transInput, and transTo – take a transition and return the corresponding component of the transition
d. findTransition – takes a state, a label, and a list of transitions and returns a list
containing the single transition matching the given state and character (note the transitions emanating from a state are uniquely determined by each character label
e. findNextState – takes a DFA, a label, and a state and returns a state
f. dfaAccept – takes a DFA and an input String and returns True if the DFA accepts the input and False otherwise (i.e. decompose the string one character at a time, don't
match the entire string since your solution must work for any DFA). It is helpful to
separate this into two functions each with different sets of parameters (one for an
empty list and one for a non-empty list). One function takes a current state and one
simply takes a DFA, whose state is assumed to be the initial state of the DFA.
this is my code has lots of errors but am trying to fix them
allStates = ["q1","q2","q3","q4","q5"] -- iniitialize all states
firstState = "q1"
finalStates = "q4"

--define all transitions as a tuple

t1 = ("q1",'0',"q2")
t2 = ("q1",'1',"q2")
t3 = ("q1",'.',"q3")

-- place all transitions in a list
allTransitions = [t1,t2,t3]

lst =[]

stateFactory = (allStates, firstState, finalStates, allTransitions)

findTransition state label listOfTransition =
    if (state , label , "q1") elem listOfTransition
        then lst ++ [] -- if the tuple matches the one in transition add to list
    else
        lst -- no match dont add

    if (state , label , "q2") elem listOfTransition
        then lst ++ [] -- if the tuple matches the one in transition add to list
    else
        lst -- no match dont add

    if (state , label , "q3") elem listOfTransition
        then lst ++ [] -- if the tuple matches the one in transition add to list
    else
        lst -- no match dont add

findNextState DFA label state =
    --get the transition and extract the last element which is the state
    last findTransition state label allTransitions

dfaAccept DFA inputString =
    if inputString == null then False

expected Output
Prelude> dfaAccept stateFactory ""
False
Prelude> dfaAccept stateFactory "1"
False
Prelude> dfaAccept stateFactory "1.0"
True
Prelude> dfaAccept stateFactory "11.11"
True
Prelude> dfaAccept stateFactory "10.10.10"
False

A: Is this homework for a class that you're taking, or is this self-guided Haskell study?  If this is self-guided, I think you might be trying an exercise that's too hard for you at this stage. I would suggest taking a look at this answer:  Getting started with Haskell.  Even though it's an old answer, it's been updated now and again, and most of the resources there are still useful.  The http://www.haskell.org website also has links to lots of resources for learning Haskell, in the "Documentation" section.
If this is homework for a class you're taking, you might be in trouble.  You're making some pretty basic mistakes in your code (using elem where you need `elem`; trying to apply last to four arguments; using an uppercase identifier DFA as a variable name) which shows that you don't have the Haskell fundamentals nailed down yet.
Perhaps you should talk to your professor and let him or her know that this assignment is beyond you.  Maybe you can get an extension, or maybe you can offer to turn in a Java solution for partial credit (assuming that this course isn't specifically a Haskell course).
If you insist on forging ahead, here's a hint.  You're asking for help writing one of the hardest functions, findTransition, but you haven't even written the "easy" ones, like allStates, firstState, and so on.  (You've used the same names in your solution, but you've defined them as constants for a specific DFA instead of making them functions applied to a general DFA tuple, which is what the assignment requires).
So, can you complete the following template by filling in the underscores, in order to answer parts 1 and 2(b)?
-- simple type synonyms to make things easier to read
type State = String
type Symbol = Char

-- some more complicated type synonyms
type Transition = (State, Symbol, State)
type DFA = ( [State]        -- all states
           , State          -- first state
           , [State]        -- final states
           , [Transition]   -- all transitions
           )

allStates :: DFA -> [State]
allStates _ = _

firstState :: DFA -> State
firstState _ = _

finalStates :: DFA -> [State]
finalStates _ = _

allTransitions :: DFA -> [Transition]
allTransitions _ = _

Once you're able to do that, write the functions in part 2(c).  Once you've done all that, you might be ready to tackle findTransition.  At this point, you'll probably need to learn about the find or filter functions, or else you'll need to learn how to write recursive list functions.


text:
Q: Different hashes during CRAM-MD5 authentication As an exercise, I'm trying to implement a mock SMTP server with CRAM-MD5 authentication in Go (without following RFC 2195, since it looks like it doesn't matter to the client what format the pre-hashed challenge is in; I also assume there is only one user "bob" with password "pass"). But I can't seem to get it right as the hash in response is always different from what I have on the server. I send the email using Go as such (running it as a separate package):
{...}
smtp.SendMail("localhost:25", smtp.CRAMMD5Auth("bob", "pass"),
   "bob@localhost", []string{"alice@localhost"}, []byte("Hey Alice!\n"))
{...}

Here's what I do when I get the authentication acknowledgement from the client:
{...}
case strings.Contains(ms, "AUTH CRAM-MD5"):
    rndbts = make([]byte, 16) // Declared at package level
    b64b := make([]byte, base64.StdEncoding.EncodedLen(16))
    rand.Read(rndbts)
    base64.StdEncoding.Encode(b64b, rndbts)
    _, err = conn.Write([]byte(fmt.Sprintf("334 %x\n", b64b)))
{...}

And this is what I do with the client's response:
{...}
 {
    ms = strings.TrimRight(ms, "\r\n") // The response to the challenge
    ds, _ := base64.StdEncoding.DecodeString(ms)
    s := strings.Split(string(ds), " ")
    login := s[0] // I can get the login from the response.
    h := hmac.New(md5.New, []byte("pass"))
    h.Write(rndbts)
    c := make([]byte, 0, ourHash.Size()) // From smtp/auth.go, not sure why we need this.
    validPass := hmac.Equal(h.Sum(c), []byte(s[1]))
    {...}
}
{...}

And the validPass is never true. I omitted error handling from the excerpts for brevity, but they're there in the actual code (though they're always nil). Why are the hashes different? I have looked at the source code for net/smtp, and it seems to me that I'm going in the right direction, but not quite.

A: I hope this helps! Runnable version is at https://play.golang.org/p/-8shx_IcLV. Also note that you'll need to fix your %x (should be %s) so you're sending the right challenge down to the client. Right now I think you're trying to hex-encode your base64 string.
Once you've fixed that, I believe this code should help you to construct the right response string on the server and compare it to what the client sent.
// Example values taken from http://susam.in/blog/auth-cram-md5/

challenge := []byte("<17893.1320679123@tesseract.susam.in>")
username := []byte("alice")
password := []byte("wonderland")
clientResponse := []byte("YWxpY2UgNjRiMmE0M2MxZjZlZDY4MDZhOTgwOTE0ZTIzZTc1ZjA=")

// hash the challenge with the user's password
h := hmac.New(md5.New, password)
h.Write(challenge)
hash := h.Sum(nil)

// encode the result in lowercase hexadecimal
hexEncoded := hex.EncodeToString(hash)

// prepend the username and a space
toEncode := []byte(string(username) + " " + hexEncoded)

// base64-encode the whole thing
b64Result := make([]byte, base64.StdEncoding.EncodedLen(len(toEncode)))
base64.StdEncoding.Encode(b64Result, toEncode)

// check that this is equal to what the client sent
if hmac.Equal(b64Result, clientResponse) {
    fmt.Println("Matches!")
}