text:
Q: OpenCV 'NoneType' object has no attribute 'shape' I am trying to get this to work: https://circuitdigest.com/tutorial/real-life-object-detection-using-opencv-python-detecting-objects-in-live-video (scroll to the 'Object detection using ORB' part)
`
import cv2
import numpy as np

def ORB_detector(new_image, image_template):
    # Function that compares input image to template
    # It then returns the number of ORB matches between them
    image1 = cv2.cvtColor(new_image, cv2.COLOR_BGR2GRAY)

    # Create ORB detector with 1000 keypoints with a scaling pyramid factor of 1.2
    orb = cv2.ORB_create(1000, 1.2)

    # Detect keypoints of original image
    (kp1, des1) = orb.detectAndCompute(image1, None)

    # Detect keypoints of rotated image
    (kp2, des2) = orb.detectAndCompute(image_template, None)

    # Create matcher
    # Note we're no longer using Flannbased matching
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
    # Do matching
    matches = bf.match(des1,des2)

    # Sort the matches based on distance.  Least distance
    # is better
    matches = sorted(matches, key=lambda val: val.distance)
    return len(matches)

cap = cv2.VideoCapture(0)

# Load our image template, this is our reference image
image_template = cv2.imread("phone.jpg", 0)
# image_template = cv2.imread('images/kitkat.jpg', 0)

while True:
    # Get webcam images
    ret, frame = cap.read()

    # Get height and width of webcam frame
    height, width = frame.shape[:2]

    # Define ROI Box Dimensions (Note some of these things should be outside the loop)
    top_left_x = int(width / 3)
    top_left_y = int((height / 2) + (height / 4))
    bottom_right_x = int((width / 3) * 2)
    bottom_right_y = int((height / 2) - (height / 4))

    # Draw rectangular window for our region of interest
    cv2.rectangle(frame, (top_left_x,top_left_y), (bottom_right_x,bottom_right_y), 255, 3)

    # Crop window of observation we defined above
    cropped = frame[bottom_right_y:top_left_y , top_left_x:bottom_right_x]

    # Flip frame orientation horizontally
    frame = cv2.flip(frame,1)

    # Get number of ORB matches
    matches = ORB_detector(cropped, image_template)

    # Display status string showing the current no. of matches
    output_string = "Matches = " + str(matches)
    cv2.putText(frame, output_string, (50,450), cv2.FONT_HERSHEY_COMPLEX, 2, (250,0,150), 2)

    # Our threshold to indicate object deteciton
    # For new images or lightening conditions you may need to experiment a bit
    # Note: The ORB detector to get the top 1000 matches, 350 is essentially a min 35% match
    threshold = 250

    # If matches exceed our threshold then object has been detected
    if matches > threshold:
        cv2.rectangle(frame, (top_left_x,top_left_y), (bottom_right_x,bottom_right_y), (0,255,0), 3)
        cv2.putText(frame,'Object Found',(50,50), cv2.FONT_HERSHEY_COMPLEX, 2 ,(0,255,0), 2)

    cv2.imshow('Object Detector using ORB', frame)
    if cv2.waitKey(1) == 13: #13 is the Enter Key
        break

cap.release()
cv2.destroyAllWindows()

`
For some reason I am getting an error on the line 41 at 'height, width = frame.shape[:2]' and I cannot get it to work (the error is the title), I have tried fixing the image path and that has not worked. I am running this in Jupyter Lab.
I tried fixing the image path and checking if its .shape works (so image_template.shape), this is what many other stackoverflows told.

A: Your read is not returning a frame. The following code:
cap = cv2.VideoCapture(0)
ret, frame = cap.read()

should check if you actually managed to read a frame. cap.read() will return False if it failed, so you need to:
if not ret:
    print("Couldn't read a frame!")
    ... do something to handle this failure

Because the read failed, frame is None, so when you call frame.shape, python complains that the 'NoneType' object has no attribute 'shape'


text:
Q: Swift - How to do a custom slide animation? I've been looking for swift code to make simple custom slide transitions between views (just left to right or right to left, without bounce) but I only found code for complicated animations. Thanks everyone for your help !
Oscar

A: What you need to do is subclass UIStoryboardSegue Class and override the perform method.
The code inside your perform method would be something like this
    var ourOriginViewController = self.sourceViewController as! UIViewController

    ourOriginViewController.navigationController?.pushViewController(self.destinationViewController as! UIViewController, animated: false)
    var transitionView = ourOriginViewController.navigationController?.view

    UIView.transitionWithView(transitionView!, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromRight, animations: { () -> Void in

    }) { (success) -> Void in

    }

Assign this segue class to your custom segue in storyboard
Attaching screenshot for reference

A: I finally found the answer here : http://mathewsanders.com/animated-transitions-in-swift/#custom-transition-animations and adpated it a little bit.
1) Create this Swift NSObject file
class TransitionManager2: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate  {

    private var presenting = true
    // MARK: UIViewControllerAnimatedTransitioning protocol methods

    // animate a change from one viewcontroller to another
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {

        // get reference to our fromView, toView and the container view that we should perform the transition in
        let container = transitionContext.containerView()
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!

        // set up from 2D transforms that we'll use in the animation
        let offScreenRight = CGAffineTransformMakeTranslation(container.frame.width, 0)
        let offScreenLeft = CGAffineTransformMakeTranslation(-container.frame.width, 0)

        // prepare the toView for the animation
        toView.transform = self.presenting ? offScreenRight : offScreenLeft

        // set the anchor point so that rotations happen from the top-left corner
        toView.layer.anchorPoint = CGPoint(x:0, y:0)
        fromView.layer.anchorPoint = CGPoint(x:0, y:0)

        // updating the anchor point also moves the position to we have to move the center position to the top-left to compensate
        toView.layer.position = CGPoint(x:0, y:0)
        fromView.layer.position = CGPoint(x:0, y:0)

        // add the both views to our view controller
        container.addSubview(toView)
        container.addSubview(fromView)

        // get the duration of the animation
        // DON'T just type '0.5s' -- the reason why won't make sense until the next post
        // but for now it's important to just follow this approach
        let duration = self.transitionDuration(transitionContext)

        // perform the animation!
        // for this example, just slid both fromView and toView to the left at the same time
        // meaning fromView is pushed off the screen and toView slides into view
        // we also use the block animation usingSpringWithDamping for a little bounce
        UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: nil, animations: {

            // slide fromView off either the left or right edge of the screen
            // depending if we're presenting or dismissing this view
            fromView.transform = self.presenting ? offScreenLeft : offScreenRight
            toView.transform = CGAffineTransformIdentity

            }, completion: { finished in

                // tell our transitionContext object that we've finished animating
                transitionContext.completeTransition(true)

        })

    }

    // return how many seconds the transiton animation will take
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.4
    }

    // MARK: UIViewControllerTransitioningDelegate protocol methods

    // return the animataor when presenting a viewcontroller
    // remmeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // these methods are the perfect place to set our `presenting` flag to either true or false - voila!
        self.presenting = true
        return self
    }
    // return the animator used when dismissing from a viewcontroller
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.presenting = false
        return self
        }
    }

2) Change the segue between the 2 ViewControllers to "Custom"
3) Add in the first ViewController this code :
let transitionManager = TransitionManager2()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // this gets a reference to the screen that we're about to transition to
    let toViewController = segue.destinationViewController as! UIViewController

    // instead of using the default transition animation, we'll ask
    // the segue to use our custom TransitionManager object to manage the transition animation
    toViewController.transitioningDelegate = self.transitionManager

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plotting a few Maclaurin Series in Mathematica I would like to plot the Taylor polynomials for several functions. Specifically:
Exp[Sin[x]]
( x^2 + Exp[ x ] )^( -1 )

and
Exp[ -4 x^2 + 5 x]

I have their Taylor series as:
taylorFunction1[x_, n_] := Normal[Series[f1[x], { x, 0, n} ] ]
taylorFunction2[x_, n_] := Normal[Series[f2[x], {x,  0, n} ] ]
taylorFunction3[x_, n_] := Normal[Series[f3[x], {x,  0, n} ] ]

I would like to plot the functions of x and their Taylor series of degree n = 10 and compare each, specifically over the interval [-1/2, 1/2]. However, for some reason, whenever I use the "Plot[]" command, Mathematica just returns an empty graph. I come from a C programming background, but I am rather unfamiliar with Mathematica. Can anyone help me out and let me know what's going on?
Thanks!

A: Here's one way:
Plot[
 Evaluate@Normal@Series[{Exp[Sin[x]], (x^2 + Exp[x])^(-1), Exp[-4 x^2 + 5 x]}, {x, 0, 5}],
 {x, -1/2, 1/2}]


text:
Q: How to get header HTML code included in all .html files I have a simple website, in which I've written the code that's about the header.
This is included in the index.html. Now that I want to add another .html file, how can I have the header related code, included into all the HTML files?
A simple copy paste will surely do the job, but is it a correct solution?
Developing in Ubuntu, using Sublime Text with H5BP and Compass.

A: I would use PHP:
// header.php
<?php
date_default_timezone_set('America/Los_Angeles');
function https(){
  $sv = $_SERVER;
  if(!isset($sv['HTTPS'])){
    header("LOCATION:https://{$sv['SERVER_NAME']}{$sv['PHP_SELF']}"); die();
  }
}
function http(){
  $sv = $_SERVER;
  if(isset($sv['HTTPS'])){
    unset($_SERVER['HTTPS']);
    header("LOCATION:http://{$sv['SERVER_NAME']}{$sv['PHP_SELF']}"); die();
  }
}
$doc = "<!DOCTYPE html>

      <meta http-equiv='content-type' content='text/html;charset=utf-8' />
      <meta name='keywords' content='put your site keywords here' />";
$main = "

        Home
        Page 2
        Page 3
        Page 4
        Page 5
        Page 6
        Page 7

";
 ?>

Now, put header.php in a restricted folder, in the same location as index.html for added security, then change index.html to index.php. Now index.php:
// index.php
<?php
include_once 'restricted/header.php'; http(); // could be https() for SSL
echo "$doc
    <title>Whatever - Home</title>
    <meta name='description' content='Whatever - Home' />

$main";
?>

A: You could also ajax to load in the header into the separate pages, if you didn't want to deal with php.  Just have the header html in a separate file and do an ajax call on dom load and then apply the response to the container of the header in the page you are using.


text:
Q: Improper integrals: is it possible to have a non bounded function such that its improper integral converges? Find an example of a non-negative function $(f\geq 0)$ which is continuous and such that $\int_{0}^{\infty}f(x)dx$ is finite ($\int f < \infty$) but $\lim_{x\rightarrow\infty}f(x)$ does not exist.
Also, is it possible that $\int_{0}^{\infty}f(x)\,dx$ exist but $f(x)$ is not bounded?

