text:
Q: What is the probability that the queen of hearts is drawn exactly twice assuming all 3 cards drawn were queens? 3 cards are drawn independently from a standard 52-card deck with replacement. What is the probability that the queen of hearts is drawn exactly twice assuming all 3 cards drawn were queens?
I believe I have to use Bayes rule.
If event A is that a queen of hearts is drawn exactly twice, and event B is the event that all 3 cards drawn were queens, then I would set it up as:
P(A|B) = P(B|A)P(A) / P(B)
P(B|A) is the probability that all 3 cards are queens given a queen of heart is drawn twice. So this would be 1/12? Because the chance of the third card being a queen is just 1/12?
p(A) is the probability that the queen of hearts is drawn exactly twice out of three draws, which is (1/52)(1/52)(51/52).
P(B)...I'm not sure how to compute this.

A: $$P(A|B) = \frac{P(A\cap B)}{P(B)} =\frac{3\times (\frac{1}{52})^2 \times \frac{3}{52}}{(\frac{4}{52})^3}$$
If event A is that a queen of hearts is drawn exactly twice, and event B is the event that all 3 cards drawn were queens.
There are $4$ queens, probability of choosing a queen is $\frac{4}{52}$
Since heart's of queen can come in any order, multiply by $3$.

A: Compare this to the following question:

I have a bag with only four balls.  One of the balls is red, the other three of the balls are green.  I draw balls one at a time with replacement and do this a total of three times.  What is the probability that we drew the red ball exactly twice?

Take the time to recognize this is exactly the same question as yours after taking care of the conditional probability aspect of the question and will have the same answer as yours.  This is an introductory textbook example of a binomial distribution question and has as its final answer:
$$\binom{3}{1}\left(\frac{1}{4}\right)^2\left(\frac{3}{4}\right) = \frac{9}{64}$$

A: Let  $A$ be the event that a queen of hearts is drawn exactly twice in three draws, and $B$ be the event  that all 3 cards drawn were queens.
$$ Then\;\;P(A|B) = \frac{P(A\cap B)}{P(B)} =\frac{\binom32\times (\frac{1}{52})^2 \times (\frac{3}{52})}{(\frac{4}{52})^3}= \frac{9}{64}$$

A: Alternative approach that avoids Bayes Theorem:
Attack the problem combinatorically, expressing the probability as
$$\frac{N\text{(umerator)}}{D\text{(enominator)}}, \tag1 $$
where $D = 4^3.$
So, in (1) above, the denominator of $\left(4^3\right)$ represents the total number of ways that three cards can be drawn from the four card deck of four queens, sampling with replacement.
Here, for convenience the computation of $\left(4^3\right)$ is used for the denominator.  However, this contrivance assumes that the order that the cards are drawn is relevant.  That is, drawing the Queen of Hearts, and then the Queen of Diamonds is regarded as distinct from drawing the Queen of Diamonds and then drawing the Queen of Hearts.
Therefore, the numerator, $(N)$, must be computed in a consistent manner.  From this perspective, how many satisfying ways are there of drawing the three cards?
There are three choices for which of the three cards will not be the Queen of Hearts.
Assume that the first card drawn is not the Queen of Hearts. Then, there are three choices for which other Queen that this first card will be.
Therefore,
$$N = 3 \times 3 = 9.$$
Therefore, the probability is
$$\frac{N}{D} = \frac{9}{64}.$$

A: There are four queens in the deck one of which is the queen of hearts.  So what is the probability of a card drawn being the queen of heart given that the card is a queen?


text:
Q: How do I set the AppDomain FriendlyName in a ClickOnce scenario? It seems that the FriendlyName gets set to "DefaultDomain" when the application is deployed using ClickOnce instead of the exe name.  I would like to disambiguate my windows from other potential ClickOnce apps that may also be "DefaultDomain".
Clarification: We are using an unmanaged call,
[DllImport("user32.dll")]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

to retrieve the class name of windows around the user's desktop, and need to make sure we respond in a certain way to windows created by our application.  When deployed by ClickOnce, our windows no longer carry the exe name as the domain and will not be easily distinguished from other potential ClickOnce deployed apps.

A: Great Question.
I can't say for sure why this is the case, but I believe that perhaps the application is 'hosted' differently since it is the 'ClickOnce Application Deployment Support Library' that is launching the application.
However, if you have an unrelenting desire to use AppDomain.FriendlyName to distinguish your applications, then perhaps you could create the appdomain yourself and define your own friendly name.
Another idea that would serve the same purpose would be to to use the application full name as follows:
private static string GetAppName()
{
    if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
    {

        ApplicationDeployment curDeployment = ApplicationDeployment.CurrentDeployment;
        string fullname = curDeployment.UpdatedApplicationFullName;
        Match match = Regex.Match(fullname, "#.+/(?<app>.+).exe");

        return match.Groups["app"].ToString();
    }
    return null;
}

I created the regex pretty quickly, so no gurantees. Here is a link that explains the naming conventions: http://blogs.msdn.com/b/shawnfa/archive/2004/06/30/170241.aspx
Another idea would be to just use reflection to get the calling assembly name, but this will not work so well in all partial-trust environments.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expandable Div Using Jquery I have a site (lowrateadvisor.com) I am working on getting an expandable div at the top of the page to work.  I can get it to work in jsfiddle.net/3shEE/95/, just not on the site.  Any help is much appreciated.
CSS
#expandable a{
color:#fff;
text-decoration:underline;
}
#expandable a:hover{
color:#fff;
text-decoration:none;
}
#expandable {
    width: 100%;
    height:35px;
    background: transparent;
    overflow: hidden;
background:#000;
color:#fff;
font-size:11px;
text-align:center;
}

#expandable.dropped {
    background: #666;
    color: white;
    border-bottom: 1px solid #111 }

#expandable span {
    display: block;
    width: 100%; height: 50px;
    line-height: 50px; text-align: center;
    cursor: pointer;
}
#expandable ul {
    width: 100%;
}

HTML

     Get the lowest possible rates on pre approved home loans, mortgages and refinancing your home.

We will never...

» Ask for your SSN.

» Ask for a credit card.

» Store your information.

» Hassle or Pressure any applicant.

 Get Pre Approved | Get A Quote

JQUERY
$("#expandable").hover(function() {
    $(this).stop().animate({"height":"200px"},1000).addClass("dropped");
}, function() {
    $(this).stop().animate({"height":"35px"},1000).removeClass("dropped");
});

A: Can't see any typo mistake.... just a SyntaxError: illegal character on line 67
Try using jquery 1.8.2 and this:

A: This happens sometimes when copying code from JSFiddle.
The last semicolon (sometimes last but one) of your jQuery code is copied as an illegal character. Try to delete the last line }); and retype it by hand.


text:
Q: status bar disappeared after full screen video in WKWebView only in iOS 12 As you can see this only happened in iOS 12.
iOS 12              iOS 11

here is my code:
import UIKit
import WebKit

class ViewController: UIViewController {

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    override var prefersStatusBarHidden: Bool {
        return false
    }

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView(frame: UIScreen.main.bounds)
        view.addSubview(webView)
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        webView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
        webView.loadHTMLString("

", baseURL: URL(string: "https://www.youtube.com/"))
        setNeedsStatusBarAppearanceUpdate()
    }
}

my info.plist is right below:

Does anyone know how to solve it?
I know that if I set the key View controller-based status bar appearance to YES will help, but In that case it will look like this:

There are unknown reason for changing status bar from white and black, and as for my real project is in a large scale, so it will be nice to solve in the original setting, rather than make every ViewController inherit from one class which is subclass from UIViewController or add dynamic for overriding prefersStatusBarHidden and preferredStatusBarStyle in extension (here just try to force it show update status bar when View controller-based status bar appearance set to YES)
Hope there is a solution for View controller-based status bar appearance set to NO, that will be very helpful thx.
here is the demo project, it was created by Xcode9.4, feel free to try it with.

A: Use this solution:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  ...
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoExitFullScreen:) name:@"UIWindowDidBecomeHiddenNotification" object:nil];
...
}