A: Hint:
Let the graph of $f$ consist of a sequence of disjoint isosceles triangles of height $n$ and base length $\frac{1}{n 2^{n}}$. The area of the $n$-th triangle is $$\frac{1}2 \cdot n \cdot \frac{1}{n2^{n}} = \frac{1}{2^{n+1}}$$
so the integral is $$\int_0^\infty f(x)\,dx = \sum_{n=1}^\infty \frac{1}{2^{n+1}} = \frac12 <+\infty$$
However, $f$ is clearly unbounded. Also $\lim_{n\to\infty} f(x)$ does not exist.

A: $$ f(x) = \sum_{n\geq 1} n e^{-n^6(x-n)^2} $$
is a continuous and non-negative function, which is unbounded over $\mathbb{R}^+$ (since $f(n)\geq n$) and such that
$$ \int_{\mathbb{R}^+}f(x)\,dx \leq \int_{\mathbb{R}}f(x)\,dx = \sum_{n\geq 1}\frac{\sqrt{\pi}}{n^2} = \frac{\pi^{5/2}}{6} < +\infty. $$
$\hspace1in$

A: Define a non-negative continuous and unbounded function $f$ such that $\int_{k}^{k+m}f(x)\, dx=\frac1{k^\alpha}$ for $k,m\in\Bbb N$, then you will had that
$$\int_0^\infty f(x)\, dx=\sum_{k=1}^\infty\frac1{k^\alpha}<\infty,\quad\text{when }\alpha>1$$
By example the non-negative and unbounded continuous function defined by
$$f(x):=\begin{cases}(k+1)(x-k)^{(k+1)^3},&x\in[k,k+1],\,k\text{ non-negative and even}\\k(k+1-x)^{k^3},&x\in[k,k+1],\,k\text{ non-negative and odd}\end{cases}$$
Then we found that
$$\int_k^{k+2}f(x)\, dx=2(k+1)\int_0^1 x^{(k+1)^3}\, dx=2\frac{k+1}{(k+1)^3+1}$$
Hence
$$0\le\int_0^\infty f(x)\, dx=2\sum_{k=0}^\infty\frac{k+1}{(k+1)^3+1}<\infty$$


text:
Q: Animate while UIScrollView bounces I want to do a little animation every time the UIScrollView bounces, to be exact, I want a button to move a little bit to the left and then back to it's original position. I use the scrollViewDidScroll method and check if the scrollView's contentOffset is higher than the actual content height and then call the animation. The problem is that the animation is called multiple times during the bounce if I do it like that. Is there a way to only call it once?

A: Have an ivar or property named something like animationActive that will keep track of animation. When you start it, set animationActive = YES; and when animation completes, set animationActive = NO;. And of course, before you start animation, check if (animationActive == YES).


text:
Q: Dynamic memory Deallocation in QT How does the dynamically allocated pointers in QT coding are destroyed because we don't write a specific destructor for them?

A: To expand on Neox's answer, Qt has two methods for object management:

*

*QObject tree structure

*Managed pointer classes

And the two don't really mix very well for reasons which will become apparent.
QObjects can either be 'free' or have a parent. When a QObject has its parent set (either by providing the QObject constructor with a pointer to another QObject, or by calling setParent()) the parent QObject becomes the owner of the child QObject and will make sure any of its children are destroyed when it is. There are also several methods available to inspect child/parent relationships.
A separate method of managing dynamically allocated objects are the managed pointer classes which this paper explains quite well. To summarise though:

*

*"The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction" and is therefore good when you need objects which have clear and obvious ownership and lifetime.

*"The QSharedPointer class holds a strong reference to a shared pointer [and] will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it" and is therefore good when ownership is not as clear cut, but you want to make sure it doesn't get lost and become a memory leak. QWeakPointer can be used to share the pointer without implying any ownership.

As you can see, some of the guarded pointer classes can be used with a QObject tree, but you should make sure you read and understand the documentation thoroughly before doing so or you may end up with a corrupt data structure.

A: The short answer is:

QObjects organize themselves in object trees. When you create a QObject with another object as parent, it's added to the parent's children() list, and is deleted when the parent is.

Qt has a good docu about object hierarchy and ownership within the framework. You can read it here


text:
Q: Advantage of log4j What's the advantage of log4j over set System.out and System.err to output to a log file?

A: Actually, you should look into the slf4j facade these days, as it allows you to use {}-placeholders for the most concise statements.  You can then use the appropriate logging framework behind slf4j to handle the actual treatment of your log statements.  This could be log4j or the slf4j-simple which just prints out all of INFO, WARN and ERROR, and discards the rest.
The crucial observation you need to make is that the WRITING of log statements is done when the code is written, and the DECISION of what is needed is done when the code is deployed, which may be years after the code was written and tested.  System.out.println requires you to physically change your code to get rid of them, which is unacceptable in a rigid write-test-deploy cycle.  IF the code changes, it must be retested.  With slf4j you just enable those you want to see.
We have full logging in the test phase, and rather verbose logging in the initial period of a production deployment, after which we go down to information only.  This gives us full information in a scenario where debugging a case is very rarely possible.
You might find this article I wrote interesting.  The target audience is beginning Java programmers, with my intention of giving them good habits from the start.  http://runjva.appspot.com/logging101/index.html

A: At a high level, the win from Log4j over manual logging is that you can decouple your logging code from what you actually want to log and where and how you want to log it.  Details about logging verbosity/filtering, formatting, log location, and even log type (files, network, etc.) are handled declaratively using configuration and extensibly via custom appenders, rather you having to code that flexibility yourself.
This is critically important because it's often hard for developers to predict how logging needs will change once their software is in production. Operations teams managing that software may need less verbose logs, may need mulitple logs, may need to ship those logs to multiple servers, may need to sometimes get really verbose data for troubleshooting, etc.   And it's usually impossible for operations teams, if they need to change how logging works, to convince the developer to make big code changes.  This often leads to production downtime, friction between operations and development, and wasted time all around.
From the developer's point of view, Log4j insulates you from having to make code changes to support logging, and insulates you from being pestered by people who want logging changes. It enables people managing your code to scratch their own itch rather than bugging you!
Also, since Log4j is the de-facto standard for Java logging, there are lots of tools available which can do cool things with Log4j-- furthermore preventing you and your operations teams from re-inventing the wheel.
My favorite feature is the ability to easily write appenders send data to non-file sources, like SYSLOG, Splunk, etc. which makes it easy to your app's custom logging into operations management tools your IT department is already using.

A: my favorites (not all)

*

*Ability to set parameters of logging in config, without recompiling

*Ability to set the way log is written (from text file to SMTP sender)

*Ability to filter by severity