- (void)videoExitFullScreen:(id)sender
{
  [[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
}

Reference more here:
https://github.com/react-native-community/react-native-webview/issues/62

A: Remove Following property from info.plist file. and Give it programmatically only.

Status bar is initially hidden : NO
View controller-based status bar appearance : NO
Status bar style : UIStatusBarStyleLightContent

It may be work for you.

A: Create one extension of AVPlayerViewController like below this slo
extension AVPlayerViewController {
    open override var prefersStatusBarHidden: Bool {
        return false
    }
}

A: In the end I used category in objective-c to deal with this problem.
I set View controller-based status bar appearance to YES and add code below
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}

As for my experience, you have to also implement code above in UINavigationViewController.
It seems that it has its own implementation for that.
And also every window to see if there is a rootViewController exist, if there isn't, then add one for it.
Although this solution is a bit Cumbersome, but that is the one I solved my issue perfectly so far.

A: If you want the status bar to be white, technically to be .lightContent, follow the steps below:

*

*In Info.plist, set View controller-based status bar appearance = YES

*Create an extenstion to either UIViewController or UINavigationController, and write the following codes:

    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

    open override var prefersStatusBarHidden: Bool {
        return false
    }

Note: In case the status bar turns back to dark, you may need to trigger a call of self.setNeedsStatusBarAppearanceUpdate() inside viewWillAppear() to inform the status bar to refresh itself.
Hope that helps !!! Have a nice one!

A: Subscribe for

UIWindowDidBecomeHiddenNotification

event
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIWindowDidBecomeHiddenNotification"), HandleAction);

and set the status bar state in handler:
void HandleAction(NSNotification obj)
{
    UIApplication.SharedApplication.StatusBarHidden = false;
}


text:
Q: Timing issues with PrintStreams I'm using eclipse IDE, and sometimes, depending on the code, System.err output is printed before than System.out's. For instance:
    public static void main(String[] args) {
        System.out.println("Regular text"); //1
        System.err.println("Error text"); //2
    }

With that code, everything is fine. 2 is printed after 1. However, adding some extra system.out sentences reverses the order:
    public static void main(String[] args) {
        System.out.println("Regular text"); //1
        System.err.println("Error text"); //2

        //Additional printing stuff
        for(String s = "a";s.length() < 200; s = s.concat("" + (char)(s.charAt(s.length()-1)+ 1))){
            System.out.println(s);
        }

    }

1 is printed after 2.
How is this possible?

A: stderr and stdout are 2 different streams, and normally will be printed when flushed. I would expect some buffering to take place and this would affect flushing. Consequently the quantity of data in each stream will affect the flushing and the output.

A: On some OSes (*nix in particular), the standard output stream is buffered -- that is, whatever gets sent to it might sit around a bit before being sent to the terminal/screen.  Standard error, however, often is not buffered, or is auto-flushed after each output.
System.out and System.err are just Java's objects to represent those two streams, and thus, tend to behave as they would on the host platform.  But i'm not aware of anything that specifically says they have to.

A: They are separate streams each with their own buffers. You write to a stream which is then "copied" or written out to the console.
You should find that calling
System.out.flush()
System.err.flush()

will flush the streams to the actual device (the Eclipse console) and bring some semblance of order.


text:
Q: How to loop through a list and make a dictionary files = ['bob.csv', 'mike.csv', 'sally.csv']
file_type = "excel"
units = "mm"
bin_size = 1
filter_amount = .512
gecko_file = "n"

for file in files:
    d = {file:
         {
        'file_type': file_type,
        'units': units,
        'bin_size':bin_size,
        'filter_amount':filter_amount,
        'gecko_file':gecko_file
        }
    }

d

Has this output:
{'sally.csv': {'file_type': 'excel',
  'units': 'mm',
  'bin_size': 1,
  'filter_amount': 0.512,
  'gecko_file': 'n'}}

I'm wondering why there isn't an output for every 'file' in 'files'. I'd want my output to be:
{'sally.csv': {'file_type': 'excel',
  'units': 'mm',
  'bin_size': 1,
  'filter_amount': 0.512,
  'gecko_file': 'n'}}

{'mike.csv': {'file_type': 'excel',
  'units': 'mm',
  'bin_size': 1,
  'filter_amount': 0.512,
  'gecko_file': 'n'}}

{'bob.csv': {'file_type': 'excel',
  'units': 'mm',
  'bin_size': 1,
  'filter_amount': 0.512,
  'gecko_file': 'n'}}

How can I achieve this?

A: You will have to add print(d) inside the for loop only then it will print all three dictionaries.
files = ['bob.csv', 'mike.csv', 'sally.csv']
file_type = "excel"
units = "mm"
bin_size = 1
filter_amount = .512
gecko_file = "n"

for file in files:
    d = {file:
         {
        'file_type': file_type,
        'units': units,
        'bin_size':bin_size,
        'filter_amount':filter_amount,
        'gecko_file':gecko_file
        }
    }
    print(d)


text:
Q: jquery tabs, jpages "Syntax error, unrecognized expression: ?" I'm using two popular technologies, jquery tabs and jPages.  Unfortunately the target below does not seem to be cooperating.  Can this be fixed in the current setup for the three pages I've put below?
$("div.holder").jPages({containerID : "card-row"});

Page 1 (using jquery tabs):

Your Collection

Page 2 (uses ajax):

Page 3:


text:
Q: For rendering image data:image/png;base64 is better OR not? I am currently working on minimizing site execution time by minifying my source code, image rezising, proper image extensions, avoiding redirects and much more.
    I just want to ask you guys whether it is better to use data:image/png;base64 instead of giving static image source path for rendering image ?
    If base64 is better then could you please give me reason also ?


text:
Q: Should not abort ACTION_NEW_OUTGOING_CALL broadcast according to API, but nothing happens The API on the ACTION_NEW_OUTGOING_CALL says:

Any BroadcastReceiver receiving this Intent must not abort the broadcast

When I do (that is, abort the call) by calling abortBroadcast() nothing happens. No error, not even a warning or an information message. Why is this statement put in the API Javadoc?
public class OutgoingCallInterceptor extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        abortBroadcast();
    }
}

A: Possibly to let developers know that doing so will foul up the action (placing a phone call)?
When you about the broadcast I'm assuming that the call fails correct?


text:
Q: how add logical negation(!) operator in dynamic html how to add negation operator in dynamic html content
'
<select ng-model="year" class="form-control" ' + strAttrs[2] + ' ng-options="year.value as year.name disable when year.disabled for year in years" class="form-control" ng-required="true" name="Year"></select>
'

In this above code i have given negation operator like this,

!(form.Year.$error.required)

but every time it is taking null,I guess I have not added logical operator proper in dynamic html content.
Any help is appreciable, Thanks in advance. :)

A: The following works for me:

Result Box

Note that I did not need to escape the single quotes.  When I tried escaping the single quotes it did not work.
I also noticed some invalid quoting going on in your select:
class="form-control" ' + strAttrs[2] + ' ng-options="year.value as year.name disable when year.disabled for year in years"
You also define the class twice, but that should just fail silently.
Here's a tiny working example:

<!doctype html>

  <input type="checkbox" ng-model="success">Success {{success}}

  <input type="checkbox" ng-model="error">Error {{error}}

Result Box


text:
Q: Energy conservation for the wave equation I recently encountered this problem in PDE class involving a concept I have never met, it states:

$ u_{tt} - u_{xx} = 0 ; \space \space 0 < x < 1 ; \space \space t > 0 $
$ u(0,t)=u(1,t)=0 $
$ u(x,0) = x(1-x) $
$ u_t (x,0) = 0 $
We are to use the law of energy conservation for this problem to determine the sum:
$$ \sum_{k=1}^{\infty} \frac{1}{(2k-1)^4} $$

All I can do here is separate variables to solve the problem via eigenfunctions expansions but I do not believe I have encountered the term Energy Conservation for the wave equation and how it can be used to find this sort of sum, I know about Green's functions and how they can be used to find the sums of inverse eigenvalues, so I need someone to help me with this in telling me what this term means and possibly direct me to a source or demonstration of this sort of solution. All help appreciated thanks

A: We solve this by computing the Fourier series of $u = x(1-x)$ and then evaluating $\int_0^1 u_x^2 {\rm d}x$ (the energy) in two different ways.
The Fourier series of $u(x,0) = x(1-x)$ on $[0,1]$ is
$$u(x,0) = \frac{8}{\pi^3}\sum_{n=1}^\infty\frac{\sin[\pi (2n-1) x]}{(2n-1)^3}$$
The energy of the system is given as $H = \frac{1}{2}\int_0^1 u_x^2 + u_t^2{\rm d}x$ as derived in the other answer. At $t=0$ we have $u_t = 0$ so the second term does not contribute.
First by using $u(x,0)=x(1-x)$ we find
$$H = \frac{1}{2}\int_0^1(1-2x)^2{\rm d}x = \frac{1}{6}$$
and secondly by using the Fourier series representation of the solution we also have
$$\begin{align}H &= \frac{32}{\pi^4}\int_0^1 \sum_{n=1}^\infty\sum_{m=1}^\infty \frac{\cos[\pi (2n-1) x]\cos[\pi (2m-1) x]}{(2n-1)^2(2m-1)^2} {\rm d}x \\&= \frac{16}{\pi^4}\sum_{n=1}^\infty \frac{1}{(2n-1)^4}\end{align}$$
Equating the two results gives us
$$\sum_{n=1}^\infty \frac{1}{(2n-1)^4} = \frac{\pi^4}{96}$$
As you can see this problem has little to do with the acctual PDE and energy conservation per se, and is more just an exercise in working with Fourier series.

A: For the first part note that
$$
\frac{d}{dt}(u_t^2/2)=u_tu_{tt}=u_tu_{xx},
$$
then after an integration by parts and up to boundary terms, you will find the Hamiltonian
$$
H=\frac {1}{2}\int_0^1(u_t^2+u_x^2)dx
$$
or the energy, a conserved quantity. For the value of the sum I think you have to expand with respect to a suitable base of [0,1].


text:
Q: MongoDB join on nested Array I'm currently working on a small chat roulette application. For that I user MongoDB and NodeJS in the Backend. To list all of the chat channel I want to join two collections. The elements of the first one (chats) has nested arrays:
{
  title: 'example 1',
  country: 'UK',
  ...
  chat: [
    {
      details: 'chat1 infos',
      channel: [
        '5ea3257d4b861a5aa0d03111',
        '5ea3257d4b861a5aa0d03122'
      ]
    },
    {
      details: 'chat2 infos',
      channel: [
        '5ea3257d4b861a5aa0d03333'
      ]
    }
  ]
}

The second one (channels) stores all the details:
{
  _id: '5ea3257d4b861a5aa0d03111',
  title: 'Channel1',
  details: 'Channel1 Details'
},
{
  _id: '5ea3257d4b861a5aa0d03222',
  title: 'Channel2',
  details: 'Channel2 Details'
},
{
  _id: '5ea3257d4b861a5aa0d03333',
  title: 'Channel3',
  details: 'Channel13 Details'
}

The result should look like that:
{
  title: 'example 1',
  country: 'UK',
  ...
  chat: [
    {
      details: 'chat1 infos',
      channel: [
        {
          _id: '5ea3257d4b861a5aa0d03111',
          title: 'Channel1',
          details: 'Channel1 Details'
        },
        {
          _id: '5ea3257d4b861a5aa0d03222',
          title: 'Channel2',
          details: 'Channel2 Details'
        }
      ]
    },
    {
      details: 'chat2 infos',
      channel: [
        {
          _id: '5ea3257d4b861a5aa0d03333',
          title: 'Channel3',
          details: 'Channel13 Details'
        }
      ]
    }
  ]
}

I tried that by using $lookup:
db.collection('chats').aggregate([
  { "$lookup": {
    "from": "channel",
    "localField": "chat.channel",
    "foreignField": "_id",
    "as": "chat.channel"
  } }
]);

But by that, I join all results on each channel.
Regardless of which ids are contained in the channel. How I can join the collections to get the described result?

A: You can follow this section

you can use populate

 let _doc =await firstModel.find().populate("channels")

A: try this
db.chats.aggregate([
  {
    $unwind: "$chat" // we need this as we have an array of chats, and each chat element has an array of channels
  },
  {
    $lookup: {
      from: "channels", // will use pipeline in lookup to get rid of multiple group stages
      let: {
        channelIds: "$chat.channel"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$_id", // _id of channel
                "$$channelIds" // channel ids from chat.channel array
              ]
            }
          }
        }
      ],
      as: "chat.channel"
    }
  },
  {
    $group: {
      _id: "$_id", // group the unwinded chat array
      title: {
        $first: "$title"
      },
      country: {
        $first: "$country"
      },
      chat: {
        $push: "$chat"
      }
    }
  }
])

check this Mongo Playground


text:
Q: RestController how to Return Object containing flux Spring webflux In my RestController , I'm trying to wrap my response in an ObjectResponse instead of returning flux< X > .
here the ObjectResponse:
public class ObjectResponse {

           private Flux<X> Xbdd;
           private String metadata="Metadata";

}
so my endpoint looks like this:
@GetMapping("/objects")
public ObjectResponse getReactiveObjects() {}

Question:
1- is this possible in a reactive approach ? or should I use instead a List in ObjectResponse and use the collectList Operator ?
Edit:
I end up using the collectList Operator :
 @GetMapping("/objects")
public Mono<ObjectResponse> getListObjects() {
   return objectRepository.findAll().collectList().flatMap(listObjects-> Mono.just(ObjectResponse.builder().Xbdd(listObjects).build()));
}

And using list in ObjectResponse instead of flux:
public class ObjectResponse {

       private List<X> Xbdd;
       private String metadata="Metadata";
}