A: Levels, formatting, logging to multiple files... A logging framework (even if it's java.util.logging) is really beneficial if there's a chance anything may go wrong while your code is running.

A: Log4j offers the ability to rotate your log files based on size and delete them based on quantity (logrotate), so your servers don't fill up their disks.  Personally I think that is one of the more valuable features in Log4j.
Also Log4j is popular and understood by many developers.  The last three companies I've worked at have all used Log4j in most projects.

A: log4j allows you to log to various resources e.g. event log, email, file system etc while allowing your application to remain decoupled from all of these resources. Furthermore, you get to use a common interface to log to all of the various resources without having to learn or integrate thier corresponding APIs.

A: Take a look and you will understand the power of log4j :
log4j.properties I used once for a project :
# ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF

# No appenders for rootLogger
log4j.rootLogger=OFF

folder=..
prefix=
fileExtension=.log
htmlExtension=${fileExtension}.html
datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
layout=%d{${datestamp}} ms=%-4r [%t] %-5p %l %n%m %n%n

# myLogger logger
log4j.logger.myLogger=ALL, stdout, infoFile, infoHtml, errorFile

# stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=${layout}
# infoFile
log4j.appender.infoFile=org.apache.log4j.FileAppender
log4j.appender.infoFile.File=${folder}/${prefix}_info${fileExtension}
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=${layout}
# infoHtml
log4j.appender.infoHtml=org.apache.log4j.FileAppender
log4j.appender.infoHtml.File=${folder}/${prefix}_info${htmlExtension}
log4j.appender.infoHtml.layout=org.apache.log4j.HTMLLayout
log4j.appender.infoHtml.layout.Title=Logs
log4j.appender.infoHtml.layout.LocationInfo=true
# errorFile
log4j.appender.errorFile=org.apache.log4j.FileAppender
log4j.appender.errorFile.File=${folder}/${prefix}_error${fileExtension}
log4j.appender.errorFile.layout=org.apache.log4j.PatternLayout
log4j.appender.errorFile.layout.ConversionPattern=${layout}

# APPENDERS SETTINGS
log4j.appender.stdout.Threshold = ALL
log4j.appender.infoFile.Threshold = INFO
log4j.appender.infoHtml.Threshold = INFO
log4j.appender.errorFile.Threshold = WARN.

To change the variables in your java code you can do :

Loading Configuration
Log4j will automatically load the configuration if it is stored in a
  file called "log4j.properties" and is present on the classpath under
  "" (e.g. WEB-INF/classes/log4j.properties).
I don't like that approach and prefer to load the configuration
  explicitly by calling:
PropertyConfigurator.configure( Config.ETC + "/log4j.properties" );
  This way I can reload the configuration at any time as long as my
  application is still running. I like to add a button to an
  administrative jsp, "Reload Log4J".
Dynamic Log File Location
Many people complain that Log4j forces you to hard-code the location
  where your logs will be kept. Actually, it is possible to dynamically
  choose the log-file location, especially if you use the ${log.dir}
  property substitution technique above. Here's how:

String dynamicLog = // log directory somehow chosen...
Properties p = new Properties( Config.ETC + "/log4j.properties" );
p.put( "log.dir", dynamicLog ); // overwrite "log.dir"
PropertyConfigurator.configure( p );

A: *

*logging (Document historical business events that occur, you can check old logs)

*track the application (project flow)

*debugging the application (Detailed information what occurs in a method at granular level //data, value and all inside methods)

*error handling (information about specific error that occur)


text:
Q: JavaScript Frames Manipulation I have a piece of javascript with Phonegap application which works nice on iPhone but on Android it doesn't work.
var js = "var c = frames.content;";

js += "if (c.document.readyState == 'complete') {";

js += "var l = c.document.getElementsByName('login')[1];";

js += "var u = c.document.getElementById('user_id');";
js += "var p = c.document.getElementById('password');";

js += "if (u && p) {";

js += "u.value = '" + getData("username") + "';";
js += "p.value = '" + getData("password") + "';";

js += "l.click();";

js += "}";

js += "}";

The Android browser says there is frames object which is of type DOMWindow but there is no child frame named content. What I am doing wrong?
UPDATED
I solved it. I wasn't executing the JavaScript in the right WebView.


text:
Q: How do I find out whether a Python module is run on GAE? I have a module that uses lxml. Since this cannot be imported on GAE, I'd like to use a suitable substitute by default. Something along the lines of:
if not ON_GAE:
    import lxml
else:
    import beautifulsoup

How can I determine that I'm on GAE? Is there a OS variable of some sorts?
Update: There are certain modules that will not run on GAE (like sockets). Rather than having multiple blocks of try ... except ImportError, I'd like to know from the start which code blocks needs an alternative implementation.

A: You can use this:
on_app_engine = os.environ.get('SERVER_SOFTWARE', '').startswith('Google')
Then something like:
if on_app_engine:
  import lxml
else:
  import bla

A: You can simply try and see if an import throws an exception and use the other import only if it's necessary.
try:
    import lxml
except ImportError:
    import beautifulsoup


text:
Q: NHibernate fetchmany duplicated values repository pattern I have a problem with duplicated results in list for my query.
What I have is two FetchMany on a method for my repository:
    public IQueryable<MyEntity> Query()
    {
        return Session.Query<MyEntity>()
            .FetchMany(x => x.ListA)
            .FetchMany(x => x.ListB);
    }

Query:
var result = _myEntityRepository
    .Query()
    .Where(x => names.Contains(x.Name))
    .Where(x => x.ListA.Any(m => listAIds.Contains(m.Id)))
    .Where(x => x.ListB.Any(m => listBIds.Contains(m.Id)))
    .OrderBy(x => x.CreationDate)
    .ToList();

Mapping:
        HasManyToMany(x => x.ListA)
            .Table("MY_ENTITY_TYPE_A")
            .ParentKeyColumn("MYENTITY_ID")
            .ChildKeyColumn("MYENTITYA_ID")
            .Fetch.Join();

ListA is class MyEntityA with several properties.
ListB is class MyEntityB with several properties.
The SQL produced is good and gets the values I need, how ever the values added to ListA and ListB gets duplicated several times. ListA and ListB are seperate tables (many to many).
I use fluent-nhibernate.
I looked up using ToFuture but that only gave me Method Not Implemented Exception and I don't want to use NHibernate outside my repository.
Here is what I tried:
    public IQueryable<MyEntity> Query()
    {
        var query = Session.Query<MyEntity>();

        Session.Query<MyEntity>().FetchMany(x => x.ListA).ToFuture();
        Session.Query<MyEntity>().FetchMany(x => x.ListB).ToFuture();

        return query;
    }

Exception is thrown at:
        Session.Query<MyEntity>().FetchMany(x => x.ListA).ToFuture();

TargetInvocationException is thrown with inner exception "The method or operation is not implemented."
Stack trace:
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at NHibernate.Linq.DefaultQueryProvider.ExecuteFutureQuery(NhLinqExpression nhLinqExpression, IQuery query, NhLinqExpression nhQuery)
   at NHibernate.Linq.DefaultQueryProvider.ExecuteFuture(Expression expression)
   at NHibernate.Linq.LinqExtensionMethods.ToFuture[T](IQueryable`1 query)

How can accomplish this? At the moment I do Disctint on ListA and ListB, but it seems to be slower and not so nice with all the duplicated values in the entities created.
MyEntity has many items of EntityA in ListA and many items of EntityB in ListB, but there are no duplicates in the database.
Note: I have to use FetchMany for both, else there will be too many select queries!

A: Getting ToFuture to work will be important.  x.ListA X x.ListB is a Cartesian product.   ToFuture should work.  Can you provide more details on your attempt at using it?
Ignoring the Cartesian product, you can get your current approach to work by using <set/> instead of <bag/> when mapping ListA and ListB.  This tells NHibernate that the collections should not contain duplicates.  Normally this wouldn't be necessary, but including both ListA and ListB in the same query is creating the duplicate results.  <set/> should fix this.


text:
Q: Dependencies In Same Reactor I have a very simple Tycho reactor with two modules: one is a standard Maven project with this addition to make it a bundle:
<plugin>
    <groupId>org.apache.felix</groupId>
    <artifactId>maven-bundle-plugin</artifactId>
    <extensions>true</extensions>
    <executions>
        <execution>
            <id>default-bundle</id>
            <phase>package</phase>
            <goals>
                <goal>bundle</goal>
            </goals>
            <configuration>
                <instructions>
                    <Export-Package>org.acme.jar</Export-Package>
                </instructions>
                <manifestLocation>META-INF</manifestLocation>
            </configuration>
        </execution>
    </executions>
</plugin>

The second is a Tycho project that has a dependency to the above JAR in the MANIFEST.MF.
If I start the build, I get the following exception:
[ERROR] Cannot resolve project dependencies:
[ERROR]   Software being installed: plugin 0.0.1.qualifier
[ERROR]   Missing requirement: plugin 0.0.1.qualifier requires 'bundle org.acme.jar 0.0.1' but it could not be found

Which is really weird, because the bundle is in the same reactor.
But no worries, I can just add the Maven dependency, too:
<!-- parent pom.xml -->
<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>target-platform-configuration</artifactId>
    <version>0.26.0</version>
    <configuration>
        <pomDependencies>consider</pomDependencies>
    </configuration>
</plugin>

<!-- plug-in pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.acme</groupId>
        <artifactId>jar</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

Still I get the same exception, which is weird because the documentation claims: Maven resolves the GAV dependencies according to the normal Maven rules.
That's just not true. Evidently org.acme.jar doesn't get resolved. Or maybe Tycho fails to see that it's a bundle.
The JAR module is an API project used for server side components, and we want to drop SWT / Tycho in the long run, so it's not an option to make org.acme.jar an Eclipse plug-in.
How do I define dependencies in the same reactor for Tycho?

A: I'm afraid that what you ask for is currently not possible. The Tycho Wiki documents this limitation in the dependency on pom-first artifacts HOW-TO.
That being said, if you really want your whole build (maven-bundle-plugin and Tycho parts) to run with a single mvn clean install, then using the maven-invoker-plugin at the end of the "plain Maven" build to fork a "Tycho build" should work. It's a rather cumbersome workaround, however (example on Github).


text:
Q: Oracle AQ delete and re-create Agent when dequeue hangs I have this weird problem in Oracle 11g.
I have an advanced queue, XALOTUPUT_Q, and an subscriber agent 'lasernet'. When I have been debugging from my .net code the agent seems to stop working and i then have to delete and create the angent and then i can dequeue again.
Has anybody had the same problem and how did you fix it?
Agent pl/sql code
DECLARE
   /* Add subscribers lasernet to the suscriber list: */
   subscriber          sys.aq$_agent;
BEGIN
   subscriber := sys.aq$_agent ('lasernet', 'XALOUTPUT_Q', 0);
   DBMS_AQADM.ADD_SUBSCRIBER(
   queue_name => 'XAL_SUPERVISOR.XALOUTPUT_Q',
   subscriber => subscriber,
   RULE => 'tab.user_data.beskedtype = ''lasernet''' ,
   TRANSFORMATION => null,
   QUEUE_TO_QUEUE => false,
   DELIVERY_MODE => 3);-- persistens or buffered
END;

DECLARE
   /* Remove subscribers from the subscriber list: */
   subscriber          sys.aq$_agent;
BEGIN
    subscriber := sys.aq$_agent ('lasernet', null, null);
   DBMS_AQADM.remove_SUBSCRIBER(
   queue_name => 'XAL_SUPERVISOR.XALOUTPUT_Q',
   subscriber => subscriber);
END;

my .net code  it is placed in a thread task and are running as a win service
 public bool Listen()
        {
            var conListen = new OracleConnection(_constr);
            conListen.Open();
            XALOUTPUT_T queueItem = null;
            var threadNumber = CountThread(SUBSCRIBER_1);
            Console.WriteLine("TestListen()");
            OracleAQQueue queueListen = new OracleAQQueue("XALOUTPUT_Q", conListen);
            string subscriber = "lasernet";
            var listenConsumers = new string[2] { subscriber, "vau_mail" };

            try
            {
                queueListen.MessageType = OracleAQMessageType.Udt;
                queueListen.UdtTypeName = "XALOUTPUT_T";
                queueListen.DequeueOptions.ConsumerName = subscriber.ToUpper();
                queueListen.DequeueOptions.DeliveryMode = OracleAQMessageDeliveryMode.PersistentOrBuffered;
                queueListen.DequeueOptions.Visibility = OracleAQVisibilityMode.Immediate;
                queueListen.DequeueOptions.Wait = 5;

                var consumer = queueListen.Listen(listenConsumers, 5);

                if (consumer.ToUpper() == "LASERNET")
                {
                    Console.WriteLine("[Listen Thread] Listen returned... Dequeuing...");
                    OracleAQMessage deqMsg = queueListen.Dequeue(queueListen.DequeueOptions);
                    XALOUTPUT_T result = (XALOUTPUT_T)deqMsg.Payload;
                    try
                    {
                        if (deqMsg != null && deqMsg.Payload is XALOUTPUT_T queuePayload)
                            queueItem = queuePayload;
                        var operation = SendDataToLasernet(queueItem, threadNumber).GetAwaiter().GetResult();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        queueListen.Dispose();
                    }
                }
                else
                    Console.WriteLine("Consumer not found...");
            }
            catch (Exception e)
            {
                Console.WriteLine(" .net - Error: {0}", e.Message);
                queueListen.Dispose();
                conListen.Close();
                Listen();
            }
            finally
            {
                queueListen.Dispose();
                conListen.Close();
                Listen();
            }
            return true;
        }


text:
Q: Styling mat-option with Active and Hover - Angular Materials I can't find a CSS solution for changing the text color of the option that is active. Also for the option being hovered. I'm having trouble finding any documentation on styling angular materials in CSS.
One thing I don't understand is I'm using
.mat-option.mat-selected {
  background: red;
  color:black;
}

and the background is red on the last selected item, but it also has white text color instead of black.
I need it to have black text and as I hover over an option, it should have a white background.
This is the mat-option I'm trying to style
<mat-form-field class="example-full-width" appearance="outline">
         <mat-label id="placeholder">Find User</mat-label>
       <input type="text" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto"  type="text" name="userName" required minlength="3">
              <mat-autocomplete #auto="matAutocomplete" name="userName">
         <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
           {{option}}

         </mat-option>
       </mat-autocomplete>
   <!-- {{myControl.value}} -->

     </mat-form-field>```

A: mat-list-option has mat-option.mat-active class when it's active and mat-option.mat-selected when selected.
Please add the following CSS to your stylesheet:
.mat-option.mat-active {
  background: red !important;
}

The following could be used to style hovering:
.mat-option:hover:not(.mat-option-disabled)

A: All material ui style css are from node_modules.
So you can customize material css as follows.
1) The best way is to change node_module css file.
   If you want to change mat-select hover style, first of all, you have to find css file.
     If you installed indigo-pink theme, you can find this css file.
node_modules/@angular/material/prebuilt-themes/indigo-pink.css

And class is .mat-option:focus:not(.mat-option-disabled)
ex: .mat-option:focus:not(.mat-option-disabled){background:#3f51b5;color:white}
2) If you don't want to change module css, you have to insert customize css style to last
   css file of angular.json styles.
angular.json
   "styles": [
      "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
      "src/styles.scss"
   ],

last css file is styles.scss, so you should insert your style on it.
   But customize css styles has to be end with "!important"
3) In the case of using customize angular material theme, you can find this file.
./node_modules/@angular/material/_theming.scss

Change the css on this file like this.
  .mat-option {
    color: mat-color($foreground, text);
&:hover:not(.mat-option-disabled),
&:focus:not(.mat-option-disabled) {
  background: #607d8b;
  color: white
}


text:
Q: "Not speaking" vs. "not having spoken."
His tongue was stiff, the consequence of not speaking/not having
spoken in a whole year.

Does the meaning change a lot if you choose one option or the other? Or maybe adding having is superfluous in this sentence?

A: If you want to use not speaking, you will need to follow it with a different adverbial phrase, like so:

His tongue was stiff, the consequence of not speaking for a whole year.

The difference is that in would mean "sometime during" while for gives the sense "for the entire duration."

His tongue was stiff, the consequence of not having spoken in a whole year.

In this case, in is acceptable, because not having spoken gives the reader the understanding that the act of not speaking was a constant in the past, and the temporally inclusive sense of for is not needed. The writer could, however, in this case choose to use for as well without changing the meaning.

A: The choice of not speaking and not having spoken depends on the context and construction of the sentence.
Not speaking has no tense, like not smoking and not drinking. It can be used in present, past and future contexts.
Not having spoken is a phrase that sets the scene in the past. It leads naturally to whatever follows as a consequence.
Not speaking during the lecture is/was the advice given to the students.
Not having spoken during the lecture, he raised his hand to ask a question.
Not speaking for an entire year means not saying anything for 365 days, by implication for a calendar year.
Not speaking in an entire year is not idiomatic. We don't say that someone didn't speak in an hour or in a day. I would disagree with RobJarvis's interpretation of the distinction.


text:
Q: C++ multiple type assignment I not very familiar with C++, have some issues with the multiple assignments
int a = 0, b = 0;

works
int i;
double d;
char c;
c = i = d = 42;

also works
but why this does not works.
int a = 4, float b = 4.5, bool ab = TRUE;

A: This is to do with the allowed syntax. The format is, in very high-level terms, roughly:
type varName [ = expr ][, varName [ = expr ] ]?;

Where there is no allowance at all for another type to be introduced mid-stream.
In practice declaring multiple variables per line can lead to a lot of ambiguity and confusion.
Quick quiz: What is the initial value of a? What type is b?
int* a, b = 0;

If you guessed a was a NULL pointer and b was int* you'd be wrong. This is why it's often preferable to spell it out long-form so there's absolute clarity:
int* a;
int b = 0;


text:
Q: Overriding onTrimMemory in Application vs Activity What are the merits and de-merits of overriding the onTrimMemory in an Application vs Activity. The Android documentation looks exactly the same for both Application's and Activity's onTrimMemory and it seem they are both called in background.
If I implements the onTrimMemory in Activity and the app is backgrounded and activities onDestroy is called, can onTrimMemory be called after that?
For the above case, should I put the onTrimMemory in the Application if I do want to trim the cache for the app if the onTrimMemory cant be called on the activity?

A: You should override onTrimMemory(int) in Application or Activity (or any other component) based on who keeps the memory you want to trim. The class that is responsible for the memory should do the trimming.
The mechanism of the callback is following: the system calls Application.onTrimMemory(int) which then calls the same callback on the app's components. The callback is called everywhere where is should be called (I doubt it will be after Activity.onDestroy() - you shouldn't care about such activity any more). Your decision to override shouldn't be affected by the Activity lifecycle.
If the memory belongs to the application, handle it there. If it belongs solely to an Activity, handle it there.


text:
Q: Git copying branches from one organization's repo to other organization's repo As of now, we are working in one organization who is having admin permissions for a repository. That repository has many branches among which three is ours.
We need to copy that three branches along with master from their organization's repository to our organization's repository (which is empty as of now).
All the webhooks installed in that, should be copied as well. Condition being: No files should be lost from either of the repositories. We just need a copy of it to do things from our own.
What is the best way to do it?

A: First, clone the repository locally.
~$ git clone git@github.com:org1/repo.git
~$ cd repo

Then, add another remote to that repository.
~/repo$ git remote add origin2 git@github.com:org2/repo.git

Now you have two remotes: origin points to org1/repo.git, and origin2 points to org2/repo.git.
So now, you want to push all of the branches of your local repo to your second remote:
~/repo$ git push origin2 --all

That should get you most of the way there. But it will not copy the webhooks.

A:
We need to copy that three branches along with master from their organization's repository to our organization's repository (which is empty as of now).

What can you do?

*

*Clone the original repo

*Add new remote git remote add <origin2> <url2>

*Use the code from both the repositories inside a single repo

Now you can pull and merge the branches from the 2 remotes and have the code of both of them in a single repository.
As you can see in the image below you will have 2 repositories  which builds up your big repository.
# clone first repository
git clone <repo1>

# add remote
git remote add <remote2> <url2>

# display the list of all the remotes
git remote -v

# now add your branches to what ever branch you want
# you said that you need 3 branches so simply check them out from originX
# and push them to origin Y

A: The -all did not work in my case. I used:
git clone <upstream-repo-url/repo.git> --mirror
cd <repo>
git remote add <your-remote-name> <your-remote-url/repo.git>
git push <your-remote-name> --mirror

git push all branches from one remote to another remote


text:
Q: Getting weird value in Double Hello i made a "Clicker" as a first project while learning swift i have an automated timer that is supposed to remove some numbers from other numbers but sometimes i get values like 0.600000000000001 and i have no idea why.
Here is my "Attack" function that removes 0.2 from the Health of a zombie.
let fGruppenAttackTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("fGruppenAttackTime"), userInfo: nil, repeats: true)

func fGruppenAttackTime() {
    zHealth -= 0.2
    if zHealth <= 0 {
        zHealth = zSize
        pPengar += pPengarut
    }

    ...
}

And here is my attackZ button that is supposed to remove 1 from the health of the zombie
@IBAction func attackZ(sender: UIButton) {
    zHealth -= Double(pAttack)
    fHunger -= 0.05
    fGruppenHunger.progress = Float(fHunger / 100)
    Actionlbl.text = ""
    if zHealth <= 0 {
        zHealth = zSize
        pPengar += pPengarut
    }
}

Lastly here are the variables value:
var zHealth = 10.0
var zSize = 10.0
var pAttack = 1
var pPengar = 0
var pPengarut = 1

When the timer is on and the function is running and i click the button i sometimes get weird values like 0.600000000000001 and if i set the 0.2 in the function to 0.25 i get 0.0999999999999996 sometimes. I wonder why this happens and what to do with it.

A: In trojanfoe's answer, he shares a link that describes the source of the problem regarding rounding of floating point numbers.
In terms of what to do, there are a number of approaches:

*

*You can shift to integer types. For example, if your existing values can all be represented with a maximum of two decimal places, multiply those by 100 and then use Int types everywhere, excising the Double and Float representations from your code.

*You can simply deal with the very small variations that Double type introduces. For example:

*

*If displaying the results in the UI, use NumberFormatter to convert the Double value to a String using a specified number of decimal places.
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 0  // or you might use `2` here, too
formatter.numberStyle = .decimal

print(formatter.string(for: value)!)

By the way, the NSNumberFormatter enjoys another benefit, too, namely that it honors the localization settings for the user. For example, if the user lives in Germany, where the decimal place is represented with a , rather than a ., the NSNumberFormatter will use the user's native number formatting.

*When testing to see if a number is equal to some value, rather than just using == operator, look at the difference between two values and seeing if they're within some permissible rounding threshold.

*You can use Decimal/NSDecimalNumber, which doesn't suffer from rounding issues when dealing with decimals:
var value = Decimal(string: "1.0")!
value -= Decimal(string: "0.9")!
value -= Decimal(string: "0.1")!

Or:
var value = Decimal(1)
value -= Decimal(sign: .plus, exponent: -1, significand: 9)
value -= Decimal(sign: .plus, exponent: -1, significand: 1)

Or:
var value = Decimal(1)
value -= Decimal(9) / Decimal(10)
value -= Decimal(1) / Decimal(10)

Note, I explicitly avoid using any Double values such as Decimal(0.1) because creating a Decimal from a fractional Double only captures whatever imprecision Double entails, where as the three examples above avoid that entirely.

A: It's because of floating point rounding errors.
For further reading, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Squeezing infinitely many real numbers into a finite number of bits
  requires an approximate representation. Although there are infinitely
  many integers, in most programs the result of integer computations can
  be stored in 32 bits. In contrast, given any fixed number of bits,
  most calculations with real numbers will produce quantities that
  cannot be exactly represented using that many bits. Therefore the
  result of a floating-point calculation must often be rounded in order
  to fit back into its finite representation. This rounding error is the
  characteristic feature of floating-point computation.


text:
Q: Determine the name of a file to download I need to download a file from a url which has format similar to http://server.com/settings/files/1 when I paste this url in a web-browser this can determine the name of the file to download in this case scheme_563.txt, my question is how I can retrieve the name of the file (which obviously is not included in the url) to download  using the wininet functions? currently i am using the HttpQueryInfo function with multiples values like HTTP_QUERY_CONTENT_LOCATION,HTTP_QUERY_CONTENT_DESCRIPTION, etc. but without luck.

A: According to http://en.wikipedia.org/wiki/List_of_HTTP_header_fields, the Content-Disposition header includes this information
Content-Disposition: attachment; filename=fname.ext

Maybe this optional header is available in the response to a HTTP GET or HEAD request in this case.
Note that the filename may be encoded - see How to encode the filename parameter of Content-Disposition header in HTTP? for a discussion