I read here that it not blocking : https://stackoverflow.com/questions/72038077/does-flux-collectlist-introduce-blocking-behavior#:~:text=No%20collectList()%20is%20not,when%20we%20use%20this%20operator
Any comment/ suggestions  ?


text:
Q: Filter through nested JSON object and obtain JSON with specific keys, using Ruby I currently have a nested JSON object which resembles
{
"People": [
    {
        "Name": "James",
        "Age": "18",
        "Gender": "Male",
        "Sports": []
    },
    {
        "Name": "Sarah",
        "Age": "19",
        "Gender": "Female",
        "Sports": [
            "Soccer",
            "Basketball",
            "Football"
        ]
    }
]
}

Being new to Ruby, I aim to filter throught the entire json and return only the json object/objects in which the "Sports" array has content. So in the above scenario I expect to obtain the object below as a final outcome:
    {
        "Name": "Sarah",
        "Age": "19",
        "Gender": "Female",
        "Sports": [
            "Soccer",
            "Basketball",
            "Football"
        ]
    }

Will I have to initiate a new method to perform such an act? Or would using regular ruby calls work in this case?

A: If you're getting a JSON object from a request, you want to parse it and then you can traverse the hash and arrays to find the information you need. See http://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html
In your case, something like this:
require 'json'

parsed_json = JSON.parse('{"People": [ ... ]}')

parsed_json["People"].each do |person|
  puts person if person["name"] == "Sarah"
end

A: Although @philipyoo answer is right, it miss an explanation on how to "filter" the parsed JSON. If you are new to ruby, take a look at Array#keep_if : http://ruby-doc.org/core-2.2.0/Array.html#method-i-keep_if
require 'json'

people = JSON.parse("{long JSON data ... }")
people_with_sports = people.fetch('People', []).keep_if do |person|
  !person.fetch('Sports', []).empty?
end


text:
Q: How to draw a circle when the face is detected in OpenCV - python So I wrote this code that can detect my face using the webcam and make a rectangle around the face. But how can I draw a circle around the face instead?
import cv2

face_cascade = cv2.CascadeClassifier("face.xml")

cap = cv2.VideoCapture(0)

while True:
    _, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.1, 4)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 100), 3)

    cv2.imshow('img', img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()

A: for (x, y, w, h) in faces:
    center_coordinates = x + w // 2, y + h // 2
    radius = w // 2 # or can be h / 2 or can be anything based on your requirements
    cv2.circle(img, center_coordinates, radius, (0, 0, 100), 3)

Use the coordinates to find the center of the face and from that point draw a rectangle of radius w/2 or h/2.


text:
Q: HermesJMS not able to connect to TibcoEMS server I am trying to browse queues on remote TibcoEMS (ver 8+) server using HermesJMS. Whenever I use Browse option on the configured EMS server, I get following error (server and port obscured):
com.tibco.tibjms.admin.TibjmsAdminException: Unable to connect to server. Root cause:
javax.jms.JMSException: Failed to connect to the server at tcp://servername.domain.com:port
    at com.tibco.tibjms.admin.MessengerUtil.<init>(MessengerUtil.java:59)
    at com.tibco.tibjms.admin.TibjmsAdmin.<init>(TibjmsAdmin.java:458)
    at com.tibco.tibjms.admin.TibjmsAdmin.<init>(TibjmsAdmin.java:439)
    at hermes.ext.ems.TibcoEMSAdminFactory.createAdmin(TibcoEMSAdminFactory.java:105)
    at hermes.ext.ems.TibcoEMSAdmin.getAdmin(TibcoEMSAdmin.java:75)
    at hermes.ext.ems.TibcoEMSAdmin.discoverDestinationConfigs(TibcoEMSAdmin.java:261)
    at hermes.impl.HermesAdminAdapter.discoverDestinationConfigs(HermesAdminAdapter.java:82)
    at hermes.impl.DefaultHermesImpl.discoverDestinationConfigs(DefaultHermesImpl.java:1126)
    at hermes.browser.tasks.DiscoverDestinationsTask.invoke(DiscoverDestinationsTask.java:77)
    at hermes.browser.tasks.TaskSupport.run(TaskSupport.java:175)
    at hermes.browser.tasks.ThreadPool.run(ThreadPool.java:170)
    at java.lang.Thread.run(Unknown Source)
Internal exception:
javax.jms.JMSException: Failed to connect to the server at tcp://servername.domain.com:port
    at com.tibco.tibjms.TibjmsxLinkTcp._createSocket(TibjmsxLinkTcp.java:823)
    at com.tibco.tibjms.TibjmsxLinkTcp.connect(TibjmsxLinkTcp.java:914)
    at com.tibco.tibjms.TibjmsConnection._create(TibjmsConnection.java:1351)
    at com.tibco.tibjms.TibjmsConnection.<init>(TibjmsConnection.java:4311)
    at com.tibco.tibjms.TibjmsQueueConnection.<init>(TibjmsQueueConnection.java:36)
    at com.tibco.tibjms.TibjmsxCFImpl._createImpl(TibjmsxCFImpl.java:200)
    at com.tibco.tibjms.TibjmsxCFImpl._createConnection(TibjmsxCFImpl.java:253)
    at com.tibco.tibjms.TibjmsQueueConnectionFactory.createQueueConnection(TibjmsQueueConnectionFactory.java:87)
    at com.tibco.tibjms.admin.MessengerUtil.<init>(MessengerUtil.java:47)
    at com.tibco.tibjms.admin.TibjmsAdmin.<init>(TibjmsAdmin.java:458)
    at com.tibco.tibjms.admin.TibjmsAdmin.<init>(TibjmsAdmin.java:439)
    at hermes.ext.ems.TibcoEMSAdminFactory.createAdmin(TibcoEMSAdminFactory.java:105)
    at hermes.ext.ems.TibcoEMSAdmin.getAdmin(TibcoEMSAdmin.java:75)
    at hermes.ext.ems.TibcoEMSAdmin.discoverDestinationConfigs(TibcoEMSAdmin.java:261)
    at hermes.impl.HermesAdminAdapter.discoverDestinationConfigs(HermesAdminAdapter.java:82)
    at hermes.impl.DefaultHermesImpl.discoverDestinationConfigs(DefaultHermesImpl.java:1126)
    at hermes.browser.tasks.DiscoverDestinationsTask.invoke(DiscoverDestinationsTask.java:77)
    at hermes.browser.tasks.TaskSupport.run(TaskSupport.java:175)
    at hermes.browser.tasks.ThreadPool.run(ThreadPool.java:170)
    at java.lang.Thread.run(Unknown Source)

However, I can telnet to server on required port, can connect to server using EMS admin console, also able to connect to this server through java program using below code and list queue names:
TibjmsAdmin admin = new TibjmsAdmin( serverUrl, userName, passwd );
System.out.println( "Displaying queues" );
for (QueueInfo qf: admin.getQueues())
    System.out.println( qf.getName()  );

Tried searching on web and SO but to no avail. Its not authentication problem for sure as I can connect using EMS admin console and java program.
Any clue whats going on here?

A: Why do you want to use hermesJMS? Instead you can use GEMS which is perfect for TIBCO EMS and you can perform number of operation using GEMS including publishing message on the queue and reading the content(body) of pending message on the queue.


text:
Q: How to make uwsgi --emperor run as daemon I'm using yaml. It has a line says : daemonize : /var/www/apps/myapp.log
If uwsgi -y vassals/myappconfig.yaml, the website runs in background. I can do other things in terminal, even logout. This is the effect I'm expecting.
If uwsgi --emperor vassals, the website can run, but it stuck up in terminal. I must use ctrl + c to end it to return to terminal. Then the website is down. That's not what I'm expecting.
I don't want to use things like nohup. If uwsgi --emperor is not the right solution, I'd rather to load websites one by one, all run daemonized.

A: you can pass --daemonize <logfile> to the emperor too


text:
Q: how to sort an array of dictionaries depending on several properties of the dictionary I need to sort an array of dictionaries (as close to quick sort as possible), using a keyed object from the dictionary, However because of the complexity of my dictionary (number of keyed valued) and data that can be returned in them I need to be able to sort each dictionary based off several of the keyed values in the dictionary.
for instance, say if dictionay keyvalue1 in array[0], array[1] are equal, then check if keyvalue2 is equal, if yes then continue down the list of keyvalues till the two items that you can sort array[0] & [1] on.
I have read about NSSortDescriptor and specifying the property to compare with where you can set ascending or descending, but I am not sure if this could be used to achive what I am wanting to achieve.
I have been given an example of what I need to do but its in delphi, which I am not very familiar with, however I think the example gives some insight as to what I am trying to do.
//
Result := AnsiCompareText (left.property1, right.Property1);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property2, right.Property2);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property3, right.Property3);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property4, right.Property4);
if Result <> 0 then Exit;
Result := AnsiCompareText (left.property5, right.Property5);
if Result <> 0 then Exit;
//

Hopefully this will give you some idea as to what I am trying to achieve, any help would be greatly appreciated been stuck on this for a while now, if you know of a similar solution in objective C i would love to hear it! :P

A: Lets assume you have a mutable array. Then you use this:
[myArray sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
{
  // you have two items - use whatever complex logic you want, then return
  // one of NSOrderedAscending, NSOrderedSame, NSOrderedDescending
} ];

For instance, suppose all you cared about was a "name" property:
[myArray sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
{
  NSString *n1 = [d1 objectForKey:@"name"];
  NSString *n2 = [d2 objectForKey:@"name"];
  return [n1 localizedCompare:n2];
} ];

There really nice thing about this technique is that the logic can be arbitrarily complex.


text:
Q: How to organize two functions different in the middle part I would like to ask how to nicely organize the below two functions.
I apologize for not uploading the complete code.
void prepend_float(t_ptr *x, float f)
{
    int ac = x->num;
    t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    av[0].type = A_FLOAT; //not common
    av[0].f = f;          //not common
    for (int i = 1; i < ac; ++i)
    {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}

void prepend_string(t_ptr *x, std::string s)
{
    int ac = x->num;
    t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    av[0].type = A_STRING; //not common
    av[0].s = s;           //not common
    for (int i = 1; i < ac; ++i)
    {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}

As you can see the two functions have identical code except for the two lines where I marked not common.
How can I create a common function to reduce the duplicated code?
What I can think now is to create a common function that has 4 arguments like the following.
void common_function(t_ptr *x, float f, std::string, t_type type)
{
    int ac = x->num;
    t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    if (type == A_FLOAT)
    {
        av[0].type = type;
        av[0].f = f;
    }
    else if (type == A_STRING)
    {
        av[0].type = type;
        av[0].s = s;
    }
    for (int i = 1; i < ac; ++i)
    {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}

Is there a better way to organize the two functions?

A: My suggestion: Keep the common parts and turn the differences into parameters.
In your case the difference is two statements. That can be abstracted out by using a function. std::function lets us handle any callable object, and lambda expressions make it easy to pass an ad-hoc function (consisting of the two type-specific statements we need to execute in the middle of the common code):
void prepend_something(t_ptr *x, std::function<void (t_atom &)> init)
{
    int ac = x->num;
    t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    init(av[0]);
    for (int i = 1; i < ac; ++i)
    {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}

void prepend_float(t_ptr *x, float f)
{
    prepend_something(x, [f](t_atom &a) { a.type = A_FLOAT; a.f = f; });
}

void prepend_string(t_ptr *x, std::string s)
{
    prepend_something(x, [s](t_atom &a) { a.type = A_STRING; a.s = s; });
}

A: There are several options for. Classic way would be encapsulating the common code into functions being called from both functions in question:
void f()
{
    common_pre(); // parameters/return value as needed
    specific_f();
    common_post();
}

void g()
{
    common_pre();
    specific_g();
    common_post();
}

You could pack the common code into a single function and pass a lambda to as well:
template<typename Function>
void common(Function& f) // alternatively, instead of template, std::function
{
    common_pre();
    f();
    common_post();
}

void f()
{
    common([/* capture as needed*/] (/*possibly parameters...*/) { /* f specific code */ });
}

void g()
{
    common([] () { /* g specific code */ });
}

The lambda approach is the one I would favour in given case and might look like this:
template <typename Function>
void doPrepend(t_ptr* x, Function& f)
{
    int ac = x->num;
    t_atom* av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    f(av);
    for (int i = 1; i < ac; ++i)
    {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}

void prepend_float(t_ptr* x, float f)
{
    auto assign = [f](t_atom* av)
    {
        av->type = A_FLOAT;
        av->f = f;
    };
    doPrepend(x, assign);
}

void prepend_string(t_ptr* x, std::string const& s)
{
    auto assign = [&s](t_atom* av)
    {
        av->type = A_STRING;
        av->s = s;
    };
    doPrepend(x, assign);
}

Edit: Inspired by schorsch312's answer, however instead of relying on boost and string comparisons, resolving via simple function overload:
void assign(t_atom* av, float f)
{
    av->type = A_FLOAT;
    av->f = f;
}

void assign(t_atom* av, std::string const& s)
{
    av->type = A_STRING;
    av->s = s;
}

template <typename T>
void prepend(t_ptr* x, T const& t)
{
    int ac = x->num;
    t_atom* av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    assign(av, t);
    for (int i = 1; i < ac; ++i)
    {
#if 0
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
#else
        // in this approach; we can even re-use the assign function:
        assign(av + i, x->fv[i - 1]);
#endif
    }
    do_something(x, ac, av);
    free(av);
}

Even a bit less complex than the lambda approach, although the difference is not too significant.
It results in only one single function name (which you could have achieved in the preceding two approaches by overloading the two functions instead of having separate names), though, possibly imposing further changes (specification, documentation, code already using the interface) on you.

A: I would use a template and boost type_index.
template <typename T>
void prepend_string(t_ptr *x, T s) {
    int ac = x->num;
    t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    const std::string valueType = boost::typeindex::type_id<T>().pretty_name();
    if (valueType == "float") {
       av[0].type = A_FLOAT;
       av[0].f = f;
    } else if (valueType == "string") {
        av[0].type = A_STRING;
        av[0].s = s;
    } else {
         // error handling
    }

    for (int i = 1; i < ac; ++i) {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}

This works an Linux and windows.

A: You could use object orientation.
Create an abstract BaseClass and derived classes with type string and float.
In the av structure you have references to the BaseClass and can access manipulation or get methods of the abstract BaseClass.
class MyBaseType
{
     virtual Type GetType() = 0;
     /* manipulation methods .. */
     std::string GetValueAsString() = 0;
}

class MyStringType : public MyBaseType
{
     // implement abstract methods of base class
}
class MyFloatType : public MyBaseType
{
     // implement abstract methods of base class
}

void prepend(t_ptr *x, MyBaseType *MyType)
{
    int ac = x->num;
    t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));
    av[0] = MyType;
    for (int i = 1; i < ac; ++i)
    {
        av[i].type = A_FLOAT;
        av[i].f = x->fv[i - 1];
    }
    do_something(x, ac, av);
    free(av);
}


text:
Q: Extracting values from API GET string I am making an API GET for a range of values across a date range.
How can I work through the returned string of values and pluck out specific values (in this case "day" and "value")
import requests

url = "https://api.something.com/rest/o/GHEYE/n/3/d/4/daily_client_count"

querystring = {
    "start":"2018-11-12T02:04:05",
    "end":"2018-12-13T02:04:05",
    "type":"",
    }

payload = ""
headers = {
    'Content-Type': "application/x-www-form-urlencoded",
    'Authorization': "Bearer xxxxxx44bec4572xxxxxxxx",
    'cache-control': "no-cache",
    'Postman-Token': "462xxxx-2ae4-4938-bae3-7a31xxxxx"
    }

response = requests.request("GET", url, data=payload, headers=headers, params=querystring)

print(response.text)

This returns the following string...
{"resp_code":"SUCCESS","caller_ref":"654656465456564","server_ref":"65464655496545561","data":[{"day":"2018-11-12","value":1125,"wifi_client_connected":0,"usages":1125},{"day":"2018-11-13","value":2292,"wifi_client_connected":0,"usages":2292},{"day":"2018-11-14","value":1772,"wifi_client_connected":0,"usages":1772},{"day":"2018-11-15","value":2068,"wifi_client_connected":0,"usages":2068},{"day":"2018-11-16","value":2309,"wifi_client_connected":0,"usages":2309},{"day":"2018-11-17","value":2479,"wifi_client_connected":0,"usages":2479},{"day":"2018-11-18","value":2341,"wifi_client_connected":0,"usages":2341},{"day":"2018-11-19","value":1550,"wifi_client_connected":0,"usages":1550},{"day":"2018-11-20","value":1417,"wifi_client_connected":0,"usages":1417},{"day":"2018-11-21","value":1734,"wifi_client_connected":0,"usages":1734},{"day":"2018-11-22","value":1954,"wifi_client_connected":0,"usages":1954},{"day":"2018-11-23","value":343,"wifi_client_connected":0,"usages":343},{"day":"2018-11-24","value":16,"wifi_client_connected":0,"usages":16},{"day":"2018-11-25","value":36,"wifi_client_connected":0,"usages":36},{"day":"2018-11-26","value":29,"wifi_client_connected":0,"usages":29},{"day":"2018-11-27","value":34,"wifi_client_connected":0,"usages":34},{"day":"2018-11-28","value":30,"wifi_client_connected":0,"usages":30},{"day":"2018-11-29","value":25,"wifi_client_connected":0,"usages":25},{"day":"2018-11-30","value":852,"wifi_client_connected":0,"usages":852},{"day":"2018-12-01","value":572,"wifi_client_connected":0,"usages":572},{"day":"2018-12-02","value":639,"wifi_client_connected":0,"usages":639},{"day":"2018-12-03","value":848,"wifi_client_connected":0,"usages":848},{"day":"2018-12-04","value":678,"wifi_client_connected":0,"usages":678},{"day":"2018-12-05","value":884,"wifi_client_connected":0,"usages":884},{"day":"2018-12-06","value":288,"wifi_client_connected":0,"usages":288},{"day":"2018-12-07","value":542,"wifi_client_connected":0,"usages":542},{"day":"2018-12-08","value":185,"wifi_client_connected":0,"usages":185},{"day":"2018-12-09"},{"day":"2018-12-10","value":353,"wifi_client_connected":0,"usages":353},{"day":"2018-12-11","value":82,"wifi_client_connected":0,"usages":82},{"day":"2018-12-12","value":18,"wifi_client_connected":0,"usages":18},{"day":"2018-12-13"}]}
[Finished in 1.264s]

I'd like to loop through the string pulling out the VALUE for each DAY and printing them line by line for now.
Thanks.
D

A: for item in response.json().get('data', []):
    print('Day: {}, value: {}'.format(
        item.get('day', ''),
        item.get('value','')
    ))


text:
Q: typesetting use classname in foreach php <?php
  $classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');

  if($productCatalogs != null){

    $i = 0;

    foreach($productCatalogs as $productCatalog){

      $i++;

      if($i % 2 == 0){

        // if $i is even number
        echo '
Link name
';

      } else {

        // if $i is odd number
        echo '
Link name
';

      }

    }

  }
?>

As above code, i want to use each $classNames value in foreach when $i is even number only, like first even number record use { margin-2 }, next even number record use { margin-4 }.
below is that code result i want,

 // if record is odd number, doesn't need class name

 // if record is odd number, doesn't need class name

 // if record is odd number, doesn't need class name

 // if record is odd number, doesn't need class name

 // if record is odd number, doesn't need class name

 // if record is odd number, doesn't need class name

...

A: Just use a counter variable as an index in your array and increment when  you find an even number.Also if you have many elements you need to check if you reached the end of the array and reset your counter.Something like this:
    <?php
  $classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');

  if($productCatalogs != null){

    $i = 0;
    $even_counter=0;

    foreach($productCatalogs as $productCatalog){

      $i++;

      if($i % 2 == 0){

         // if $i is even number
    echo '
Link name
';

    //when we reach the end of the array we reset our counter to 0
    $even_counter=($even_counter+1==count($classNames))?0:$even_counter+1;
      } else {

        // if $i is odd number
        echo '
Link name
';

      }

    }

  }
?>


text:
Q: Need a cheap 24Vac to 12Vdc circuit to test car audio amplifier / equipement I have inherited from a friend a lot of car speakers, amplifiers and related equipements, 'cause his widow says i'm the only friend with some general interest in this field.
Most of these stuffs are from the eighties, some are rusty, some were flooded a couple of years ago and recovered, anyway almost all are in an unknown state, so i want to test them all and decide what to keep, sell or discharge.
I tried one functional amp by using a PC power supply but it can't handle the power peaks.
I have a big 230V to 24Vac transformer, which could handle the required power, but i'd need to build a circuit to have the 12~14Vdc.
I'm not really an expert so i don't know how to take care of the required power, so my question is:
what could be a cheap circuit to have 12Vdc and enough power to test that equipement, starting from 24Vac?
("test" means that i doubt i will try to go to full volume, and that i don't care if the circuit can generate some noise... all i want is to see what's working and what's not)
Thanks

A: Buy yourself a cheap bench power supply.
Since you have no idea of the functionality of the units you are trying to power up you really need something that can limit, and display, the current the thing will try to draw when you plug it in.
Nothing does that better than a bench power supply.
You can probably find a cheap used one somewhere.


text:
Q: Updating existing Object not working in Hibernate In the below code I am trying to update the CommunityUserandRoles object if it already exist, if not insert new object. This code works fine for both insert and update in local environment, but in production its not updating the already existing object and also I am not getting any exception.
Please let me know where its going wrong.
Model Class:
import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "CommunityUsersAndRoles")
@org.hibernate.annotations.Entity(dynamicUpdate = true, dynamicInsert = true)
@org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class CommunityUserRoles implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    /**
     * Lithium user id.
     */
    @Id
    private long lithiumId;

    /**
     * Lithium user email.
     */
    @Column(unique = true)
    private String email;

    /**
     * Lithium user roles.
     */
    private String roles;

    /**
     * Lithium user lastModifiedDate.
     */
    private Date lastModifiedDate;

    /**
     *
     */
    public CommunityUserRoles() {
    }

    /**
     *
     */
    public CommunityUserRoles(long lithiumId, String email, String roles) {
        this.lithiumId = lithiumId;
        this.email = email;
        this.roles = roles;
        this.lastModifiedDate = new Date();
    }

    /**
     * Returns lithiumId.
     *
     * @return Returns the lithiumId.
     */
    public long getLithiumId() {
        return lithiumId;
    }

    /**
     * Sets lithiumId.
     *
     * @param lithiumId
     *            The lithiumId to set.
     */
    public void setLithiumId(long lithiumId) {
        this.lithiumId = lithiumId;
    }

    /**
     * Returns email.
     *
     * @return Returns the email.
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets email.
     *
     * @param email
     *            The email to set.
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * Returns roles.
     *
     * @return Returns the roles.
     */
    public String getRoles() {
        return roles;
    }

    /**
     * Sets roles.
     *
     * @param roles
     *            The roles to set.
     */
    public void setRoles(String roles) {
        this.roles = roles;
    }

    /**
     * Returns lastModifiedDate.
     *
     * @return Returns the lastModifiedDate.
     */
    public Date getLastModifiedDate() {
        return lastModifiedDate;
    }

    /**
     * Sets lastModifiedDate.
     *
     * @param lastModifiedDate
     *            The lastModifiedDate to set.
     */
    public void setLastModifiedDate(Date lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "CommunityUserAndRole [lithiumId=" + lithiumId + ", email=" + email + ", roles=" + roles
                + ", lastModifiedDate=" + lastModifiedDate + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((email == null) ? 0 : email.hashCode());
        result = prime * result + ((lastModifiedDate == null) ? 0 : lastModifiedDate.hashCode());
        result = prime * result + (int) (lithiumId ^ (lithiumId >>> 32));
        result = prime * result + ((roles == null) ? 0 : roles.hashCode());
        return result;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CommunityUserRoles other = (CommunityUserRoles) obj;
        if (email == null) {
            if (other.email != null)
                return false;
        } else if (!email.equals(other.email))
            return false;
        if (lastModifiedDate == null) {
            if (other.lastModifiedDate != null)
                return false;
        } else if (!lastModifiedDate.equals(other.lastModifiedDate))
            return false;
        if (lithiumId != other.lithiumId)
            return false;
        if (roles == null) {
            if (other.roles != null)
                return false;
        } else if (!roles.equals(other.roles))
            return false;
        return true;
    }

}

DAO Class:
import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.xyz.am.exception.PersistenceLayerException;
import com.xyz.am.persistence.foundation.AbstractGenericHibernateDAO;
import com.xyz.zbc.efg.model.CommunityUserRoles;

public class CommunityUserRolesDAO extends AbstractGenericHibernateDAO<CommunityUserRoles>
        implements ICommunityUserRolesDAO {

    @Override
    public boolean isLithiumIdExist(long lithiumId) throws PersistenceLayerException {
        final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(getPersistentClass())
                .add(Restrictions.eq("lithiumId", lithiumId));
        if (findByCriteria(detachedCriteria).size() == 1) {
            return true;
        }
        return false;
    }

    @Override
    public CommunityUserRoles getByEmail(String email) throws PersistenceLayerException {
        final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(getPersistentClass())
                .add(Restrictions.eq("email", email));
        if (findByCriteria(detachedCriteria).size() == 1) {
            return findByCriteria(detachedCriteria).get(0);
        }
        return null;
    }

    @Override
    public void insert(final CommunityUserRoles communityUserRoles) throws PersistenceLayerException {
        super.saveOrUpdate(communityUserRoles);
    }

}

Service Class method:
CommunityUserRoles communityUserRoles = null;
                          if(communityUserRolesDAO.isLithiumIdExist(lithiumUserId)) {
                              communityUserRolesDAO.getByEmail(email)
                              communityUserRoles.setRoles(roles);
                              communityUserRoles.setLastModifiedDate(new Date());

                          }else {
                              communityUserRoles = new CommunityUserRoles();
                              communityUserRoles.setLithiumId(lithiumUserId);
                              communityUserRoles.setEmail(lithiumUsers.get(lithiumUserId).getEmail());
                              communityUserRoles.setRoles(roles);
                              communityUserRoles.setLastModifiedDate(new Date());
                              log.info("New User ID "+lithiumUserId+" Email "+lithiumUsers.get(lithiumUserId).getEmail()+" Roles "+roles+" Date "+new Date());
                          }
                          communityUserRolesDAO.insert(communityUserRoles);


text:
Q: Does SNMP version 1 and 2 Support TLS? I'm trying to send a message via SNMP version 1 or 2.
I need TLS support for safe transmission.
Does both version support TLS?  (I'm using SNMP4j Library in Java)

A: No, SNMP v1 and v2 send everything in plaintext over the network.
You have to use SNMP v3 together with the security level authPriv.
Note: SNMP v3 also support the security levels noAuthNoPriv and authNoPriv which will send the data unencrypted, too.


text:
Q: Error in Creating web-service client I have created one webservice for accessing database.it's working fine .but when i am trying to creat client from that using it's WSDL it's giving error as
    "The Apache Axis2 Web service runtime does not support the client project"

I am using tomcat 6.0 and Axis2 .for creating client i have created java project and then trying to create client .SO I'm not getting why this error is getting .for axis2 does the client project is to be Dynamic web project??

A: I think You should create new "Dynamic Web Project". In the project wizard you should change "Dynamic web module version" from 3 to lower(2.2, 2.3, 2.4 or 2.5). In my case it worked with 2.5. Then you can finish creating project and generate web service client.


text:
Q: R: Displaying mean and median labels on boxplot ggplot I've just started working with R and trying to find out how to add mean and median labels on a box plot using ggplot.
I have a dataset: Unit, Quarter, # of Days:
dset <- read.table(text='Unit     Quarter  Days   Z
HH       1Q      25  Y
PA       1Q      28  N
PA       1Q      10  Y
HH       1Q      53  Y
HH       1Q      12  Y
HH       1Q      20  Y
HH       1Q      43  N
PA       1Q      11  Y
PA       1Q      66  Y
PA       1Q      54  Y
PA       2Q      19  N
PA       2Q      46  Y
PA       2Q      37  Y
HH       2Q      22  Y
HH       2Q      67  Y
PA       2Q      45  Y
HH       2Q      48  Y
HH       2Q      15  N
PA       3Q      12  Y
PA       3Q      53  Y
HH       3Q      58  Y
HH       3Q      41  N
HH       3Q      18  Y
PA       3Q      26  Y
PA       3Q      12  Y
HH       3Q      63  Y
                   ', header=TRUE)

I need to show data by Unit and Quarter and create a boxplot displaying mean and median values.
My code for a boxplot:
ggplot(data = dset, aes(x = Quarter
                       ,y = Days, fill = Quarter))  +
  geom_boxplot(outlier.shape = NA) +
  facet_grid(. ~ Unit) + # adding another dimension
  coord_cartesian(ylim = c(10, 60)) + #sets the y-axis limits
  stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red", fill="red") + #adds average dot
  geom_text(data = means, aes(label = round(Days, 1), y = Days + 1), size = 3) + #adds average labels
  geom_text(data = medians, aes(label = round(Days, 1), y = Days - 0.5), size = 3) + #adds median labels
  xlab(" ") +
  ylab("Days") +
  ggtitle("Days") +
  theme(legend.position = 'none')

I can use geom_text function to add mean and median labels but only for one dimension ("Quarter") and it requires calculation of mean and median variables beforehand:
means <- aggregate(Days ~  Quarter, dset, mean)
medians <- aggregate(Days ~  Quarter, dset, median)

It works pretty good and I managed to calculate mean and median values by both "Unit" and "Quarter":
means <- aggregate(dset[, 'Days'], list('Unit' = dset$Unit, 'Quarter' = dset$Quarter), mean)
medians <- aggregate(dset[, 'Days'], list('Unit' = dset$Unit, 'Quarter' = dset$Quarter), median)

but I do not know how to pass those variables to geom_text function to display lables for the mean and median. Maybe I should calculate mean and median in a different way or there are other options how to add those labels.
Would be grateful for any suggestions!

A: Looks like the problem is that when you calculate the mean and median values by both "Unit" and "Quarter" the variable the used to be called "Days" is in now called "x". So simply update your geom_text commands to reflect this.
ggplot(data = dset, aes(x = Quarter, y = Days, fill = Quarter))  +
  geom_boxplot(outlier.shape = NA) +
  facet_grid(. ~ Unit) + # adding another dimension
  coord_cartesian(ylim = c(10, 60)) + #sets the y-axis limits
  stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red", fill="red") + #adds average dot
  geom_text(data = means, aes(label = round(x, 1), y = x + 1), size = 3) + #adds average labels
  geom_text(data = medians, aes(label = round(x, 1), y = x - 0.5), size = 3) + #adds median labels
  xlab(" ") +
  ylab("Days") +
  ggtitle("Days") +
  theme(legend.position = 'none')

A: In answer to your second question, I think you are looking for something like this. This code produces the same chart but restricting to the subsample Z = Y.
means <- aggregate(dset[, 'Days'][dset$Z=="Y"], list('Unit' = dset$Unit[dset$Z=="Y"], 'Quarter' = dset$Quarter[dset$Z=="Y"]), mean)
    medians <- aggregate(dset[, 'Days'][dset$Z=="Y"], list('Unit' = dset$Unit[dset$Z=="Y"], 'Quarter' = dset$Quarter[dset$Z=="Y"]), median)

ggplot(data = dset[dset$Z=="Y",], aes(x = Quarter, y = Days, fill = Quarter))  +
  geom_boxplot(outlier.shape = NA) +
  facet_grid(. ~ Unit) + # adding another dimension
  coord_cartesian(ylim = c(10, 60)) + #sets the y-axis limits
  stat_summary(fun.y=mean, geom="point", shape=20, size=3, color="red", fill="red") + #adds average dot
  geom_text(data = means, aes(label = round(x, 1), y = x + 1), size = 3) + #adds average labels
  geom_text(data = medians, aes(label = round(x, 1), y = x - 0.5), size = 3) + #adds median labels
  xlab(" ") +
  ylab("Days") +
  ggtitle("Days") +
  theme(legend.position = 'none')


text:
Q: Ruby on rails scaffold model validation questions I am trying to follow a ruby on rails scaffold example.
I am using ruby version: 2.1.5 with rails version : 4.1.8
I have used this command:
rails generate scaffold User name:string email:string

This worked fine - I can run the example which shows crud functionality to my generated scaffold. The examples I have been following advise to look at the model file generated. The ones in the examples seemed to have a value called attr_accessible - but for me this was not generated - I do not know why - it seems to be quite useful so you can easily see what is inside your model? My model looks like this:
class User < ActiveRecord::Base

end

I altered it to look like this :
class User < ActiveRecord::Base
    attr_accessible :name, :email
    validates :name, :presence=>true
end

and when I now visit localhost/users I get the error:

Can somebody please tell me how a generated model can be created with this attr_accessible line, and how I can add an example of validation to the model.

A: Rails 4 doesn't use attr_accessible; it uses Strong Parameters.
They both serve as a guard for mass assignment of params, often times used during form submissions.
The scaffold doesn't support automatically setting strong params as far as I'm aware, in part because people implement strong params white listing very differently.
A couple more links on Strong Params

*

*How is attr_accessible used in Rails 4?

*https://github.com/rails/strong_parameters

*https://github.com/elabs/pundit#strong-parameters <= I strongly recommend this gem

To me this suggests whatever guide you're following is out of date.

A: I think the problem is that the scaffolding that you have used is not compatible with how Rails works in later versions. In earlier versions of Rails, attr_accessible was used for preventing security problems related to mass assignment. In later versions, the countermeasure changed and moved to the controller instead of the model.
If you still want to use the attr_accessible macro, you can add gem 'protected_attributes' to your Gemfile and install with bundler.

A: You shouldn't add them in the model.
The stuff you wanna access goes into the controller, like
def index
  @users = User.all
end

def show
  @user = User.find(params[id])
end

...

private

def user_params
  # It's mandatory to specify the nested attributes that should be whitelisted.
  # If you use `permit` with just the key that points to the nested attributes hash,
  # it will return an empty hash.
  params.require(:user).permit(:name, :mail)
end

so you can use them afterwards in your views.
e.g. in app/views/users/show...

@user.name

@user.email


text:
Q: My AutoML Image classification model has been training for longer than the requested node hours I am new to VertexAI. I am trying out its AutoML feature for a single label image classification problem. I followed all recommended steps to upload my images (Jpegs with resolution 720 x 1024) and had a manual split of data (Total images 1001 for label 1 and 870 for label 2, split approximately to 80,10 and 10% for training, validation and test). I set the requested node hours to 8 and started training. The training has been going on for more than 11 and half hours at which time I cancelled the training. Prior to this I had requested 20 node hours and the training kept going on for more than 1 day and 11 hours for the same dataset.
So my questions are:

*

*Why does the training continue for more time than requested through the node hour budget?

*Is there a way to check how the model training is progressing? Any logs for training, intermediate values of model performance through the epochs, etc. that can be accessed?
Basically, I have no idea if and how the training is progressing.

I have read through the documentation on vertex AI that I could find and other blogs and posts on the internet, but could not find any specific answers. Some posts says their image classification model with Vertex AI AutoML trained within a few hours, with about 1000s of images.
I would much appreciate any help with this. Thanks


text:
Q: How to disable anchor tag after first click in javascript ? I have a a href tag with css class thickbox I need to disable the link after first click. how I can do this?
Aspx code

My JavaScript Method
function DoSomething(element) {

                return true;
            }

A: In your javascript you can set the attribute disabled="" at your element. (look here)
If, with disable, you mean to not let the browser go to the url, you have to call event.preventDefault() (look here)

A: For this you have to create a hidden feild which will store a value example 1 or 0. If the user clicks the link first time set the hidden feild value to 1 and allow the user to redirect and then disable the hyperlink. If user again clicks the hyper link then first check the hidden feild if it contains a value 1 then don't allow him to redirect. Hope you understand my point. Also set the href property in the javascript.

A: I'm not sure exactly what the OP is trying to do, but if it is purely to allow the script to run the once after clicking, something like this would work...
function DoSomething(element) {
  if(element.getAttribute("block")==null){
    ...
    element.setAttribute("block","1");
    return true;
  }else{
    return false;
  }
}

This has the advantage of not changing the style of button by setting the disabled attribute.
However, returning true from the function and then in turn returning true to the OnClick handler of the link will result in the browser navigating to the URL in href... so I can't see why the need for the blocking of a 2nd run. (Unless thickbox, which I know nothing about, works in a way which is not the normal.)


text:
Q: Как изменить владельца таблицы в базе? Не могу изменить владельца таблицы searches c postgres на flautdb в PostgreSQL. Делаю запрос:
ALTER TABLE flaut.searches OWNER TO flautdb;
ALTER TABLE public.searches OWNER TO flautdb;
ALTER TABLE searches OWNER TO flautdb;

Ничего из этого не работает. Хотя в документации PSQL сказано, что, мол, просто укажите название таблицы. А ничего подобного:

ERROR:  relation "searches" does not exist

UDP: таблица searches существует в базе flaut. База flaut принадлежит роли flautdb, а вот таблица searches внутри неё принадлежит postgres. Если запросить таблицы под ролью flaut, то всё нормально:
          List of relations
 Schema |   Name   | Type  |  Owner
--------+----------+-------+----------
 public | searches | table | postgres
(1 row)

А вот если запрашивать под ролью postgres уже нельзя - она не видит таблицу. А в контексте базы flaut под ролью flautdb изменять ничего не могу.

flaut=> ALTER TABLE searches OWNER TO flautdb;
ERROR:  must be owner of relation searches


text:
Q: how to add class and remove class of list item how to add class and remove class of list item. while i have a sidebar where i have conditioned that when normal users log in then this list will be displayed and if admin is logged in then another list will be displayed but all the list have single ul
for example :
session_start();
echo '
';
switch($_SESSION['role'])
{
case 'admin':
 echo '
';
 echo 'Dashboard';
 echo '
';
 echo '
';
 echo 'Manage User';
 echo '
';
break;
case 'user':
 echo '
';
 echo 'Profile';
 echo '
';
 echo '
';
 echo 'Status';
 echo '
';
break;
default:
break;
}
echo '
';

So I want to say, when admin logged in then Dashboard and Manage User menu will show and so on.
if admin click on Manage User, its look should be changed through css for active class.
Please provide me solution.

A: You should put an id to your menu to avoid confusion :

You can do something like this :
$("#menu li").click(function () {
    $("#menu li").removeClass("active");
    $(this).addClass("active");
});


text:
Q: Can I perform an outer join with LINQ? I have two classes where the key2 of town links to the key 1 of utility. The data is not stored in SQL tables so there's no way I can link and get what I need with SQL.
public class Town {
    key1 string { get; set; }
    key2 string { get; set; }
    name string { get; set; }
}

public class Utility {
    key1 string { get; set; }
    key2 string { get; set; }
   name string { get; set; }
}

Data looks like the following
Town
-------
key1             key2         name
0                 1               Liverpool
0                 2               Preston
0                 3               Wigan

Utility
------

key1      key2
1           West 2
1           West 3
3           East 1
3           East 2

What I would like to do is to create a report that showed a list of all the towns with a secondary column to show how many utilities each had.
The report would look something like this
Liverpool  2
Preston    0
Wigan      2

The data cannot be obtained from just the utility information as I need to show where a town has no utilities. What I was
thinking of was some code that iterated through the Towns and then for each town did a check and counted up the number
of utility rows.
if the data was stored in the following collections:
ICollection<Town> Towns
ICollection<Utility> Utilities

Then is there some kind of LINQ query that would somehow join up these collections in a similar way to an outer join in SQL?

A: Check out Microsoft's 101 LINQ Samples.  It provides excellent examples of joins.  I don't know how anyone does LINQ without it.

A: This would work, and it's most straightforward:
var results = Towns.Select(t => new {
                       Town = t,
                       Utilities = Utilities.Count(u => t.key2 == u.key1)
              })
              .ToList();


text:
Q: JTable frozen columns not scrolling (Java 1.6) I am migrating an application from java 1.5 to 1.6 (yeah, I know).
We have a table with some frozen columns.  Constructed like so (roughly)
JScrollPane tablePane = new JScrollPane();
JTable mainTable = new JTable();
JTable frozenTable = new JTable()
JPanel rowHeaderPanel = new JPanel();
rowHeaderPanel.add(frozenTable);

tablePane.setRowHeaderView(rowHeaderPanel);
tablePane.setViewportView(mainTable);

(Table models for the main and frozenTable always have the same number of rows)
This worked as we wanted under java 1.5, ie: we had a data table with a number of frozen columns on the left hand side.  Scrolling the pane vertically scrolled both tables in unison.
Without any code changes other than moving to java 1.6 we now have an intermittent and (in dev environment) unreproducible bug.
Sometimes when you vertically scroll only the main table scrolls - the frozen table does not scroll at all.  The tables appear unlinked.
Has anyone seen anything like this before?

A: The intermittent nature of the problem should prompt one to verify that the GUI components are constructed on the event dispatch thread. The move to 1.6 may have changed the timing just enough to expose such an anomaly.

A: I have not seen anything like this before and since it is unreproducible, it will be hard to debug.  I suggest paring it down to as small of an example as possible (basically a SCCEE) and see if you reproduce the behavior.  If it still intermittent exists then it might be something to do with 1.6 but I doubt it.  If it no longer exists, then it might be something else happening in the background at the same time.

A: I agree, this is a tough problem. But the way we do it is slightly different and it currently works in production under Java 6. So it may help to solve the issue IMO.I tried to use the same variable names as in initial code. Here is the code we use:
JViewport viewport = new JViewport();
viewport.setView(frozenTable);
viewport.setPreferredSize(frozenTable.getPreferredSize());
tablePane.setRowHeaderView(viewport);
tablePane.setCorner(JScrollPane.UPPER_LEFT_CORNER,frozenTable.getTableHeader());


text:
Q: Yii Framework One to many relationship Im having a bit of a headache with trying to input data into a one to many relationship table (videos) from one form which has access to the main database called movie.. so one movie can have lots of videos attached to it.. I have one form which can add more than one video through  the users being able to add more text fields for the amount of videos they want to store..tried various option. but the records dont seem to store inside the youtube_video table..
this is what I have got so far...
Movie Model (Movie)
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'competitions' => array(self::HAS_MANY, 'Competition', 'movie_id'),
        'studio' => array(self::BELONGS_TO, 'Studio', 'studio_id'),
        'country' => array(self::BELONGS_TO, 'Country', 'country_id'),
        'movieRating' => array(self::BELONGS_TO, 'MovieRating', 'movie_rating_id'),
        'mapPin' => array(self::BELONGS_TO, 'MapPin', 'map_pin_id'),
        'twitterFeeds' => array(self::HAS_MANY, 'TwitterFeed', 'movie_id'),
        'YoutubeVideo' => array(self::HAS_MANY, 'YoutubeVideo', 'movie_id'),
    );
}

Movie Form Part of the Form -

    <?php echo $form->labelEx($model,'description'); ?>
    <?php echo $form->textArea($model,'description',array('rows'=>6, 'cols'=>50)); ?>
    <?php echo $form->error($model,'description'); ?>

    <?php echo $form->labelEx($model,'title_trailer_youtube_code'); ?>
    <?php echo $form->textField($model,'title_trailer_youtube_code',array('size'=>50,'maxlength'=>50)); ?>
    <?php echo $form->error($model,'title_trailer_youtube_code'); ?>

    <?php echo $form->labelEx($model,'title_image'); ?>
        <?php echo CHtml::activeFileField($model, 'title_image'); ?>
        <?php echo $form->error($model,'title_image'); ?>

    <?php echo $form->labelEx($modelYoutubeVideo,'embed_code'); ?>
    <?php echo $form->textField($modelYoutubeVideo,'embed_code',array('size'=>50,'maxlength'=>50)); ?>
    <?php echo $form->error($modelYoutubeVideo,'embed_code'); ?>

    <?php echo $form->labelEx($modelYoutubeVideo,'description'); ?>
    <?php echo $form->textField($modelYoutubeVideo,'description',array('size'=>50,'maxlength'=>250)); ?>
    <?php echo $form->error($modelYoutubeVideo,'description'); ?>

Movie Controller -
    public function actionCreate()
{
    $model=new Movie;  // this is my model related to table

    $modelYoutubeVideo=new YoutubeVideo;

    if(isset($_POST['Movie']))
    {

        $model->attributes=$_POST['Movie'];

        // Save Title Image and store file name in database

        $_POST['Movie']['title_image'] = $model->title_image;
        $uploadedFile=CUploadedFile::getInstance($model,'title_image');
        $name = $uploadedFile->getName();
        $model->title_image = $name;

        if($model->save())
        {

            if(!empty($uploadedFile))  // check if uploaded file is set or not
            {
                $uploadedFile->saveAs(Yii::getPathOfAlias('webroot')."/title_image/".$name);
            }

            $modelYoutubeVideo = new YoutubeVideo();

            $modelYoutubeVideo->attributes=$_POST['youtube_video'];

            // Redirect to admin

            $this->redirect(array('admin'));

        }
    }

    $this->render('create',array(
        'model'=>$model,
        'modelYoutubeVideo'=>$modelYoutubeVideo,

    ));
}

A: Well, are you duplicating
 many times to allow people to link more videos? Because if you are then you are not saving them in the DB.
After you save the the main record "foreach" through the videos and save each of them. Also you never save $modelYoutubeVideo so ....

A: After
$modelYoutubeVideo->attributes=$_POST['youtube_video'];
you should put
$modelYoutubeVideo->save();


text:
Q: Application does not launch in admin mode created from visual studio installer I have created setup.exe and msi for that, using visual studio 2013 installer project. Setup.exe installs perfectly fine however my application created in program file(X86) will not launch in admin mode by default. Is there any setting i need to do in installer project.
update: My .msi runs in admin mode i have added launch condition for this.

A: Add a app.manifest in your project and change the following line in app.manifest file:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />


text:
Q: mod_rewrite not working to secure grails application I have a grails application running on tomcat and I'm using mod_proxy to connect http server with it. My goal is to secure the login process.
My VirtualHost configuration to force https is:
ProxyPass /myapp/ http://127.0.0.1:8080/myapp
ProxyPassReverse /myapp/ http://127.0.0.1:8080/myapp

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(myapp/login) https://%{HTTP_HOST}:443/$1 [NC,R=301,L]

When I go to https://mydomain.com/myapp/adm - which requires authentication - it redirects to http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy, with no security so the rewrite is not working (if I manually replace http with https, it works fine).
Any hints?

A:
When I go to https://mydomain.com/myapp/adm - which requires
  authentication - it redirects to
  http://mydomain.com/myapp/login/auth;jsessionid=yyyyyy,

Looks like Spring security perform redirects to /login/auth.
Burt Beckwith mention here that spring security does not need grails.serverURL.
It should use request.getServerName()
Basically grails.serverURL has been used for createLink methods
I would suggest:

*

*try to use https in grails.serverURL for production environment

*set app context (if item 1) didn't help):
grails.app.context="/myapp"
Update
Just for isolate and better understand where the problem is:
Could you please run grails (on development environment) with https and check if everything works fine:
grails run-app -https

A: You made a typo, you wanted this:
RewriteRule ^/myapp/login https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

Your current RewriteRule can't ever match
I also doubt there's a point in having this
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/myapp/login [NC]

This only duplicates the ^/myapp/login you wanted in the RewriteRule. So while it works it serves no purpose.

A: In a setup where you allow both http and https, add a separate Connector element to tomcat's conf/server.xml file:
<Connector port="8081" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"  URIEncoding="UTF-8"
           scheme="https" secure="true" proxyName="somehostname.domain" proxyPort="443" />

If only https is allowed, you can add the scheme, secure, proxyName and proxyPort attributes to the existing Connector element.
In apache config, make the *:443 virtual host proxy to the Connector with the extra attributes. The plain http *:80 can connect to the original Connector.
For more information:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html#Proxy_Support
http://tomcat.apache.org/tomcat-7.0-doc/proxy-howto.html


text:
Q: VBA Conditional Formatting syntax for xlUniqueValues I am trying to highlight duplicates using conditional formatting under VBA.
If you look at Conditional formatting using VBA, one of the XlFormatConditionType (Type) for FormatConditions.Add is xlUniqueValues.
Syntax: FormatConditions.Add(Type, Operator, Formula1, Formula2)
The listed operators are: xlBetween; xlEqual; xlGreater; xlGreaterEqual; xlLess; xlLessEqual; xlNotBetween; xlNotEqual.
None of these apply to xlUniqueValues.  I have tried them all, including xlDuplicate and xlUnique, which do not throw errors.  Types xlTextString uses TextOperator, and xlTimePeriod uses DateOperator as operator modifiers, but there is no info on a modifier for xlUniqueValues.
With Range("a1:a10").FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="egg")
     .Interior.Color = RGB(255, 166, 0)
End With

My code:
With Range("B6:B30").FormatConditions.Add(xlUniqueValues, xlDuplicate)
     .Interior.Color = RGB(255, 166, 0)
End With

This highlights all unique values, no matter what I put in for the operator.  The syntax is correct, but I can find no info on how to highlight duplicates.
What is the correct syntax to highlight duplicates?
I have this working as a macro captured conditional formatting (shown below), but I'd like to get it working with this syntax, since it is cleaner.
Range("B6:B30").Select
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = RGB(255, 166, 0)
    .TintAndShade = 0
End With

A: It might be cleaner but it does not work as you have already discovered. The FormatCondition.Add's Operator parameter in this case is ignored:

Can be one of the following XlFormatConditionOperator constants: xlBetween, xlEqual, xlGreater, xlGreaterEqual, xlLess, xlLessEqual, xlNotBetween, or xlNotEqual. If Type is xlExpression, the Operator argument is ignored.

The UniqueValues documentation states that:

The UniqueValues object uses the DupeUnique property to return or set an enum that determines whether the rule should look for duplicate or unique values in the range.

Meaning that if you want to check for duplicates, use DupeUnique property which:

Returns or sets one of the constants of the XlDupeUnique enumeration, which specifies if the conditional formatting rule is looking for unique or duplicate values.

Your code will change to:
With Range("B6:B30").FormatConditions.Add(xlUniqueValues)
     .DupeUnique = xlDuplicate
     .Interior.Color = RGB(255, 166, 0)
End With

OR
With Range("B6:B30").FormatConditions.AddUniqueValues
     .DupeUnique = xlDuplicate
     .Interior.Color = RGB(255, 166, 0)
End With


text:
Q: Tkinter error: _tkinter.TclError: unknown option "-menu" Following along with a YouTube video, however I keep getting this tkinter error and I have not the faintest clue from where it originates
Code:
import tkinter as tk

G_FONT=("Verdana", 12)

class CapApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        frame = StartPage(container, self)
        self.frames[StartPage] = frame
        frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

def show_frame(self, cont):
    frame = self.frames[cont]
    frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, controller)
        label = tk.Label(self, text="Start Page", font=G_FONT)
        label.pack(pady=10, padx=10)

if __name__ == "__main__":
    app = CapApp()
    app.mainloop()

A: Agree the error message is confusing. Anyway, there's a couple of errors in your code — fixed and noted in comments in the code below:
import tkinter as tk

G_FONT=("Verdana", 12)

class CapApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        frame = StartPage(container, self)
        self.frames[StartPage] = frame
        frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

    # Fixed indentation so function is a class method.
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        # You're passing too many arguments the base class __init__()
#        tk.Frame.__init__(self, parent, controller)1
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Start Page", font=G_FONT)
        label.pack(pady=10, padx=10)

if __name__ == "__main__":
    app = CapApp()
    app.mainloop()


text:
Q: Can I disable generating hidden field for checkbox tag: in Spring MVC? Can I disable spring MVC to generate hidden field for checkbox. I'm using Thymeleaf templates.
Thanks!

A: This is a fairly old question, but I just ran into this posting a Spring form that contained checkboxes with a GET action. My work-around also uses jQuery, which was not tagged in this question, but it did achieve the desired result.
The _checkbox hidden field was showing in the URL as a query string parameter. I ended up using jQuery to remove the Spring-generated hidden fields at page load, which cleaned up the URL on submit. I did not see any adverse behavior on the server side.


text:
Q: Crystal Reports cross tab but not with the "Cross-Tab" tool My question is simple. Is is possible to have a cross-tab-like table in crystal reports?
The rows are people, the columns are trainings and the data of the cells are dates that this person participated in the training..
Is this possible?
My first though was to have a formula with a Select/case to check the name o the training (because I don't care for all of them) and if the training name is Name1, the formula should set the date of the training to a variable and somehow I would be able to use this variable and show it to my report. But I don't know even if that is possible or how it could be done.
Thanks in advance for any help.

A: In this case since columns are static..you can try below process:
you can use the same design part or increase the design part till all the static columns fit the design using the Page setup.
manually create the columns and place side by side in header... either page or group as per your report requirement.
For rows place the fields that you want to see in details and make sure to provide sufficient space between Participates and Dates.
Now play a bit with lines between columns and rows so that it looks like table and add summaries as required.
This will give the display of the cross tab though it is not cross tab.
Hope this helps


text:
Q: How to get all celery tasks? everyone. I want to get all celery tasks in my program.
Like Django-admin did.

But I have searched a lot which didn't help.
Plz. Help me out!

A: So this code would solve this problem:
from celery import current_app
def get_celery_all_tasks():
    current_app.loader.import_default_modules()
    tasks = list(sorted(name for name in current_app.tasks
             if not name.startswith('celery.')))
    return tasks

Then will return all celery tasks beside celery.

A: I think you should be able to do something such as this:
from celery import current_app

for name in sorted(current_app.tasks):
    if not name.startswith('celery.'):
        print(name)

django-celery does something similar to retrieve the list of tasks for the admin display.


text:
Q: Reject drag/drop based on object data? I have c# DataGridViews modified so that I can drag and drop rows between them.  I need to figure out how to either disable dragging on certain rows, or reject the drop for these rows.  The criteria I'm using is a value in the datarow.
I'd like to disable the row (gray it out and not allow drag) as my first choice.
What options do I have?  How can I disable or reject drag-drop based on criteria?

A: If you want to prevent a row from being dragged at all, use the following method instead:
void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
    DataGridViewRow row = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow)); // Get the row that is being dragged.
    if (row.Cells[0].Value.ToString() == "no_drag") // Check the value of the row.
        e.Effect = DragDropEffects.None; // Prevent the drag.
    else
        e.Effect = DragDropEffects.Move; // Allow the drag.
}