text:
Q: newly added item in ng-repeat is changing i am trying to add a object in ng-repeat, as shown :

            Names
            nos

            {{data.name}}
            {{data.no}}

    <input type="text" ng-model="models.name" placeholder="enter name" />
    <input type="number" ng-model="models.no" placeholder="enter number" />
    <input type="button" ng-click="datas.add(models)" value="click me!!!!" />

relevant javascript is :
    app.controller('filtersController', ['$scope', function ($scope) {
this.dataset = [{ name: "Vishesh", no: 1 },
                { name: "pqrst", no: 2 },
                { name: "uvwxyz", no: 3 }]
this.add = function (model) {
    this.dataset.push(model);
    $scope.$apply();
}}]);

Problem :
when i try to add new entries using textboxes, it will add first entry but after that i cannot add anymore entries in it, also the latest added entry changes when the values in the textboxes changes. Why is that?
Also if i change  javascript like this :
app.controller('filtersController', ['$scope', function ($scope) {
this.dataset = [{ name: "Vishesh", no: 1 },
                { name: "pqrst", no: 2 },
                { name: "uvwxyz", no: 3 }]
this.add = function (names, nos) {
    this.dataset.push({ name: names, no: nos });
    $scope.$apply();
}}]);

and HTML :
    <input type="text" ng-model="name1" placeholder="enter name" />
    <input type="number" ng-model="no1" placeholder="enter number" />
    <input type="button" ng-click="datas.add(name1,no1)" value="click me!!!!" />

it adds as many entries i want and works as expected.
What is wrong with the first approach?

A: ng-model="models.name" creates an object on the scope named "models".  Changes to models.name and models.no will change values within that object, but it's still a single object -- so datas.add(model) winds up pushing a reference to that single object onto this.dataset. Further changes to model will change that original object, which is already in this.dataset, because it's all references to the same object.
Your other approach works correctly because you're using separate primitives for ng-model="name1" and ng-model="no1". Here, each time datas.add(name1,no1) runs, it's pushing a newly constructed object onto this.dataset.  Further changes to name1 and no1 now won't modify old data, because they're primitives, not object references, and each time you push to this.dataset you construct a new object out of those primitives.

A: When you push the model object that you pass to your add() method onto the array you are actually pushing the reference to that object and now Angular is going to use two-way data binding on it. What you need to do is first copy the model so it disassociates it from the ng-model directives in your HTML.
this.add = function(model) {
  var newModel = angular.copy(model);
  this.dataset.push(newModel);
}

Here's a Plunker: http://plnkr.co/edit/SdtSesYxb828yJyDFwws?p=preview


text:
Q: C# mp3 in background I want to play a mp3 in background of my program ( without opening the media player for example --> System.Diagnostics.Process.Start(@"C:\Users\Franz\Music\Americana.mp3") ( I don't want to use...)
Now i tried it like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

class sound
{
   [DllImport("winmm.dll")]
   private static extern int mciSendString(string @cmd, StringBuilder ret, int retLen, IntPtr hwnd);
   [DllImport("winmm.dll")]
   private static extern int mciGetErrorString(int errCode, StringBuilder errText, int errLen);
}