Here, I presume you start the drag operation by doing something like this:
DoDragDrop(dataGridView1.SelectedRows[0], DragDropEffects.Move);

In this case, you don't need to use the method from my previous answer, of course.

A: Here is a sample method that should get you started:
    void dataGridView1_DragOver(object sender, DragEventArgs e)
    {
        Point cp = PointToClient(new Point(e.X, e.Y)); // Get coordinates of the mouse relative to the datagridview.
        var dropped = dataGridView1.HitTest(cp.X, cp.Y); // Get the item under the mouse pointer.
        if (dataGridView1.Rows[dropped.RowIndex].Cells[0].Value.ToString() == "not_allowed") // Check the value.
            e.Effect = DragDropEffects.None; // Indicates dragging onto this item is not allowed.
        else
            e.Effect = DragDropEffects.Move; // Set the drag effect as required.
    }

You should, of course, use it like this:
dataGridView1.DragOver += new DragEventHandler(dataGridView1_DragOver);

Modify the condition in the if-clause to your needs. Currently, it disables dragging onto a row if the first cell value equals to the "not_allowed".

A: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.dodragdrop.aspx
You can override DragEnter and DragLeave functions to achieve
In DragLeave - you can query your object based on selection and cancel operation if the object does not have the required value
Cheers

A: Probably a bit late but I had the same issue today. I wanted to prevent a drag of a list item in some situation.
I ended up using the _ItemDrag event handler. Inside the handler I checked wether dragging the Item was allowed and if not I used a SendKeys.Send("{ESC}"); command to cancel the drag.
//Prevents dragging tree items that have at least one child item
    private void lvTaxonomyItemLedgerAccounts_ItemDrag(object sender, ItemDragEventArgs e)
        {
           LedgerAccountTaxonomyItem accountTaxonomyItem = ((OLVListItem)e.Item).RowObject as LedgerAccountTaxonomyItem;
           if (_ledgerAccountTaxonomyItems.FirstOrDefault(m => m.ParentAccountId == accountTaxonomyItem.Id) != null)
               SendKeys.Send("{ESC}");
        }