private void txbStart_MouseClick(object sender, MouseEventArgs e)
{
   mciSendString("play \""+C:\Users\Franz\Music\Americana.mp3+"\", null, 0, IntPtr.Zero);
}

But it doesn'T work? but why? I'm a beginner in c# ...

A: There are many different methods you could use, some of which are explained below:

*

*http://www.daniweb.com/software-development/csharp/threads/292695/playing-mp3-in-c

*http://social.msdn.microsoft.com/Forums/vstudio/en-US/3dbfb9a3-4e14-41d1-afbb-1790420706fe/how-to-play-mp3-in-c?forum=csharpgeneral

*http://www.codeproject.com/Articles/3352/A-low-level-audio-player-in-C

*http://msdn.microsoft.com/en-us/library/windows/desktop/dd562692%28v=vs.85%29.aspx


text:
Q: get the list of open applications on windows I want to have a script that does the following thing:

*

*connect to a remote windows machine

*get the list of applications that are currently open on the machine, e.g exactly what I would get in the "applications" tab in the task manager, and print it.

Is it possible to do that in batch?
If not, what other options do I have?

A: If you have powershell installed, the following will get you a list of running applicaitons when run locally
gps | ? {$_.mainwindowtitle.length -ne 0} | select name, mainwindowtitle

If you have Powershell V2 installed on the machines you want to query, and remoting enabled, you can then run:
invoke-command –computername <remote computer name>
{gps | ? {$_.mainwindowtitle.length -ne 0} | select name, mainwindowtitle}


text:
Q: c99 -- expected expression before return The following recursive function should return 0 if the sum of the provided array is negative, and 1 if the sum is greater than or equal to 0. I don't understand why I get an "error: expected expression before return" when compiling it.
int restituisco(int *p, int len) {

    int somma;

    if (len == 0)
        if (somma < 0)
            return 0;
        else
            return 1;

    somma = p[len-1] + restituisco(p,--len);
}


text:
Q: Why would touching a rubber insulated spark plug wire causes current to go through your finger? I'm trying to understand the physics. The spark plug has a gap of 0.9mm.
Why would the current go through the insulation resistance, the finger resistance and the air gap between the finger and the engine ground instead of traveling a much less resistance through the 0.9mm gap?

A: Your finger on the wire forms a capacitor to the plug wire center conductor; the wire sheath is the dielectric. This couples to your body, forming a DC path to your torso. So the AC-coupled high-tension charge is flowing in and out of your finger to your body.
How? Even your ungrounded body presents a non-trivial capacitance to ground through the surrounding air, and in between any insulator and car ground. There will be some current, like static electricity.
Now if you're leaning on the fender, that makes a fairly big capacitance to car body ground. Given the voltages involved (~50kV for some systems), while you may not see a spark on your finger, you still might feel some current. Stand away from the fender and the body-to-car capacitance - and sensation you feel - will be less.
This across-the-insulator capacitive coupling between the plug lead and ground is why plug wires are routed away from the engine on insulating standoffs: to reduce shunt losses in the lead and instead deliver all the coil's energy to the plug where you want it.
The underlying physics is called displacement current, which is a fundamental part of how capacitors work (electric fields straining electron orbits). A change in charge induced by voltage change is accompanied by a current into and out of the capacitor as the charge changes. There doesn't need to be spark for that to happen, current still flows.


text:
Q: Running two Ubuntu KVM virtual machines with bridged (tapped?) networking I have a server that's running Ubuntu 14.04, and I'm trying to run two virtual machines with bridged networking at the same time.  The networking of the first VM works, but the second one has no networking.
The virtual machines are also Ubuntu 14.04.
What's the best way to get full (bridged) internet access for both VMs?
My best guess was to copy my br0 to br1, as seen below. But since it doesn't work, I'm guessing I need to do something else.
Here's my /etc/network/interfaces:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto em1
iface em1 inet dhcp

auto br0
iface br0 inet dhcp
   pre-up ip tuntap add dev tap0 mode tap user thor
   pre-up ip link set tap0 up
   bridge_ports all tap0
   bridge_stp off
   bridge_maxwait 0
   bridge_fd      0
   post-down ip link set tap0 down
   post-down ip tuntap del dev tap0 mode tap

auto br1
iface br1 inet dhcp
   pre-up ip tuntap add dev tap1 mode tap user thor
   pre-up ip link set tap1 up
   bridge_ports all tap1
   bridge_stp off
   bridge_maxwait 0
   bridge_fd      0
   post-down ip link set tap1 down
   post-down ip tuntap del dev tap1 mode tap

And here's how I start the kvms.
(kvm1 - the one that has networking)
kvm -enable-kvm -nographic -net nic -net tap,ifname=tap0,script=no,downscript=no -hda disk.img.a.qcow2 -hdb my-seed.img -m 8192 -smp 16

(kvm2 - the vm without networking)
kvm -enable-kvm -nographic -net nic -net tap,ifname=tap1,script=no,downscript=no -hda disk.img.b.qcow2 -hdb my-seed.img -m 8192 -smp 16

A: Bridges are like virtual ethernet switches -- you plug many VMs into them, not just one.  You should create a single bridge, and attach the NICs of both VMs to that one bridge.  Then they'll be able to talk to each other.

A: Based on @Womble's suggestion, I seem to have gotten it to work. I'll post what I did here so hopefully it will help others.
I welcome suggestions for better solutions.
Here's my new /etc/network/interfaces:
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto em1
iface em1 inet dhcp

auto br0
iface br0 inet dhcp
   pre-up ip tuntap add dev tap0 mode tap user myusername
   pre-up ip link set tap0 up

   pre-up ip tuntap add dev tap1 mode tap user myusername
   pre-up ip link set tap1 up

   bridge_ports all tap0 tap1
   bridge_stp off
   bridge_maxwait 0
   bridge_fd      0

   post-down ip link set tap1 down
   post-down ip tuntap del dev tap1 mode tap

   post-down ip link set tap0 down
   post-down ip tuntap del dev tap0 mode tap

(Replacing myusername, with the real user name I'm using).
Here's the command to start the first kvm:
kvm -enable-kvm -nographic -net nic -net tap,ifname=tap0,script=no,downscript=no -hda disk.a.qcow2 -hdb my-seed.img -m 8192 -smp 16

And here's the command to start the second kvm
kvm -enable-kvm -nographic -net nic,macaddr=0c:c4:7a:73:14:b2 -net tap,ifname=tap1,script=no,downscript=no -hda disk.img.b.qcow2 -hdb my-seed.img -m 8192 -smp 16

I had to explicitly set the mac address on the second kvm, otherwise it would have the same mac address as the first.  Having the same MAC address leads to intermittent timeouts with networking, as you can imagine.


text:
Q: How to build a three-tiered web service I want to create a web service (SOAP) under Apache Tomcat with Axis2, and I must respect the three-tiered architecture:
DAO -> Business Logic Layer -> Presentation Layer
I'm new to web services. Is there a step-by-step tutorial for this?

A: There isn't really a presentation layer in a web service, unless you consider the service itself to be the presentation layer.
http://www.roseindia.net/webservices/axis2/
There is tons of DAO information on the web, and there's nothing special about a DAO layer for a service versus any other application.  A lot of this will depend upon how you want to build your DAO layer.  I like using Spring JDBC.

A: Three tiered architecture means different things to different people.
One common interpretation is (with tiers from the user starting with #1):

*

*Presentation layer running in the browser. I.e. Javascript (possibly from some framework such as jQuery, GWT, etc).

*Business Logic layer running on the server. I.e. A dynamic web server (Tomcat in this case)

*Database such as MySQL, SqlServer, Oracle, PostgreSql, etc.

It's also possible to have a layer #2.5 doing the DAO work for you (or a custom DAO) such as Hibernate.
Another interpretation is that #1 is actually the web server, and #2 is a separate business logic server, where #1 and #2 live in separate server instances (likely on separate machines or VMs) for security, isolation, and the ability to scale and release separately (and many other motivations).
In any case, you should read up on typical Java serving architectures and possibly describe your goals better. I.e. you use "Presentation Layer" which in some definitions doesn't make sense for a non-UI based web service. Of course, Axis2 could be your "presentation layer" for a web service as well :)


text:
Q: Angular, Unable to find the root parent by its class interface From the angular documentation here, I had created a Parent class using
export abstract class Parent {}

Inside the AlexComponent, I had provided this component as Parent  to its children
providers: [{ provide: Parent, useExisting: forwardRef(() => AlexComponent) }]

Im able to access the parent inside the child component using
export class CarolComponent {
   name = 'Carol';
   constructor( @Optional() public parent?: Parent ) { }
}

But I am unable to access the parent inside the nested child components. That means parent provider gives the immediate Parent but I want to access the root parent.
For example, In this screenshot,

I want the Chris component to access the Alice Component (root parent but not immediate parent)
Is there a way to access the root parent ?

A: I've created an example in stackblitz and it works. I don't know if it's what you want to do. The child component Chris access root parent Alice injecting the Parent class.
https://stackblitz.com/edit/angular-accessing-root-parent

A: Components are created and injected into your application through Angular's injector.
Each Angular element that is decorated (@Component, @Service, ...) gets an injection token corresponding to the class itself, which is then pushed into a weakMap.
This means that every Angular element should be injected into another element and should be used by this element, provided that they are in the same injector and that they are injected and used in a correct order.
What happens here for you, is that you probably extends the Parent class in the Alice component, but also in the "blue" classes. Since the weakMap relies on the class metadata to work, it probably erases the Alice component from the weakMap to replace it with your blue class.
To resolve that, try not extending the Parent class, and reference directly your classes instead of an abstract class. See if it works.


text:
Q: Populating listbox with files to include creation date I am attempting to populate a listbox with the contents of a directory. I have it populating but I need the creation date/time included in the list.
This is what I have so far:
  var filter = Path.GetFileName(GlobalVariables.EbillFile);
  listBox_Restore.DataSource = Directory.GetFiles(GlobalVariables.EbillBackupDirectory, $"{filter}.*", SearchOption.TopDirectoryOnly);

It gives me this:
ListBox Contents
How do I go about adding the date to this list? Should I be using a different control?

A: You should use DirectoryInfo.GetFiles() to get more information about each file - for instance created date, last used date, size etc.
And then use a ListView to show the result.


text:
Q: ActionScript 2.0 dynamic smoothing I'm trying to make smoothing for images which loaded with loadclip().
I found function for smoothing and it works but only for movieclips located in _level0, for example _level0.mc, but I want to smooth children MC, for example _level0.parent_mc.children_mc and then image just dissapears.
smoothing function:
here = this; // trace(here) == _level0
bg_smooth = function (bg):Void {
    var bg_depth:Number = bg.getDepth();
    var bg_name:String = bg._name;
    var bg_parent = bg._parent;
    var bg_bitmap_temp:BitmapData = new BitmapData(bg._width, bg._height, true, 0x00FFFFFF);
    bg_bitmap_temp.draw(bg);
    removeMovieClip(bg);
    bg_parent.createEmptyMovieClip(bg_name,bg_depth);
    here[bg_name].bitmapObj = bg_bitmap_temp.clone();
    bg_bitmap_temp.dispose();
    here[bg_name].attachBitmap(here[bg_name].bitmapObj,1,"auto",true);
};

other code:
var loader:MovieClipLoader = new MovieClipLoader();
var mclL:Object = new Object();
mclL.onLoadProgress = function(target, loadedBytes, totalBytes) {
 //trace(Math.round((loadedBytes / totalBytes) * 100) + "%");
};
loader.addListener(mclL);
mclL.onLoadInit = function(element) {
    bg_smooth(element); // trace(element) == _level0.mc or _level0.parent_mc.children_mc
};

loader.loadClip("img/image.jpg", mc); // <= works
//loader.loadClip("img/image.jpg", parent_mc.children_mc); // <= not works

also tried to write _level0.parent_mc['children_mc'] instead of parent_mc.children_mc and to make here == _level0.parent_mc - still no luck. If I remove bg_smooth(element) on load complete then all works fine but of course smoothing disabled.

A: I found another working function. May be helpful for someone else.
function applySmoothing(target:MovieClip) {
    var mcParent:MovieClip = target._parent;
    var mcName:String = target._name;
    var myBitmap:BitmapData = new BitmapData(target._width, target._height);
    myBitmap.draw(target);
    target.removeMovieClip();
    target.attachBitmap(myBitmap, 1, "auto", true);
}


text:
Q: What is an alternate method to send keys to an application without being detected by keyloggers? What is the alternate method to send keys to an application without being detected by keyloggers, even not been detected by SetWindowsHookEx LowLevel Keyboard Hooking. I know there are Virtual Keyboards that are used for this purpose but I want its technique? Is there any opensource project related to it?

A: You can use a WM_SETTEXT message to directly set the text value of a particular edit box in the target application, but you have to inject your process into the target process first.
The advantage of doing this is that even if the message is hooked using SetWindowHookEx, there is no way to find out the string without likewise injecting the process. To realistically intercept this kind of message the malware would have to hook every single process on the computer and even then it would do no good because most text is not keyboard text, so the malware would have no way to know what was keyboard text and what was not.
Another method is to use WM_COPYDATA, but that is externally hookable.

A: the best way is to send ASCII string via the clipboard, is a clever method used by some program like the good KeePassX or PasswordSafe by Bruce Schneier

A: If it's sufficient to send a 4 or 6-digit PIN, your application could ask to enter it through a random mapping ->
    (1)  (2)  (3)
    zih  lbg  qsw

    (4)  (5)  (6)
    ukx  ...  ...

Code 1234 would be entered as ibqu or zlsx.
Of course this is compromised at the instant of customer actually entering his PIN as digits...
This method becomes increasingly annoying when the length increases -- so I offer this as only an alternative as asked in your title, not the best.


text:
Q: Am I supposed to have access to "com.apple.TCC"? I was doing some snooping around on my MacBook Air after the update to macOS Mojave and noticed a folder that I have permission to view its contents that I don't have permission for on my iMac. The folder in question is "com.apple.TCC" under the Application Support folder, the path from the Finder is by selecting the following: Macintosh HD -> Library -> Application Support

I was just poking around and noticed that the folder was inaccessible on the iMac and it had me wondering as to whether or not I should have access to it in the first place. I wasn't going around aimlessly deleting/modifying any of the files, I was just curiously looking at them and nothing more.
I find it quite strange that my MacBook is able to view the contents, but the iMac is not and was wondering if others can confirm if they can/cannot view its contents.

A: Apparently the TCC database stores the "privacy database": settings from System Preferences > Security & Privacy > Privacy.
See https://eclecticlight.co/2017/01/09/controlling-privacy-in-macos-sierra/ and man tccutil.
The article says

... this is managed in a special TTC database, which is stored in the folder ~/Library/Application Support/com.apple.TCC. There is also a master database stored at /Library/Application Support/com.apple.TCC, but you cannot open that folder, as only the system has that privilege.

On my iMac running High Sierra:
$ ls -ld /Library/Application\ Support/com.apple.TCC ~/Library/Application\ Support/com.apple.TCC
drwx------  3 root    admin  102  4 Oct 11:15 /Library/Application Support/com.apple.TCC
drwx------  3 ashley  staff  102 29 Jun 16:13 /Users/ashley/Library/Application Support/com.apple.TCC

Note the different ownership: the one in /Library (= Macintosh HD -> Library) is owned by root, and the one in my home folder (~/Library/Application Support = /Users/ashley/Library/Application Support) is owned by me. Because the permissions are drwx------ in both cases, only the owner can see into the folder... so when I look in Finder, the one in /Library has a "no entry" sign on it (because I'm not root), but I can open the one in my home folder, and see there is a file there named TCC.db.
I don't know why you see a difference between your MacBook Air and your iMac. In older times, I'd recommend you "repair permissions", but I believe that facility has gone away in the recent operating systems.


text:
Q: Does the sequence of iterated derivatives of $2^x$ converge uniformly to the zero function? Consider the function $2^x$. As you keep taking derivatives of that function over and over again, it converges to the zero function, at least pointwise. My question is, does it converge uniformly to the zero function on the entire real line? I used the example of $2^x$, but I could have used any exponential function $b^x$ for a number $b$ between $1$ and $e$.

A: Recall that $\frac{d}{dx} b^x = b^x \ln b$, just multiplying by a constant.  (If $b = e$, then that constant is $\ln e = 1$, so the function is its own derivative.)  With each iterated differentiation, you just multiply by the same constant again, so:
$$f_n(x) = (\ln b)^nb^x$$
This converges (pointwise) to zero as $n \rightarrow \infty$ if $|\ln b| < 1$, ie.,
$$\frac{1}{e} < b < e$$
It happens that $b = 2$ satisfies this condition.
However, uniform convergence on the entire real line requires
$$\forall \epsilon > 0: \exists N \in \mathbb{N}: \forall x \in \mathbb{R}, n \ge N: |f_n(x) - 0| < \epsilon$$
$$|\ln b|^nb^x < \epsilon$$
$$|\ln b|^n < \frac{\epsilon}{b^x}$$
which cannot be satisfied $\forall x \in \mathbb{R}$ unless $|\ln b| = 0$ (IOW, $b = 1$).


text:
Q: IF statements to rank different ranges with field calculator in ArcMap I have a simple calculation to perform using the Python Parser in ArcMap but am running into some trouble when it comes to coding the ranges of values.
I have three different fields: mean temperature, altitude, and precipitation that I would like to reclass. For example,
if temperature is >= 18 and altitude <650 and precipitation >= 1200 then write Optimal
if temperature is < 12 and altitude >=1300 and precipitation is <900 then write Unsuitable
if mean temperature is between 12-17 and altitude is between 650-1299 and precipitation between 900-1199 then write sub-suitable.
I get stuck at the last class when trying to do the code for calling up within a ranges of values. Finally, I have added a new field for the classes called MC_Clim.
This is the code I have come up with so far:
def Reclass(temperature,altitude,precipitation):
       if tmean>= 18 and altitude< 650 and prec13>= 1200:
          val= "Optimal"
       elif tmean < 12 and altitude >= 1300 and prec13< 900:
          val= "Unsuitable"

Expression:
     Reclass (!temperature!,!altitude!,!precipitation!)

A: You are close. I believe you just need to return your desired text string. And make sure argument names match your variable names (if mean temperature and temperature are different columns, be sure to include them as separate arguments)
def Reclass(temperature,  altitude, precipitation):
   if temperature >= 18 and altitude < 650 and precipitation >= 1200:
      return "Optimal"
   elif temperature < 12 and altitude >= 1300 and precipitation < 900:
      return "Unsuitable"
   # to test if a value is inside a range
   elif 12 < temperature < 17 and 650 < altitude < 1299:
      return "Sub-suitable"
   return "N/A"

## here you include column names as arguments
Expression:
     Reclass (!tmean!,!altitude!,!prec13!)


text:
Q: modal with items vertically centered aligned and with scroll I'm using bootstrap modal, and I would like to have a list with some buttons inside the modal body with this structure:
    IMAGE            IMAGE        IMAGE       IMAGE
  All Options       Option1     Option2     Other Option

   IMAGE            IMAGE        IMAGE       IMAGE
   Option3         Option4      Option5       ...

   IMAGE
   Option7

So the same margins between the buttons and all the list items aligned vertically aligned and with scroll because the buttons can occupy more height than the default modal height.
Do you know how to achieve that? I'm doing like this: http://jsfiddle.net/znhgdzL7/, but it's not working.

A: I added a max-height and an overflow to the CSS. Would that solve your issue.
It may not be the values you want, but you can adjust them accordingly.
To keep your content within the horizontal max, you will need to add the wrap property to your CSS. See the new fiddle.
  display: flex;
  flex-wrap:wrap;
  max-height:50px;
  overflow-y:auto;

new fiddle: http://jsfiddle.net/djwave28/znhgdzL7/7/

A: Check this: http://jsfiddle.net/znhgdzL7/10/
The modal can now handle many options.
here is the css:
img{
  width: 30px;
  height: 30px;
  margin-bottom: 20px;
}
.row > div {
  margin-bottom: 20px;
  text-align: center;
}
.categories-list {
 max-height: 400px;
 overflow-y: auto;
}

I also updated the html, you can just check it on the jsfiddle link.


text:
Q: How to query out random company name from grouping MYSQL I want to get specific company name from grouping. The table data look like this. I want to be able to choose one of the company_name to show in the output depending on my preference. For example i want to show Halliburton, or Hycalog, or Drill in the output for Rig A is that even possible?
rig     sequence  company_name  total_time
------  --------  ------------  ------------
Rig A   1         Hycalog                 20
Rig A   2         Halliburton             20
Rig A   3         Drill                   20
Rig B   4         Conoco                  30
Rig B   5         Total                   30

I have tried sub-query and case when all not return the results i wanted. All i wanted is to choose which company to show in the output out of the random company in the original data for example in this case i want to show company_name Drill for Rig A and show company_name Total for Rig B...
Of course if possible i can freely choose which company name i would like to show in the output.
SELECT rig, sequence, company_name, SUM(total_time) FROM table A GROUP BY rig;

rig     sequence  company_name  total_time
------  --------  ------------  ------------
Rig A   3         Drill                   60
Rig B   5         Total                   60

A: If you are using MySQL 8+, then here is one option using ROW_NUMBER:
SELECT rig, sequence, company_name, total_time_sum
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY rig ORDER BY RAND()) rn,
        SUM(total_time) OVER (PARTITION BY rig) total_time_sum
    FROM tableA
) t
WHERE rn = 1;

Demo
This will choose a random row from each rig group and display it.

A: The following query will return the expected output:
SELECT rig, sequence, company_name, SummedTotal AS total_time
FROM
(
    SELECT *,
           SUM(total_time) OVER (PARTITION BY rig) AS SummedTotal,
           ROW_NUMBER() OVER (PARTITION BY rig ORDER BY RAND()) Rnum
    FROM TableA
) Q
WHERE Rnum = 1;


text:
Q: add column db-mgirate node I'm trying to add columns using node package db-migrate
Going through the docs, I can see how to create a table, and update data, but I don't see anything that lets me add a column to a table already in existence.
db.createTable('pets', {
id: { type: 'int', primaryKey: true },
name: 'string'
}, callback);

A: db-migrate SQL-Api has an addColumn method.
exports.up = function(db, callback) {
  db.addColumn('customers', 'firstname', { type: 'string' }, callback);
};

This would add a column firstname to table customers.
Please have a look in docs for details.


text:
Q: Uso de string dá erro No inicio do código eu declaro a variável nome como char e quando tento pegar a variável nome lá em baixo no código dá erro, eu já tentei de várias formas e dessa forma que esta ai em baixo até dá certo, mas as vezes quando aparece a pergunta pro usuário " Deseja continuar ? " e ele responde s (sim), às vezes pula direto pro campo "digite o salario do funcionário:", ou seja. pula a parte em que pergunta o nome do funcionário
int cont, tinss;

char s, resp, nome[50];

float sal, novosala, val;

cont = 1;

do
{
    printf("\n digite o nome do funcionario; ");
    scanf("%s",&nome);
    printf("\n digite o salario do funcionario: ");
    scanf("%f",&sal);

    if(sal <= 500)
        {
            novosala = sal - ((sal / 100) * 8);
            val = (sal / 100) * 8;
            tinss = 8;
        }
    else
    if(sal > 500 &&  sal <= 1000)
        {
            novosala = sal - ((sal / 100) * 10);
            val = (sal / 100) * 10;
            tinss = 10;
        }
    else
    if(sal > 1000)
        {
            novosala = sal - ((sal / 100) * 12);
            val = (sal / 100) * 12;
            tinss = 12;
        }

    printf("\n Nome: %s \n",nome);
    printf("\n Salario bruto: %f \n", sal);
    printf("\n Taxa de INSS: %d% \n", tinss);
    printf("\n Valor de INSS %f \n", val);
    printf("\n Salario liquido: %f \n", novosala);

    printf("\n deseja continuar ? \n");
    resp = getch();
    cont = cont + 1;
}
while(resp == 's');

A: Primeiro, você pode até estar usando um compilador C++ mas você está programando em C. E está usando uma função que não deveria ser usada mais. Elimine a getch() e o problema será resolvido.
Tem outras funções que podem ser usadas mas eu usaria o scanf() até para não ficar esquisito hora ter que dar o ENTER, hora não.
Então ficaria assim:
#include <stdio.h>

int main() {
    char resp;
    do {
    int cont = 1, tinss;
    char s, nome[50];
    float sal, novosala, val;
    printf("\n digite o nome do funcionario; ");
        scanf("%s",&nome);
        printf("\n digite o salario do funcionario: ");
        scanf("%f",&sal);
        if (sal <= 500) {
            novosala = sal - ((sal / 100) * 8);
            val = (sal / 100) * 8;
            tinss = 8;
        } else if (sal > 500 &&  sal <= 1000) {
            novosala = sal - ((sal / 100) * 10);
            val = (sal / 100) * 10;
            tinss = 10;
        } else if (sal > 1000) {
            novosala = sal - ((sal / 100) * 12);
            val = (sal / 100) * 12;
            tinss = 12;
        }
        printf("\n Nome: %s \n",nome);
        printf("\n Salario bruto: %f \n", sal);
        printf("\n Taxa de INSS: %d% \n", tinss);
        printf("\n Valor de INSS %f \n", val);
        printf("\n Salario liquido: %f \n", novosala);
        printf("\n deseja continuar ? \n");
        scanf("%s",&resp);
        cont = cont + 1;
    } while (resp == 's');
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Versão mais C++:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string  resp;
    do {
        int cont = 1, tinss;
        string s, nome;
        float sal, novosala, val;
        cout << endl << "digite o nome do funcionario: ";
        cin >> nome;
        cout << endl << "digite o salario do funcionario: ";
        cin >> sal;
        if (sal <= 500) {
            novosala = sal - ((sal / 100) * 8);
            val = (sal / 100) * 8;
            tinss = 8;
        } else if (sal > 500 &&  sal <= 1000) {
            novosala = sal - ((sal / 100) * 10);
            val = (sal / 100) * 10;
            tinss = 10;
        } else if(sal > 1000) {
            novosala = sal - ((sal / 100) * 12);
            val = (sal / 100) * 12;
            tinss = 12;
        }
        cout << endl << "Nome: " << nome << endl;
        cout << "Salario bruto: " << sal << endl;
        cout << "Taxa de INSS: " << tinss << endl;
        cout << "Valor de INSS " << val << endl;
        cout << "Salario liquido: " << novosala << endl;
        cout << endl << "deseja continuar ? " << endl;
        cin >> resp;
        cont++;
    }
    while (resp == "s");
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dá para fazer melhor mas já está mais organizado.


text:
Q: Getting select item from three different spinners using a button to show simple fragment I am using three spinners so that the user can choose: origin, destiny and time. Depending of 3 items chosen from the spinners i want to show a fragment. I have created the spinners and the button populated the spinner using an array-list.
Example:
final Spinner Time = (Spinner) findViewById(R.id.spinner3);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
            R.array.time, android.R.layout.simple_spinner_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Time.setAdapter(adapter2);

The problem is that i am not being able to get the items selected by the user so that i can show the fragment.
I have tried to use this:
            Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

               @Override
            public void onClick(View v) {

                   Origin.getSelectedItem();
                   Destiny.getSelectedItem();
                   Time.getSelectedItem();

                   Origin.getSelectedItem().toString();
                   Destiny.getSelectedItem().toString();
                   Time.getSelectedItem().toString();

if (Origin.getSelectedItem()=="Lisbon" && Destiny.getSelectedItem()=="Ponta Delgada" && Time.getSelectedItem()=="7:00–8:00") {
    FragmentTwo firstFragment = new FragmentTwo();
    getSupportFragmentManager().beginTransaction()
            .add(R.id.main, firstFragment)
            .commit();
                   }
    }});
}


text:
Q: Rust: Generalize over Tokio TCPStream or anything that extends std::io::Write Background
I am writing a protocol machine for a library that I have purposefully written to abstract away the TCP stream.
In general, it has three functions:

*

*receive_data(), which takes in bytes.

*read_pdu(), which consumes the next Protocol Data Unit (PDU).

*write_data(), which frames data in a Protocol Data Unit (PDU) and writes it to the write stream.

I did this so I could abstract over these three IO sources:

*

*Mocked input sources and output sinks in unit tests.

*std::net::TcpStream (which implements Write).

*tokio::net::TcpStream
Number 3 is my problem: I thought Tokio implements std::io::Write in TcpStream, but I see now that it implements AsyncWrite. I am essentially trying to generalize over synchronous and asynchronous write(), which I am not even sure is possible.
Question
That said, to re-state my question: how do I generalize over sync and async writes in Rust?
I would like to add that I am open to answers that provide alternative solutions. For example, if there is a way to mock TCP sockets for testing purposes, then I don't have as strong a need for this layer of abstraction.


text:
Q: Don't allow
A: No, you can't stop a user from doing anything in their browser.
More to the fundamental point, regardless of any script tags or anything you display to the user, you can't stop anybody from manually crafting GET/POST/etc. requests to your site.  So even if you could somehow prevent someone from editing the HTML in their browser (which, again, you can't), they could still just watch the POST request and craft their own fake one with whatever data they want.
Never, ever, ever rely on client-side code for important business logic.  Track the prices of things in server-side code and use that value.  You can still maintain such data in client-side code (for UX purposes, mostly), but don't use it server-side without validating it against known trusted data first.