text:
Q: Prove that $a_{n}=\frac{b}{2a+a_{n-1}}$ is convergent For any positive integer numbers $a$ and $b$ consider the sequence:
\begin{eqnarray}
 a_{1}=a \hspace{0.5cm} a_{n}=\frac{b}{2a+a_{n-1}}
\end{eqnarray}
For $n\geq 2$. I need to prove this sequence is convergent, but if $a,b \in \mathbb{Z^{+}}$ it is not always increasing, maybe I need to find a subsequence of this sequence, but it's hard to see a simple view, I don't know if I need to see the $\overline{\lim a_{n}}$ and $\underline{\lim a_{n}}$ where:
\begin{eqnarray}
 \overline{\lim a_{n}}&=&\sup_{k\geq n}\{a_{k}\}\\
 \underline{\lim a_{n}}&=&\inf_{k\geq n}\{a_{k}\}
\end{eqnarray}
If you can give me one advice or hint, I will be grateful, as I don't see some things. Thanks .

A: Hint 1: Can you show that the sequence is bounded?
Hint 2: Can you look at the possible limits for any subsequence? Can you show that all subsequences have to converge to the same limit?

A: If there is a limit, $L,$ it solves $L=\frac b{2a+L}.$ Solve for $L.$ (There are two solutions for $L,$ but one of them is negative, so you can ignore that case.)
Then relate $|a_n-L|$ in terms to $|a_{n-1}-L|.$ Use that to show $|a_n-L|\to 0.$