A: No, you can't do that. You should always have that sort of validations on the server side, because everything that comes from the user browser may be faked.

A: u need to display everything u need to the user but only pass the item id to the post.
then serverside retrieve the price and the rest of the data for the transaction.


text:
Q: Chkdsk and PSEXEC I run maintenance for a lot of offices and use chkdsk as a part of the maintenance. I've recently been using PSEXEC to start a batch file that simply runs chkdsk and then pauses to keep the command prompt window open so that I can check to see if there were any errors found.
I would like to automate the process a little more.
I read somewhere (sorry my browser is not letting me cut and paste the link to the TechNet article) that chkdsk has exit codes that can be used to determine if any errors were found or not.
My problem is that I do not know where to begin in making use of these error codes? Could anyone shed some light or point me in the right direction on what I need to learn so that I can make a batch file or script that can run the chkdsk and then perform another action depending on the exit code?

A: The batch file is interpreted by CMD. The exit status of a command is stored in %errorlevel% variable.
echo %ERRORLEVEL%

or:
goto error_%ERRORLEVEL%
:error_0
echo Ok
:error_1
echo Exit code 1.
...

The if command in cmd can test for the status of the last command:
IF ERRORLEVEL 0 goto okay
echo Error.
goto end
:okay
echo Normal exit.
:end

For details run inside cmd:
 help if

A: ok here's a link to do this via powershell which I'd think would be more robust then a psexec solution (not that psexec is bad).
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384915(v=vs.85).aspx


text:
Q: Inline implemented interface indentation I've noticed that when I inline implement an interface in the class body itself, ie. not inside a method,
Runnable r = new Runnable() {

    @Override
    public void run() {
        // do something
    }
};

and then press CTRL + SHIFT + F (automatically fixes indentation), eclipse indents the methods alot like:
Runnable r = new Runnable() {
                            @Override
                            public void run() {
                               // do something
                            }
};

Anyone else encountered this?

A: Uncheck the "Align fields in columns" from the first tab of the Formatter

A: Depends on your eclipse settings. You can change the default formatting by clicking: window > preferences > java > code style > formatter.

A: In eclipse preferences, go to the formatter page (Window->Preferences, Java->Code Style->Formatter).  Edit the formatting 'Profile'.  Go to the 'Blank Lines' tab, and change the 'Before first declaration' value from 1 to 0.
FYI, this will change the formatting for ALL classes, not just anonymous ones.  It'd be nice if it was more granular, but there it is.


text:
Q: ¿Cuál es la diferencia entre el tipo Long y el tipo Integer en Java? No logro ver la diferencia que hay entre ambos tipos

A: *

*Long usa 64 bits.

*Int usa 32 bits.

Por lo que la cantidad de valores enteros distintos que pueden tomar es distinta.
En la siguiente imagen extraída de aquí puedes ver los valores que comprenden.
Espero que te haya servido.


text:
Q: python read file output from certain string value I want to read the text file from the part where it prints Network Cards and continue from there, but i dont have a clue how to do this.
import os

def main():
    print "This is a file handling system"
    fileHandler()

def fileHandler():
    os.system('systeminfo>file.txt')
    foo = open('file.txt', 'r+')
    readFile = foo.read()
    x = readFile.startswith('Network Card')
    print x
    foo.close()

if __name__ == '__main__':
    main()

A: You don't need to save the subprocess output to a file first. You could redirect its stdout to a pipe:
from subprocess import check_output

after_network_card = check_output("systeminfo").partition("Network Card")[2]

after_network_card contains output from systeminfo that comes after the first "Network Card"`.
If you have access to the output as a file object then to get the part starting with the line with "Network Card":
from itertools import dropwhile

with open('file.txt') as file:
    lines = dropwhile(lambda line: "Network Card" not in line, file)

You could also use explicit for-loop:
for line in file:
    if "Network Card" in line:
       break
# use `file` here

A file is an iterator over lines in Python.


text:
Q: How can i remove views inside of StackLayout? I have a project. When i scan a barcode; its adding labels inside of stacklayout. But when i scan 2nd one its saving first labels, then adding 2nd one too. I must see just scanned one, not the 1st one. So how can i delete first labels then add new ones ?
  for (int i = 0; i < count; i++)
            {
                kampanya.Children.Add(new Label
                {
                    Text = $"{myCampaignList[i].Name}",
                    TextColor = Color.FromHex("#22223b"),
                    FontSize = 22
                }); ;

Its my part of a code. When i scan its adding new label like this.

A: Clear all children of the StackLayout before start adding any:
 kampanya.Children.Clear()
 for (int i = 0; i < count; i++)
{
     kampanya.Children.Add(new Label
     {
         Text = $"{myCampaignList[i].Name}",
         TextColor = Color.FromHex("#22223b"),
         FontSize = 22
     });
}


text:
Q: How to use ajax in ruby on rails to update a form after a field has been filled out I have two models, one is called labor_report and the other is employee, My ruby on rails application deals with creating labor reports for a certain employee. So after the employee enters his employee number in a text field for the labor report, i need ajax to grab the corresponding name and department number from employees and fill in the other textboxes for the labor report that correspond to that data.

A: Maybe you're looking for observe_field.
http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/observe_field

A: If you are using jquery and unobtrusive javascript, you could use jquery's "blur", which triggers an event when you click or tab out of a text field:
$("input").blur(function(){
      $.ajax({
        type: "POST",
        url: "/controller/action",
        data: $(this).val(),
        dataType: "script",
        callback: null
      });
    }
    return false;
  });


text:
Q: how to add a class to one dynamic menu item? php:
$sql = "SELECT id, menuname
        FROM table
        WHERE status = 'active'
        ORDER BY order ASC";
$result = mysql_query($sql);
$menu = "
\n";
while ($row = mysql_fetch_assoc($result)) {
    $menu.= "
{$row['menuname']}
";
}
$menu.= "
\n";

html:

About

News

Prices

Gallery

Contact

I'd like to add the class="lhidden" to the "News" (not the 2nd menu,because the order can be changed).

News

How can i do that? I'm just learning javascript and php,so I have no idea :S

A: How about
while ($row = mysql_fetch_assoc($result)) {
    $menu.= "
{$row['menuname']}
";
}

A: Using jQuery is pretty easy:
$('a[href="?id=2"]').parent().addClass('lhidden');

This would first find the specific anchor, then add your class to its parent.
Documentation for the selector part here: http://api.jquery.com/attribute-equals-selector/

A:    $sql = "SELECT id, menuname
   FROM table
   WHERE status = 'active'
   ORDER BY order ASC";
   $result = mysql_query($sql);
   $menu = "
\n";
   while ($row = mysql_fetch_assoc($result)) {

   if($row['id']==2)
   {
       $menu.= "
{$row['menuname']}
";
   }
   else
   {
       $menu.= "
{$row['menuname']}
";
   }
   $menu.= "
\n";


text:
Q: Injecting a service / constant with a namespaced name like "com.application.configs" I have a constant service defined like:
myModule.constant("com.application.configs",{language: "EN"});

And now I want to inject this into my controller but I don't know how to achieve this using a constant name with dots like that.
myModule.controller("dialogController",function ($scope, com.application.configs) {...})

Obviously this doesn't work but I don't know how to do this injection or if this is possible without doing the manual $inject.
How can I correctly use a service / constant like that?

A: You can't use dot in variable names. Try
myModule.controller("dialogController",['$scope', 'com.application.configs', function ($scope, applicationConfigs) {...})

'com.application.configs' should be injected as applicationConfigs


text:
Q: Widgets with *internal* links do not display after database migration I am using Grunt to dump my local db, search and replace URLs in it (and account for serialization by using grunt-peach based on Peach), send it to my staging server, then import it into my staging db. I use Grunt because I can accomplish all of this with one quick command line entry.
However, after a successful db transfer to my staging server, any widgets—either custom widgets or the built in text widget that comes bundled with WordPress—do not appear on the frontend or in the backend (Appearance->Widgets screen) of my staging server after a transfer if they contain an internal link (i.e., a link to a page or post within my site). If they contain an external link (e.g., to stackoverflow.com) then the widget appears on the frontend and in the backend as expected.
I've examined the db entries for the widgets in question on the staging server after a successful transfer. The links are present, they correctly point to the staging server URL instead of my local URL, and the new character counts (serialization) appear correct.
Does anyone know what the issue could be and how I can ensure all of my widgets containing internal links transfer successfully?
EDIT: Upon further inspection, the serialization is not corrected after migration. I suspect this is a bug with Peach opened an issue.

A:
* Import the database on the new server.

When your domain name or URLs change there are additional concerns. The files and database can be moved, however references to the old domain name or location will remain in the database, and that can cause issues with links or theme display.
If you do a search and replace on your entire database to change the URLs, you can cause issues with data serialization, due to the fact that some themes and widgets store values with the length of your URL marked. When this changes, things break. To avoid that serialization issue, you have three options:

*

* Use the Velvet Blues Update URLs or Better Search Replace plugins if you can access your Dashboard.

* Use WP-CLI's search-replace if your hosting provider (or you) have installed WP-CLI.

* Use the Search and Replace for WordPress Databases Script to safely change all instances. (If you are a developer, use this option. It is a one step process as opposed to the 15-step procedure below)


text:
Q: Mikhlin multiplier theorem at origin? The Mikhlin multiplier theorem states the following:
Theorem [Theorem 2, Davide Guidetti
Vector valued Fourier multipliers and
applications]. Let $m$ be a bounded function on $\displaystyle \mathbb{R}^{n}$ which is smooth except possibly at the origin, and such that the function ${\displaystyle |x|^{k}|\nabla ^{k}m|}$ is bounded for all integers ${\displaystyle 0\leq k\leq n/2+1}$: then $m$ is an $L^p$ multiplier for all $1 < p < \infty$.
Why not considered at the origin? At origin is trivial? (Because if $x=0$ then ${\displaystyle |x|^{k}|\nabla ^{k}m|}$ is bounded automatically?