text:
Q: How to show event date highlight(from database) in calender php I am using php in my project, for which I am using a JavaScript calendar. I have an event date in my database, which I want to highlight in my calendar. I have tried the following code:
PHP
$items = '';

        $selq = mysql_query("SELECT * FROM ".$gettn." WHERE template_content_id = '$gettid'");

        $fetselq = mysql_fetch_array($selq);

        $linkId1 = $fetselq['id'];

        $getevent1 = mysql_query("SELECT * FROM `template3event` WHERE tl3_id = '$linkId1'");
        //$items = array();
        while($fetcgetevent1 = mysql_fetch_array($getevent1)){
        $items .= date('d-F', strtotime($fetcgetevent1['date'])).',';
        }

        $event_date = substr($items, 0, -1);

        $event_dates = explode(',', $event_date);

        $Event_count = substr_count($event_date  , ',');

        // for($z = 0; $z <= $Event_count; $z++){
        //      echo $event_dates[$z].'
';
        // }

JavaScript
// fill the month table with column headings
function day_title(day_name){
    document.write(""+day_name+"	")
}
// fills the month table with numbers

function fill_table(month,month_length)
{

    day=1
    // begin the new month table
    document.write("

"+month+"   "+year+"
")
    document.write("

")

    // column headings
    day_title("S")
    day_title("M")
    day_title("T")
    day_title("W")
    day_title("T")
    day_title("F")
    day_title("S")
    // pad cells before first day of month
    document.write("

")
    for (var i=1;i<start_day;i++){
        document.write("")
    }
    // fill the first week of days
    for (var i=start_day;i<8;i++){
        document.write(""+day+"	")
        day++
    }
    document.write("
")
    // fill the remaining weeks
    while (day <= month_length) {
        for (var i=1;i<=7 && day<=month_length;i++){
            var getcurrentmonth= $('#hiddenmonth').val();
            var getcurrentdate=$('#hiddendate').val();
            if(getcurrentmonth === month)
            {
                if(getcurrentdate == day )
                {

                    document.write(""+day+"	")
                }
                else
                {

                    document.write(""+day+"	")
                }
            }
            else
            {
                document.write(""+day+"	")
            }

            day++
        }
        document.write("

")
        // the first day of the next month
        start_day=i
    }
    document.write("

")
}
// end hiding -->

// CAHNGE the below variable to the CURRENT YEAR
var d = new Date();
var n = d.getFullYear();

var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";

var mm = month[d.getMonth()];

var dd=d.getDate();
today = mm+'/'+dd+'/'+n;

year=n

var leap = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
var add = 0;
if(leap == true ){
    add = 1;
}
//alert(add);

$('#hiddenmonth').val(mm);
$('#hiddendate').val(dd);
// first day of the week of the new year
today= new Date("January 1, "+year)
start_day = today.getDay() + 1   // starts with 0
fill_table("January",31)
fill_table("February",28+add)
fill_table("March",31)
fill_table("April",30)
fill_table("May",31)
fill_table("June",30)
fill_table("July",31)
fill_table("August",31)
fill_table("September",30)
fill_table("October",31)
fill_table("November",30)
fill_table("December",31)

I have used a query to fetch data from the database. I don't know how to proceed to the next step. I only want to use this script to achieve this, I don't want to use jQuery.


text:
Q: TypeError: Cannot read property 'forEach' of undefined 'react_devtools_backend.js:2574' I am getting this error is production for react web application. me not able to find the issue can someone please help me. me getting the blank page as result. but if i reload the page then it works fine.
Below I am sharing the error page also.

Router.jsx
function Router() {
  const {systemResourceIds, userPageAccess} = useSelector(state=> state?.getUser);
  const systemResources = userPageAccess?.systemResources ;
  let setSystemResourceIdObject = systemResourceIds;
  let routes =(setSystemResourceIdObject)? createRoute(setSystemResourceIdObject):setSystemResourceIdObject;
  let defaultRoute = '';
  const componentIdMapping = {
    "SR-001":ExecutiveDashBoard,
    "SR-008":Admin,
    "SR-002":ProjectList,
    "SR-007":FileUpload,
    "SR-003":ProjectProfile,
    "SR-0013":UserRoleAssignment,
    "help":Help,
    "SR-0021":MonitoringList,
    "SR-0022":CreateMonitoringList
  };

  (routes) && routes?.forEach(route=>{
    if(componentIdMapping[route.id]){
      route["component"]=componentIdMapping[route.id];
    }
  });

  if (systemResources && systemResources.length > 0) {
    if (typeof setSystemResourceIdObject !=="undefined" && setSystemResourceIdObject["SR-001"]) {
      defaultRoute = '/executivedashboard';
    } else if (typeof setSystemResourceIdObject !=="undefined" && setSystemResourceIdObject["SR-002"]) {
      defaultRoute = '/projectlist';
    } else if (typeof setSystemResourceIdObject !=="undefined" && (setSystemResourceIdObject["SR-007"])) {
      defaultRoute = '/fileupload';
    } else if (typeof setSystemResourceIdObject !=="undefined" && setSystemResourceIdObject["SR-008"]) {
      defaultRoute = '/admin';
    }
  }
  const generalAccess = () => {
    return (
      <Switch>
        <Route exact strict path="/" render={() => <Redirect to={defaultRoute} />} />
        {
          (routes) && routes.map(route=>(route.access) ?
            <Route key = {route.id} exact strict path ={route.link} component={route.component}/>
           :
            <Route key = {route.id} exact strict path ={route.link} render={() => <Error statusCode={403} /> } />
          )
        }
        <Route exact strict path="/monitoringlist/project/:id" component = {MoninoringListProjects} />
        <Route exact strict path="/monitoringlist/edit/:id" component = {EditMonitoringList} />
        <Route exact strict path="/monitoringlist/report/:id" component = {MoninoringListProjects} />
        <Route exact strict path="/monitoringlist/addprojects/:id" component = {AddProjects} />
        <Route exact strict path="/monitoringlist/projectdetails/:id/:key" component = {MLProjectDetailsInfo} />
        <Route path="*" render={() => <Error statusCode={400}/>}/>
      </Switch>
    );
  };

  return generalAccess();
}

export default Router;


text:
Q: how to handle errors of error handling system? I've been working on developing a java web service. In this project I have an error handling system. My problem is what to do if the error handling system itself throws an exception(e.g. FileNotFoundExcption for the log file). Should it be swallowed? or Should it be sent to user or something else.
_new information_________
In my older prjects when ever an exception is thrown. 1-system catch the exception. 2a- system return an appropriate message to the user. 2b- System logs the exception with it's whole stack trace.this way the end user can inform the admin and admin sends me the error log. my question is what if the system can't log the exception. in the past i would have send a second message to the user to inform the system admin about this. I'm wondering if this is the right choice.

Any kind of information is appreciated.

A: It depends.
To catch or throw an exception, it all depends on the context in which exception occurs.
To answer your question If there is something that can be done with an exception, go ahead.