Q:

undefined method `joins' for #

I'm trying to convert this query from raw SQL to Arel (6.0.0), but I'm running into problems that I never had before Arel was rebuilt from the ground up in later versions. The error I'm getting, specifically, is:
undefined method `joins' for #<Arel::SelectManager>
This error occurs are starting an ActiveRecord joins query, and then appending another joins. Any idea how I should combine joins with ActiveRecord (and Arel predicates?)
The new code:
v = o.joins(Vote.table_name).on(Vote.arel_table[:voteable_type].eq(o.to_s).and(Vote.arel_table[:voteable_id].eq(o.arel_table[o.primary_key])))
        v = v.joins(self.class.base_class.table_name).on(self.base_class.arel_table[self.class.base_class.primary_key].eq(o.arel_table[p[0]]))
        v = v.where(self.class.base_class.areal_table[self.class.base_class.primary_key].eq(self.id))

converted from:
v = o.where(["#{self.class.base_class.table_name}.#{self.class.base_class.primary_key} = ?", self.id])
v = v.joins("INNER JOIN #{Vote.table_name} ON #{Vote.table_name}.voteable_type = '#{o.to_s}' AND #{Vote.table_name}.voteable_id = #{o.table_name}.#{o.primary_key}")
v = v.joins("INNER JOIN #{self.class.base_class.table_name} ON #{self.class.base_class.table_name}.#{self.class.base_class.primary_key} = #{o.table_name}.#{p[0]}")

o is an ActionModel Instance.
If anyone's interested, this if for use in the thumbs_up gem.
Any help would be appreciated!

A:

Is join in Arel not joins
vote_t = Vote.arel_table
other_t = self.class.base_class.arel_table
v = o.join(vote_t).on(vote_t[:voteable_type].eq(o.to_s).and(vote_t[:voteable_id].eq(o.arel_table[o.primary_key])))
v = v.join(other_t).on(other_t[self.class.base_class.primary_key].eq(o.arel_table[p[0]]))
v = v.where(other_t[self.class.base_class.primary_key].eq(self.id))


Q:

Unity 3d Importing .png via script

I have a problem. When I try to import texture via script to my assets, I get this error:

Assertion failed: Assertion failed on expression:
  '!(o->TestHideFlag(Object::kDontSaveInEditor) && (options &
  kAllowDontSaveObjectsToBePersistent) == 0)'
  UnityEditor.AssetDatabase:CreateAsset(Object, String)
  Editor.TextureImportWindow:OnGUI() (at
  Assets/Scripts/Editor/TextureImportWindow.cs:40)
  UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

and this:

Could not create texture from Assets/Textures/importedTexture13.png:
  File could not be read  UnityEditor.AssetDatabase:CreateAsset(Object,
  String)  Editor.TextureImportWindow:OnGUI() (at
  Assets/Scripts/Editor/TextureImportWindow.cs:40)
  UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

My code:
 public class TextureImportWindow : EditorWindow
 {
     [MenuItem("Window/Pixel Terrain/Import Texture")]
     public static void ShowWindow()
     {
         GetWindow<TextureImportWindow>("Import Texture");
     }

     private Texture2D _texture;
     private string _path;

     private void OnGUI()
     {
         if (GUILayout.Button("Select File"))
         {
             _path = EditorUtility.OpenFilePanel("Choose texture", "", "png");
             if (_path.Length != 0)
             {
                 var www = new WWW("file:///" + _path);
                 _texture = Texture2D.blackTexture;
                 www.LoadImageIntoTexture(_texture);
             }
         }

         if (_texture != null)
         {
             if (GUILayout.Button("Import"))
             {
                 if (!AssetDatabase.IsValidFolder("Assets/Textures"))
                 {
                     AssetDatabase.CreateFolder("Assets", "Textures");
                 }
                 AssetDatabase.CreateAsset(_texture, "Assets/Textures/importedTexture12.png");
                 AssetDatabase.SaveAssets();
                 AssetDatabase.Refresh();
             }
         }
     }
 }

A:

First of all, AssetDatabase.CreateAsset supports few extensions and png is not one of them. According to the doc, these are the supported formats:

.mat for materials
.cubemap for cubemaps
.GUISkin for skins
.anim for animations
.asset for arbitrary other assets.)

PNG is not mentioned anywhere so you get error when you try to import it with that function. AssetDatabase.ImportAsset is more appropriate for this but since it requires a relative path, it won't work because you are using an absolute path provided from EditorUtility.OpenFilePanel.
To import png file into your project from EditorUtility.OpenFilePanel, just copy it to the destination with  File.Copy or FileUtil.CopyFileOrDirectory(Recommended) then call AssetDatabase.Refresh().
Replace:
AssetDatabase.CreateAsset(_texture, "Assets/Textures/importedTexture12.png");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();

with:
FileUtil.CopyFileOrDirectory(_path, "Assets/Textures/importedTexture12.png");
AssetDatabase.Refresh();


Q:

Regex for matching a previous group in the pattern?

I can never seem to find any documentation on the regex for matching a capture group as part of the pattern. For example:
(\w\d\w):$1

..should match a4b:a4b
$1 doesn't work, but I know it's something similar. Anyone know?

A:

In a regex pattern, a backreference to the first capturing group is always \1, not $1.
Reason: $ means "end of string" (or end of line, depending on context) in a regex.
In a replace pattern (which isn't a regex), some dialects allow $1 (e. g. .NET, Java, Perl and JavaScript), some allow \1 (Python and Ruby), and some allow both (PHP and JGSoft).
Edit: Since you wrote that you couldn't find any documentation on this, check out these overviews on regular-expressions.info:

Grouping and Backreferences
Regex Replacement Syntax


Q:

jboss as 7 + jersey - ClassNotFound com.sun.jersey.server.impl.container.servlet.Include

I migrating project on jboss as 7 from jersey version 1.9 to 1.17 and I get the following exception:
12:05:48,573 WARN  [org.jboss.as.ee] (MSC service thread 1-10) JBAS011006: Not installing optional component com.sun.jersey.server.impl.container.servlet.Include due to except
ion: java.lang.ClassNotFoundException: com.sun.jersey.server.impl.container.servlet.Include from [Module "deployment.ApiEar-2.0.0-SNAPSHOT.ear.ApiService-2.0.0-SNAPSHOT.war:ma
in" from Service Module Loader]
        at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
        at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
        at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
        at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:423)
        at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
        at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
        at java.lang.Class.forName0(Native Method) [rt.jar:1.6.0_32-ea]
        at java.lang.Class.forName(Class.java:247) [rt.jar:1.6.0_32-ea]
        at org.jboss.as.server.deployment.reflect.DeploymentClassIndex.classIndex(DeploymentClassIndex.java:54)
        at org.jboss.as.ee.component.deployers.EEModuleConfigurationProcessor.deploy(EEModuleConfigurationProcessor.java:81) [jboss-as-ee-7.1.2.Final-redhat-1.jar:7.1.2.Final-
redhat-1]
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:116)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_32-ea]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_32-ea]
        at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_32-ea]

code runs fine under 1.9. Here are my dependencies:
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.9.1</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.9.1</version>
</dependency>

what could cause such an exception?

A:

I think your problem is related to the fact that Jersey was changed quite a bit from version 1.9 to 1.10; namely there was a big change to Servlet functionality. You can read more here: Jersey 1.10 released
As far as your problem goes, I think you simply missing some dependencies. I know I had to add the following to my .pom file:
        <!-- Jersey 1.17 dependencies -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey-version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
            <scope>compile</scope>
        </dependency>
        <!-- end Jersey 1.17 dependencies -->


Q:

SQL if statement within WHERE clause

I want to do the following query, how can I implement it?
SELECT * FROM table WHERE routeNum LIKE 'N10%'
-->if no rows return, WHERE clause change to routeName LIKE '&something%'

A:

I think this will work for you:
WITH CTE AS (
    SELECT 2 AS 'INDEX', * FROM table WHERE routeNum LIKE 'N10%'
    UNION ALL
    SELECT 1 AS 'INDEX', * FROM table WHERE routeNum LIKE '&something%'
)
SELECT *
FROM CTE
WHERE CTE.INDEX = (SELECT MAX(INDEX) FROM CTE)

As you have to choose between two result sets, you will need two queries, which will return two different sets and then, based on the 'index' which corresponds to the query that has run, you choose how to display your results.
Here is a SQLFiddle demo.


Q:

Controlling the background in Python's matplotlib

I want to have blank background in my figure, however, it seems that the for some reason the default is not. Here is an example:
import matplotlib.pyplot as plt
x=[1,2]
y=[3,4]
plt.plot(x,y)

This gives me the following figure:

Why do I get this gridded grey background by default? How would one change the default? And perhaps also how would that differ from setting it only for one figure without changing defaults? Thanks
Edit: Apparently, this happened because I imported the seaborn module, as the answer suggested. But why does this behavior occur? So if I want to use both seaborn and matplotlib in one script, I need to keep setting the default background?

A:

What you show in the question isn't actually the matplotlib default style. You may get this because you may have imported some other modules.
To get back the default style use
plt.rcParams.update(plt.rcParamsDefault)

When e.g. seaborn is imported it sets its own style. This is a very greedy behaviour, but you can of course set another style afterwards
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-paper')

You may want to look at the style reference.
This question may be of interest when no other style is desired. The idea is, to only load the API, without the styles from seaborn
import seaborn.apionly as sns


Q:

php Cookie not working, won't get set

When I submit the form to the action processing script, I am supposed to set the cookie. But the cookie doesn't get set.
<input type="email" name="fes-email" class="fes-input" value="<?php echo $_COOKIE['hotspot-user-email']; ?>" placeholder="Еmail">

This is found on the processing script page.
setcookie('hotspot-user-email', $_POST['fes-email'], time() + (86400 * 30), 'domain.tld');

What I am attempting is to save the email address in a cookie, so that the next time the user returns the address will be echoed in the input field.
Is there a problem with my code?
if(!empty($_POST['fes-email'])) {

            if (filter_var($_POST['fes-email'], FILTER_VALIDATE_EMAIL)) {

                setcookie('hotspot-user-email', $_POST['fes-email'], time() + (86400 * 30), '/'); // 86400 = 1 day

            }else { echo("EMAIL IS NOT VALID"); }

        }else { echo("EMPTY FIELD"); }

A:

Following is the simplest snippet that does the magic
<?php
  if (isset($_COOKIE['testCookie'])) {
      echo "
 Cookie is set: " . $_COOKIE['testCookie'] ."
";
  } else {
      if (setcookie('testCookie','myemail@mydomain.com', time() + 86400)) {
          echo "
 cookie is set
";
      }
  }
?>


Q:

Expose a web service (wsdl) as a webform

Just wanted to ask if anyone knows of a reliable & easy way to expose a webservice (wsdl) as a webform to end-users.
Our team develops a lot of software for external contacts, which often involve creating a web service and exposing it as both a wsdl and a website. We'd like to automate this last step as much as possible (especially for the mindless data-pumping projects) so we can concentrate on developing web services instead of websites.
I recently came across Enunciate, but have not found the time yet to play with it in detail. I was wondering if anyone has any experience with it  (or with any similar projects) what your findings are, and what direction you would advice us to take with this.
Best regards,
Tim

Update2:
Turns out what I need is perfectly described in this Enunciate module: http://jira.codehaus.org/browse/ENUNCIATE-23. The only problem is that it's not implemented... (yet?)
Anyone have any experience in creating your own modules, or knows of an existing solution that provides the same functionality?

A:

I'm not sure how much weight my response carries (since I'm the lead developer of Enunciate) but I'd like to encourage you to try it out. I know a lot of happy Enunciate users.
Even if you decide not to use it, I'd like to hear about your experience and why you decided against it.


Q:

Reference Excel cells in Word

Does anyone know of a pre-packaged solution for referencing Excel cells directly in a Word document?
For example,

                                                         {[TestExcel]Tab1!A1}

Dear Mr. {[TestExcel]Tab1!A2},
Our systems have alerted us that your account {TestExcel]Tab1!AccountNumber} is overdue. Please remit payment of {TestExcel]Tab1!PaymentDue} immediately.

This example uses a hypothetical { } syntax, where the contents are standard Excel formula.
Every solution I've seen uses custom VBA to accomplish this. It seems like an extremely common need for which there should be some good 3rd party software available that lets non-technical users accomplish this task.
As indicated in the example above both named ranges and standard cell references would need to be supported.

A:

Yes.
Step 1: Copy the excel cell.
Step 2: Go to your word document where you want to paste the reference.
Step 3: Right click
Step 4: Under paste options, select  "link with source formatting" or "link and merge formatting".

A:

I tried @Green Demon's method, but the two Paste Options listed were not present for me (Office 2013). I only had Keep Source Formatting, Merge Formatting, and Keep Text Only. However, I poked around and found the Paste Special, which was hidden on the Ribbon
The instructions are as follows:

Copy the Excel range.
Go to your Word document, and left click where you want to paste the Excel range.
Click on Paste Special from the Ribbon as shown below, or type Ctrl+Alt+V.

Click on the Paste link radio button.
Click on Microsoft Excel Worksheet Object. The Paste Special dialog box should look something like this:

Click OK.

The range should now be pasted in your document, and if you save, close, and re-open the Word document, you will be prompted about whether or not you want to "update this document with the data from the linked files," which works the same way as it does if you're doing Excel-to-Excel linking.
This feature is fantastic, and I'm so happy to have found it today. However, in my brief experience using it, having these Word-to-Excel links dramatically increases the amount of time it takes to open your Word document, even before it prompts you about updating. After that, the act of updating the Excel links takes much longer than it would if you were doing the same linking Excel-to-Excel. All of my work is done on network-share files, so YMMV.


Q:

inheriting from a class declarations in c++

When you want to inherit from a class in C++, is it illegal to have std declared in the first line below?
#ifndef HWEXCEPTION_H
#define HWEXCEPTION_H

#include <stdexcept>

class HWException : public std::run_time_error
{
    void testException(int num);
};

#endif

vs
using std::run_time_error
class MyClass : public run_time_error

This is assuming you have #include  at the top.  I get compile errors for having std::run_time_error, but do not seem to by doing it the second way and was wondering why.
 error C2039: 'run_time_error' : is not a member of 'std'
 'run_time_error' : base class undefined
1>main.cpp
 error C2039: 'run_time_error' : is not a member of 'std'
 error C2504: 'run_time_error' : base class undefined

A:

Both are legal. But assuming this is in a header file, you should not use the using directive version, as it places the name in the global namespace, which may cause problems for users of your header.
Edit: Just noticed that you have the class name wrong:
#include <stdexcept>
class MyClass : public std::runtime_error {
};

is what you need.


Q:

Derivative of a function along a path

I'm having problems visualizing and understanding the chain rule for the derivative of a function along a path. i.e $$\frac{df(r(t))}{dt}=\nabla f(r(t))\cdot r'(t)$$
My thinking is that this result should be zero as $\nabla f$ is an orthogonal vector and $r'(t)$ is a tangent vector to the surface. I know I am wrong but I can't see how? If anyone can enlighten me I'd appreciate it.

A:

If the path parametrized by $\vec{r}(t)$ happens to be a contour of $f$, then (as you say) $\nabla f$ will be perpendicular to the curve and therefore perpendicular to $\vec{r'}(t)$.  Therefore, the derivative will be zero.  Another way to see this is that $f$ is (by definition) constant along a contour, thus (again) the derivative will be zero.
More generally, however, $\vec{r}$ may parametrize some arbitrary path, not necessarily a contour.  That is when the formula is relevant.


Q:

How can I use ObjectAnimator parameters to adjust for all devices?

I want to use ObjectAnimator to move a textView in the Y axis.This code works but it is not suitable for every device because of the screen sizes.
   ObjectAnimator mover = ObjectAnimator.ofFloat(expand, "translationY", -250, 0);

How can I change the last two parameters?There are also similar questions there I tried these also but they don't work.

A:

There are 2 cases:

You want to move your view so that it takes some defined position relatively to another view. In that case you should make your calculations based only on position of those views (see getTop(), getLeft(), etc.)
You want your views to move some defined physical distance of the screen (which is your case I guess), so user will percept it as movement. In such case you should use device-independent-pixels (dp) instead of raw pixels (-250 in your case). ObjectAnimator itself does not support such conversion, so you have to do it by yourself. The easiest way (to write, read and support) is to store such value in dimensions resources and get them through getResources().getDimensionPixelOffest() method


Q:

What is difference between point and hitTest and how i can use hitTest?

I want add area of touch to my scrollView and i have the scrollView inside container view. the page of scrollView is less that container. I find a lot in internet how is the use in Swift 4.2 but nobody explain how use step by step the hitTest. What i hava do when i do the subclass of type UIView? How use this class after in the class that have the scroolView or the containerView?
Thanks.
This is the code.
import UIKit

struct scrollViewDataStruct {
    let title: String?
    let image: UIImage?
}

class PaymentsOptionsController: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var scrollView: UIScrollView!
    var scrollViewData = [scrollViewDataStruct]()

    override func viewDidLoad() {
    super.viewDidLoad()
    self.scrollView.delegate = self

    scrollViewData = [scrollViewDataStruct.init(title: "First", image:  #imageLiteral(resourceName: "amex")),scrollViewDataStruct.init(title: "Second", image:  #imageLiteral(resourceName: "chase-debit-card_front")),scrollViewDataStruct.init(title: "Third", image:  #imageLiteral(resourceName: "amex"))]
    scrollView.contentSize.width = self.scrollView.frame.width * (CGFloat(scrollViewData.count) + 1)
    var i: CGFloat = 0
    var j: CGFloat = 1
    let halfInterSpacing: CGFloat = 10.5
    let viewWidth : CGFloat = 305
    let viewOptions = PaymentMenuViewController(frame: CGRect(x: (halfInterSpacing * j) + viewWidth * i, y: 0, width :  viewWidth, height: self.scrollView.frame.height))
    self.scrollView.addSubview(viewOptions)
    i += 1
    j += 2
    for data in scrollViewData{
        let view = CustomView(frame: CGRect(x: (halfInterSpacing * j) + viewWidth * i, y: 0, width :  viewWidth, height: self.scrollView.frame.height))
        view.imageView.image = data.image
        self.scrollView.addSubview(view)

        i += 1
        j += 2
    }
    self.scrollView.clipsToBounds = false
    }

    class CustomView: UIView {
        let imageView : UIImageView = {
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.backgroundColor = UIColor.white
        imageView.contentMode = .scaleAspectFit
        return imageView
        }()

        override init(frame: CGRect) {
            super.init(frame: frame)
            self.addSubview(imageView)
            imageView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
            imageView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
            imageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        }

        required init?(coder aDecoder: NSCoder) {
             fatalError("aaa")
        }
    }
}

class PassThruScrollView: UIScrollView {

    var passThruViewRef: UIView?

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool    {

    return point.y > passThruViewRef?.frame.height ?? 0

    }

}

Imagen from my stroyBoard

A:

If you want the hitTest for the scroll view to recognize gestures outside of the scroll view, you need to convert the coordinate to the coordinate system of the current view:
class CustomScrollView: UIScrollView {
    var referenceView: UIView?   // if you leave this `nil`, it will assume `superview`

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let view = referenceView ?? superview!

        let frame = convert(view.bounds, from: view)
        return frame.contains(point) ? self : nil
    }
}

FWIW, this works fine on the device but behaves strangely on the simulator, so use at your own risk.
But below I scrolled while doing gestures in the gray area, outside of the scroll view:


Q:

Is it possible to have Stream as a parameter to a WCF Data Service Operation?

Please note this question is specific to WCF Data Services not normal Wcf Service.
I'm trying to upload a file to the service without any luck.
As soon as I add the following code:
[WebInvoke(Method = "POST")]
public void UploadPic(Guid id, Stream fileContents)
{
    myImageSaver.SaveImageFromStream(fileContents);
}

My whole data service crashes. I cannot query any of the entity sets. I just get the Blue WCF Screen of death.

A:

It's not possible to pass a stream as a prameter to a service operation, only primitive types are supported as parameters to service operations. The proper way of supporting streams in WCF Data Services is to use either the MLE/MR functionality. Take a look at this blog series for a detailed walkthrough of how to implement such service:
http://blogs.msdn.com/b/astoriateam/archive/2010/08/04/data-services-streaming-provider-series-implementing-a-streaming-provider-part-1.aspx


Q:

Best way to handle monthly subscription allowance with Stripe?

What will be the best pratice to compute monthly allowance of our service when using a Stripe monthly subscription?
I can see 2 strategies:

Add usage to a monthly usage hash (ie. {month_1: 342, month_2: 20}). Calculate current month based on the Stripe subscription start date. Kind of ignore variance in Stripe subscription actual renewal dates, and require manual intervention to block a customer if renewal doesn't go through.
Have a monthy_allowance (credit counter still avaiable for the current month) variable that is replenish when Stripe fires the successful subscription renewal web hook. It's more tie to the actual subscription status, but I can see being an issue as it seems harder to test and subject to bugs if the web hook doesn't properly receive the event. Can be an issue if some customers got locked out until we manually allow them back in.

I suppose it doesn't really matter in this question, but we are using Ruby on Rails with MongoDB as backend.

A:

If you're talking about having some kind of 'usage credit' that your users will 'use up', and that is replenished when a Subscription charge is made, I think you could likely handle this by just having a bucket (like, a counter) that you draw down when they use something, and you fill up when the Subscription is successfully paid, and where you block them (or provide a way to buy more) when the bucket hits zero.
Does that make sense?


Q:

Unit Test a private field which is behavior relevant

first of all: I found few solutions for my problem but the "newest" one was from 2014 and used reflections so I hope I could maybe find some more advanced solutions for my question.
Thats the case and its about migrateUser and canAdd. This is an example class to make my question easily visible.
public class UserInterfaceImpl implements UserInterface {

    private final List<T> accountList = new LinkedList<>();
    private final AccountInterface accountInterface;
    private boolean bonusReceived = false;

    public UserInterfaceImpl(AccountInterface accountInterface) {
        this.accountInterface = accountInterface;
    }

    public void migrateUser(AccountMergerInterface accountMerger, UserInterface oldUser) {
        boolean success = accountMerger.performChange(this, oldUser);
        if (success && !bonusReceived) {
            //addBonus
            accountInterface.deposit(1);
            bonusReceived = false;
        }
    }

    public boolean canAdd() {
        return accountList > 0;
    }

    public AccountInterface getAccount() {
        return accountInterface;
    }
}

The migrateUser method changes the some account Data which is not relevant for my test because I would test it separately of course (should be like that what I read so far).
So I wonder, how can I see if the behavior of that class changes the bonusReceived correctly? Without using reflections and do it as sophisticated as possible?
My first attempt was that:
@Test
public void testMigrateUser() {
    AccountMergerInterface test = mock(AccountMergerInterface.class);

    // define return value for method getUniqueId()
    when(test.performChange()).thenReturn(true);
}

But now I cannot continue. The rule should be in my example to have no getter and setter! The class should be like my example.
I don't know how to:

set bonusReceived to false before migrateUser is executed that accountInterface.deposit(1); is not executed
see if bonusReceived will be set to false if the if() continue is true.
Same questions for the List: how can I access the private field of List, add an Object so that the return value is true or false. Or should I "simulate" a List and if yes, how can I do that?

Thanks in advance!

A:

Unit tests check public observable behavior.
There is no point in verifying internal state of an object since this may change to support other behavior. You don't want to change your unit test in that case...
So mock the AccountMergerInterface  (as you already did) and the AccountInterface and verify that your class under test calls the methods on them in the right order with the right parameters:
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private AccountMergerInterface accountMergerInterface;
@Mock
private AccountInterface accountInterface;
@Test
public void testMigrateUser() {
    // arrange
    when(test.performChange()).thenReturn(true);
    // act
    new UserInterfaceImpl(accountInterface).migrateUser(accountMergerInterface);
    // assert
   InOrder inOrder Mockito.inOrder(accountMergerInterface, accountInterface);
   inOrder.verify(accountMergerInterface).deposit(1);
   inOrder.verify(accountInterface).whatEverToCallNext();
}

Same questions for the List:

There is currently no code dealing with the list in UserInterfaceImpl.
You cannot verify behavior which is not there...


Q:

Using include inside loop to send mail

I am trying to have my loop insert into the database 6 records automatically, the only thing that changes is the dates of these records, and whenever it enters it has to send an email with the always updated data, but the only one thing I got was to make it send only 1 email, and this email only has the last loop information.
The idea is to send an email whenever you insert it into the DB
Here is the code test:
<?php
$replace1="27-02-2019 00:00";
$replace2="27-02-2029 00:00";
$strStart = '2019-09-10';
$strEnd = '2029-09-10';
$dteStart = new DateTime($strStart);
$dteEnd   = new DateTime($strEnd);
$dteDiff  = $dteStart->diff($dteEnd);
$anos=$dteDiff->format("%Y");
$dias=$dteDiff->format("%d");
$meses=$dteDiff->format("%m");
$repete = ($anos * 12);
$rotina="6";
if($rotina == "6"){
    $assunto = "Rotina Semestral";
    $repete = ($repete / 6);
     for($i = 0; $i <= $repete; $i++){
        echo $i."==".$replace1." - ";
        echo $replace2."
";
        $replace1 = date('d-m-Y H:m',strtotime($replace1." +6 Months"));
        include('email1.php');
    };
}elseif($rotina == "3"){
   //code...
   };
}elseif($rotina == "1"){
    $repete = $anos;
     for($i = 0; $i <= $repete; $i++){
        //code...
    };
};

Here is email1.php:
<?php
 $path = $_SERVER['DOCUMENT_ROOT'] . '\dist\PHPMailer_5.2.0\\';
 $file = $path . 'class.phpmailer.php';
 include($file);

   $mail = new PHPMailer();
   $mail->CharSet = 'UTF8';

   $mail->IsSMTP();
   $mail->Host = "$smtp";
   $mail->SMTPAuth = false;

    $mail->From = "$emailhost";
    $mail->FromName = "Nova tarefa  SIGMA ";
    $mail->AddAddress ($email_post);

    $mail->WordWrap = 99999;
    $mail->IsHTML(true);

    $mail->Subject = "Nova tarefa SIGMA WO/NF/ID Cliente: ".$won1;
    $mail->AddEmbeddedImage('img/baixo.png', 'baixo');
    $mail->Body    = "

Informação do Pedido - Novo Pedido

                      WO/NF/ID Cliente:

                      $won

                      Responsável do pedido:

                      $res_2

                      Técnico 1:

                      $tec1_1

                      Cliente:

                      $cli

                      Vazio

                      Vazio

                      Técnico 2:

                      $tec2_2

                      Descrição da Tarefa:

                      $descre

          Bom Trabalho! →

  ";
                   $mail->Send();

A:

I cant't test it for the moment but the new file will be something like this
<?php
 $path = $_SERVER['DOCUMENT_ROOT'] . '\dist\PHPMailer_5.2.0\\';
 $file = $path . 'class.phpmailer.php';
 **include_once($file);**
 function my_send_mail($smtp,$emailhost,$email_post,$won1,$won,$res_2,$tec1_1,$cli,$tec2_2,$descre){
   $mail = new PHPMailer();
   $mail->CharSet = 'UTF8';

   $mail->IsSMTP();
   $mail->Host = "$smtp";
   $mail->SMTPAuth = false;

    $mail->From = "$emailhost";
    $mail->FromName = "Nova tarefa  SIGMA ";
    $mail->AddAddress ($email_post);

    $mail->WordWrap = 99999;
    $mail->IsHTML(true);

    $mail->Subject = "Nova tarefa SIGMA WO/NF/ID Cliente: ".$won1;
    $mail->AddEmbeddedImage('img/baixo.png', 'baixo');
    $mail->Body    = "

Informação do Pedido - Novo Pedido

                      WO/NF/ID Cliente:

                      $won

                      Responsável do pedido:

                      $res_2

                      Técnico 1:

                      $tec1_1

                      Cliente:

                      $cli

                      Vazio

                      Vazio

                      Técnico 2:

                      $tec2_2

                      Descrição da Tarefa:

                      $descre

          Bom Trabalho! →

  ";
                   $mail->Send();
 }

and your default file will be
<?php
include('email1.php');
$replace1="27-02-2019 00:00";
$replace2="27-02-2029 00:00";
$strStart = '2019-09-10';
$strEnd = '2029-09-10';
$dteStart = new DateTime($strStart);
$dteEnd   = new DateTime($strEnd);
$dteDiff  = $dteStart->diff($dteEnd);
$anos=$dteDiff->format("%Y");
$dias=$dteDiff->format("%d");
$meses=$dteDiff->format("%m");
$repete = ($anos * 12);
$rotina="6";
switch($rotina){
case "6":
    $assunto = "Rotina Semestral";
    $repete = ($repete / 6);
     for($i = 0; $i <= $repete; $i++){
        echo $i."==".$replace1." - ";
        echo $replace2."
";
        $replace1 = date('d-m-Y H:m',strtotime($replace1." +6 Months"));

        my_send_mail($smtp,$emailhost,$email_post,$won1,$won,$res_2,$tec1_1,$cli,$tec2_2,$descre);
    };
    break;
case "3":
   //code...
break;
case "1":
    $repete = $anos;
     for($i = 0; $i <= $repete; $i++){
        //code...
    };
break;
}

But i don't know where you take the variable used inside the file mail1.php
I don't know what php lib you are using for sendmail but implemente exceptions in mail send http://php.net/manual/en/language.exceptions.php
Sorry for my bad english
Replace
$mail->Send()

whit this
try {
  if ( !$mail->Send() ) {
    $error = "Unable to send to: " . $to . "
";
    throw new phpmailerAppException($error);
  } else {
    echo 'Message has been sent using <?php echo strtoupper($_POST['test_type']); ?>

';
  }
} catch (phpmailerAppException $e) {
  $errorMsg[] = $e->errorMessage();
}

if ( count($errorMsg) > 0 ) {
  foreach ($errorMsg as $key => $value) {
    $thisError = $key + 1;
    echo $thisError . ': ' . $value;
  }
}


Q:

Angular -Js $http.post not working in django

I have just started Django and what I was trying to implement $http.post method of angular to post form data to my Django database,and my further plan was to update the view to display the results without page refresh.so what i thought to post data in django db and then my view function will return a jsonresponse,of that posted data which i can use to update the view using $http.get method.
But the problem is occuring with me is whenever i post data it is not able to post the data and returning an empty json response.
Here is my codes which i am working on:-
urls.py
from django.conf.urls import url
from . import views
app_name='demo'
urlpatterns=[
    url(r'^$',views.index,name="index"),
    url(r'^add_card/$',views.add_card,name="add_card")

]

views.py
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .forms import CardForm
from .models import Card
# Create your views here.

def add_card(request):
    saved = False
    if request.method == 'POST':
        #print('hi')
        form = CardForm(request.POST)
        #print('hi')
        if form.is_valid():
            #print('hi')
            card = Card()
            #print('hi')
            card.content = form.cleaned_data['content']
            #print('hi')
            saved = True
            card.save()
            #print('hi')
        return JsonResponse({'body':list(q.content for q in Card.objects.order_by('-id')[:15])})

    else:
        return HttpResponse(
            json.dumps({"nothing to see": "this isn't happening"}),
            content_type="application/json"
        )

def index(request):
    return render(request,'demo/index.html',{'form':CardForm()})

controller.js
var nameSpace = angular.module("ajax", ['ngCookies']);

nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies',
function ($scope, $http, $cookies) {
    $http.defaults.headers.post['Content-Type'] = 'application/json';
    // To send the csrf code.
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.get('csrftoken');

    // This function is called when the form is submitted.
    $scope.submit = function ($event) {
        // Prevent page reload.
        $event.preventDefault();
        // Send the data.
        var in_data = jQuery.param({'content': $scope.card.content,'csrfmiddlewaretoken': $cookies.csrftoken});
        $http.post('add_card/', in_data)
          .then(function(json) {
            // Reset the form in case of success.
            console.log(json.data);
            $scope.card = angular.copy({});
        });
    }
 }]);

My models.py:-
from django.db import models

# Create your models here.
class Card(models.Model):
    content = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.content

My forms.py-
from django import forms
from .models import Card

class CardForm(forms.ModelForm):
    class Meta:
        model = Card
        fields = ['content']

A:

You have some problems in your view.py code.

You need to create a new object in your database from the request data
You need to return the new data as a response
if form.is_valid():
    new_content = form.cleaned_data['content']
    card = Card.objects.create(content=new_content)
    return JsonResponse(
           list(Card.objects.all().order_by('-id').values('content')[:15]),
           safe=False
    )

That should return a list of the content value of your first 15 objects in your Card table after creating a new object in that table by the content provided, IF your form is valid.
Also your CardForm should be defined as follows:
class CardForm(forms.ModelForm):
    class Meta:
        model = Card
        fields = ('content',)

Finally, your $http.post call is asynchronous, which means that when the .then is reached, there is a probability (almost a certainty) that the post request has not been resolved yet, thus your json.data is empty. To solve this problem:
$http.post('add_card/', in_data)
    .then((json) => {
        // Reset the form in case of success.
        console.log(json.data);
        $scope.card = angular.copy({});
});

A far better read and solutions on the asynchronous-to-synchronous calls are: ES6 Promises - Calling synchronous functions within promise chain, How do you synchronously resolve a chain of es6 promises? and Synchronous or Sequential fetch in Service Worker

Good luck :)


Q:

How to prevent accidental publishing of a private pub package

When I have a package that I absolutely won't publish to pub.dartlang.org, how can I prevent someone accidentally publishing it?

A:

add

publish_to: none

to your pubspec.yaml.
This setting can be used to specify a custom pub package server to publish to and none prevents publishing.


Q:

Did the bible make any prediction of what Jewish law should do if a transsexual woman with a real vagina existed?

Did the Bible make any predictions of what Jewish marriage law would rule on the subject of a transsexual woman with a real vagina if a Jewish men wanted to or did marry him?
Should Jewish law continue to ban the relationship if tall transsexual women may possibly exist who might be pretty tempting to every Jewish man?

A:

No. The Bible made no such prediction.


Q:

What cross browser css do I need to switch image/animated logo

Basically I have an animated svg logo that works lovely in all browsers apart from Edge, so was wondering if there is a way to change it to a static svg when viewed on Edge or if anyone has an Edge fix for an animated svg?
Quite new to all of this and used a animated svg generator to produce the svg but am at a loss to know the best thing to fix this..?

It is the main logo and the current result can be found here: https://ethostec.net/

A:

this could be done simply by using JS or PHP :
JS :

PHP :
<?php
    if (preg_match('/Edge/i', $_SERVER['HTTP_USER_AGENT'])) {
        //It's Edge and you have to show the static logo
    }
?>


Q:

ViewPager does not show correct page

I have a viewPager and I add fragments inside it.
At first I have 4 fragments, showing the last one. 5, 6, 7 ,8
When I reach the first fragment. I make a Api Call, get the data for another 4 earlier fragments: 1,2, 3, 4. And I set the last one as vizible.
My issue is that going through them. I get this: 8, 7 ,6 ,5, 8, 7, 6, 5.
If I exit and reenter the fragment, it works fine. but always the first time, it seems to have the other fragments cached somehow?
This is how I create the fragments:
 private List<PSActivityFragment> getFragments(){
    UserRecord profile = UserRecord.getMyUser(PSProfileActivity.this);
    CrudStateCallback crudStateCallback = new CrudStateCallback() {
        @Override
        public void onResponse(String string) {
        }
    };
    List<PSActivityFragment> fList = new ArrayList<PSActivityFragment>();
    if(profile != null) {
        loader.setVisibility(View.GONE);
        if(profile.getMonths().size() > 0) {
            for (PSUserActivityMonth month : profile.getMonths()){
                Log.i("","month is fragments created are:" + month);
                PSActivityFragment psaf1 = new PSActivityFragment();
                psaf1.init(month, crudStateCallback);
                fList.add(psaf1);
            }
        }
    }else{
        loader.setVisibility(View.VISIBLE);
    }
    return fList;

}

Each time I get new data. I recreate the adapter:
  pager.removeAllViews();
    pager = null;
    pager = (ViewPager) findViewById(R.id.viewpager);
    final List<PSActivityFragment> fragments = getFragments();
    myPagerAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
    pager.setAdapter(myPagerAdapter);

I tried instead of recreating and setting the adapter again to just set the fragments to the adapter again, and call notifyDataSetChanged. But still, I get the same issue. Are the fragments cached somewhere? why does this happen?
I checked the log and the fragments are created in the normal order:
 06-02 14:16:21.514: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=11, year=2015, weeks=1}
 06-02 14:16:21.515: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=12, year=2015, weeks=5}
 06-02 14:16:21.515: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=1, year=2016, weeks=5}
 06-02 14:16:21.515: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=2, year=2016, weeks=5}
 06-02 14:16:21.515: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=3, year=2016, weeks=5}
 06-02 14:16:21.516: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=4, year=2016, weeks=5}
 06-02 14:16:21.516: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=5, year=2016, weeks=6}
 06-02 14:16:21.516: I/(14192): month is fragments created are:PSUserActivityMonth{category='u/23', month=6, year=2016, weeks=1}

These are months: I should see after cycling through the pager this:
june 16, may 16 , april 16 , march 16 (first for) and then feb 16, jan 16, dec 15, nov15.
Instead I see: june 16, may 16 , april 16 , march 16 (first for) and then june 16, may 16 , april 16 , march 16 again
Adapter code:
public class MyPageAdapter extends FragmentPagerAdapter {

private List<PSActivityFragment> fragments;

public MyPageAdapter(FragmentManager fm, List<PSActivityFragment> fragments) {
    super(fm);
    this.fragments = fragments;
}

@Override

public Fragment getItem(int position) {
    return this.fragments.get(position);
}

@Override

public int getCount() {
    return this.fragments.size();
}

}

PS: My activity extends fragmentActivity, and I ma using a getSupportFragmentManager as you can see when I create the adapter. Could this be the issue?

A:

using a Activity with FragmentActivity and getSupportFragmentManager. I thought that that might be the issue so I  did this:
 if(getSupportFragmentManager() != null && getSupportFragmentManager().getFragments() != null){
        getSupportFragmentManager().getFragments().clear();
    }

And now it works!!!


Q:

Is there a way of making a button that was generated through a for loop span two colums

I have been creating buttons through a for loop for a calculator. However, I'd like to make two buttons span two columns.
I know that by creating individual buttons we can write
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor = "hand2",activebackground = "#1E90FF", command = lambda: btn_eval(0))
zero.grid(row = 5, column = 0, columnspan = 2, padx = 1, pady = 1)

 buttons = ['M+', 'M-', 'MR', 'MC',
            'CA', 'Del', '/', 'hi',
            '7', '8', '9', '*',
            '4', '5', '6', '-',
            '1', '2', '3', '+',
            '0', '.', '=', 'bye'
               ]
          count = 0

          for row in range(2, 10):
               for column in range(4):
                    button = Button(window, width = 10, fg = "black", height = 3, bd = 0, bg = '#fff',
                                    cursor = 'hand2', activebackground = '#1e90ff', text = buttons[count],
                                    command = lambda i=buttons[count]: self.functions(i)).grid(row=row, column=column)
                    count += 1

I am just putting "hi" and "bye" just to keep space but the buttons that I want to span 2 columns are "CA" and zero

A:

Using a ternary condition (or a simple if) to set the columnspan accordingly should be possible:
buttons = ['M+', 'M-', 'MR', 'MC',
            'CA', 'xxxxx', 'Del', '/',  # the xxxxx will be skipped
            '7', '8', '9', '*',
            '4', '5', '6', '-',
            '1', '2', '3', '+',
            '0', 'xxxxx', '.', '='
               ]
count = 0

for row in range(2, 10):
    for column in range(4):
        if (row,column) in [(3,1),(9,1)]: # the xxxxx positions, no need to make a button
            continue
        cs = 2 if buttons[count] in ("0","CA") else 1
        button = Button(window, width = 10, fg = "black", height = 3, bd = 0, bg = '#fff',
                        cursor = 'hand2', activebackground = '#1e90ff',
                        text = buttons[count],
                        command = lambda i=buttons[count]: self.functions(i)).grid(row=row,
                                                            column=column, columnspan = cs)
        count += cs # to make indexes still work as is, increase by 2 when needed


Q:

What is the point of 10k users seeing deleted stuff?

I know that 10k users are able to see deleted questions but what's the point of that?
A question is deleted because it is low-quality, off-topic or badly recieved. I guess the reason behind this is because the question should not be seen by new users because they can be misled about what is the correct style of a good question. Also, these "trash" should not be floating around everywhere, right?
Now you give the 10k users the privilage to view deleted questions. That kind of makes them "not deleted". They must be still in the database! Furthermore, if I were a 10k user, why would I bother to read deleted posts? They are bad anyways. And obviously I would not be curious to see how bad they are.

A:

Sometimes the mob gets it wrong.
Deleting content is something that should be done under the most extreme cases; that is, the content on the site would be more harmful if it were undeleted.
Allowing a 10K user to see posts like that allow them to step in and cast a vote to reverse the decision in case it truly was in error.

That kind of makes them "not deleted". They must be still in the database!

The term is soft deletion.  It means that the data is still around in case it needs to be audited, but isn't generally visible to the public.

A:

Just because a post happens to be deleted doesn't imply it's was no good, users who have over 10K reputation are allowed to cast an un-delete vote if they believe the question should not of been removed. With enough votes this will restore the question.
Also it is actually rare for items that where "removed" to actually be deleted from the database right away, mainly because by design we do not trust our users. Basically meaning when you develop a website on you try your best to protect the user from themselves. So if they removed something by mistake it can retrieved (restored) it in some way.


Q:

How to write this snippet more clean

In a turn-based game, I'd like to find the previous player.
To find the next player, I can just type:
int lastPlayer = match.currentPlayer - 1;

The problem is when the currentPlayer is player 1. Then lastPlayer becomes 0, which is wrong. It should be player6.
To fix this, I can do:
    int lastPlayer = match.currentPlayer - 1;

    if (lastPlayer == 0)
        lastPlayer = match.numberOfPlayers;

My question is how to write this in a cleaner way. I know game center, turn based code do something like:
    (currentIndex + 1) % match.participants.count];

How can I rewrite my code to do the same?
Thanks in advance

A:

How about that?
int lastPlayer = match.currentPlayer > 1 ? match.currentPlayer - 1 : match.numberOfPlayers;


Q:

Error loading msvcr100.dll (ErrorCode: 126) when webapp is deployed to Azure

I tried to update sql server types nuget package which updated this package to msvcr120.dll but still I am getting the same error:

Error loading msvcr120.dll (ErrorCode: 126)

Locally, its working fine. Also, I am pushing these dll.s with the build to Azure.
Below is a snapshot of the error when we try to access the deployed webapp.

A:

It May Because of You Missed SqlServerTypes in your Bin Folder
It Contains 2 Folders like x64 and x86 has Reference files SqlServerSpatial110.dll and msvcr100.dll
Include those 2 DLL's in your bin folder


Q:

Why do electrical storms cause metal objects to vibrate?

I am curious about the vibration of metal objects as a sign of an impending lightening strike. This is apparently a common occurrence; so much so that a quick google search will yield many pages instructing people to head for shelter if their keys (other other small metal objects) start to vibrate in the midst of an electrical storm.
One climbing site even mentions that a vibrating rope is a sign of a lightening strike.
Can someone explain the mechanism behind this? My guess is that it a piezo electric effect, though this contradicts my (limited) understanding that atmospheric electricity is static.
Thanks :)

A:

The lightnings primarily depend on strong electrostatic fields. They're up to 100 volts per meter in the summer and 500 volts per meter in the winter. These fields are fluctuating. When a certain critical threshold not far from those values is reached, a lightning strikes.
Does the electrostatic field move a metal?
There is no direct electrostatic force acting on the keys because they keys' total electric charge is basically zero. That's true even if the electric field of the thunderstorm depends on location and time.
However, the metallic object gets charged locally. The electric field polarizes the keys. It means that one side of the keys (measured relatively to the direction of the electrostatic field of the thunderstorm) is positively charged while the opposite side is negatively charged.
The total force acting on this polarized object would be zero if the electrostatic field were uniform and constant in time. But when the electric field is non-uniform (which may also be guaranteed by its being time-dependent because the signals only propagate by the speed of light), there will be a net force acting on the keys.
I am not able to produce any numbers now but the keys (or metallic object) get the charge $+Q$ coulombs in the upper part of the keys and the opposite charge $-Q$ coulombs on the lower side. Because the electric field depends on the altitude and oscillates, the electric field may be higher on the upper side of the keys than on the opposite one, and there will be a net force. The electric field may fluctuate. When the object is light enough relatively to the length in the relevant direction, the electrostatic force will be enough to move the keys or make them oscillate.
What really matters is some ratio of the length to the width etc. Even bad conductors may get polarized and exhibit the same effect – which is why long ropes, perhaps especially wet ones, can oscillate.


Q:

Does Linux support capturing tcp packets without being super user?

Is it possible to capture packets without superuser?
This is what I see in the wikipedia article:

In some Unix-like operating systems, a user must have superuser privileges to use tcpdump because the packet capturing mechanisms on those systems require elevated privileges. However, the -Z option may be used to drop privileges to a specific unprivileged user after capturing has been set up. In other Unix-like operating systems, the packet capturing mechanism can be configured to allow non-privileged users to use it; if that is done, superuser privileges are not required.
  http://en.wikipedia.org/wiki/Tcpdump

A:

It is possible to capture packets without being root, but you need to have the CAP_NET_ADMIN and CAP_NET_RAW capabilities. Basically you have to become root (so that you get all of the capabilities), then drop all of your capabilities except for those two, and drop root privileges too.
For managing the user ID that UNIX commands run as there are convenient tools like sudo. Unfortunately there are no standard tools to manipulate capabilities from the shell in the way that is required here.
This page describes what you need to do at the C level and this one contains a HOWTO to set up Wireshark to work this way.


Q:

Noise reduction in physiological measurements (EEG/ECG)

I am building a hobby EEG and I am interested in quantifying how effective are the various noise reduction techniques.
The basic circuit would be two electrodes going to an instrumentation amplifier. Then the signal goes to various filtering stages and then to a final "mundane" amplifier. I am interested in noise reduction before the filtering. Here are the steps that I am considering (hopefully this can evolve into a community wiki).

Adding a right leg electrode directly linked to the ground of the circuit. (against 60Hz hum)
Adding a driven right leg electrode for common mode rejection. (against 60Hz hum)
Adding passive low pass filters in front of the inputs of the instrumentation amplifier (see here). (against DC difference between the electrodes and bias current from the inputs)
Faraday cage (against 60Hz hum)
Shielded cables for the electrodes (against 60Hz hum)

Are there any technical manuals discussing these approaches? Could you share your knowledge about the effectiveness of each approach? Could you suggest other approaches?

A:

You want to look into all the documentation on the ModularEEG Design that is here. This is an open source/hardware project to build an EEG and has a wealth of information
You also want to take a look at this app note by TI that discusses dealing with noise in ECG.
Sidenote: Before you build anything taking bio-potential feedback please ensure that your circuit has sufficient isolation (via optocouplers, transformers or something else). Also try to design your circuit to run off two 9V batteries (+9V and -9V with current draw <100mA on the rails). These are good precautions when starting out to make sure you don't hurt yourself. Nerves are very sensitive and can be damaged by low voltage high frequency pulses that you won't even feel as a shock.


Q:

ASP Core PatchDocument returning Invalid Input

I want to use JsonPatchDocument to update models that were changed on the Angular 6 front end.
Unfortunately i keep receiving 400 Bad Request response with following message:
{"":["The input was not valid."]}

Now i am not sure if i am doing this properly but this is how my code is setup:
Frontend:
edit.ts class

onSubmit() {
    this.testService.update(this.id, this.prepareFormModel())
      .subscribe(res => console.info(res);
  }

  prepareFormModel() {
    const formModel = this.testForm.value;

    const retVal: any = {
      title: formModel.title as string,
      comment: formModel.comment ? formModel.comment : '' as string,
      qualified: formModel.qualified as boolean
    };

    return retVal;
  }

test.service.ts class
constructor(private http: HttpClient) { }

  update(id: string, value: any): Observable<any> {
    return this.http.patch<any>('http://localhost:5001/api/test' + '/' + id, value);
  }

in my ASP CORE Project Test Controller
    [HttpPatch("{id}")]
    public async Task<IActionResult> UpdateModel(Guid id, [FromBody]JsonPatchDocument<TestModel> modelDocument)
    {
        return Ok();
    }

The DTO model
    public class TestModel
    {
        public string Title { get; set; }
        public string Comment { get; set; }
        public bool Qualified { get; set; }
    }

Any idea as to what i am stuffing up?
Update 1:
I noticed that httpclient patch only sends out content type application/json. Looking at some examples of JsonPatchDocument it seems to request application/json-patch+json type.

A:

For your current code, you misunderstood JsonPatchDocument which is used to describe exactly how you want to modify a document (For example, replace the value in a field with another value) without having to also send along the rest of the unchanged values.
You currently passing the prepareFormModel instead of describing how you want to modify formModel.
If you want to get TestModel directly in UpdateModel, you need to remove JsonPatchDocument.
    public async Task<IActionResult> UpdateModelWithOutJsonPatch(Guid id, [FromBody]TestModel modelDocument)
    {
        return Ok();
    }

If you want to implement JsonPatchDocument which is descripted in JSON Patch With ASP.net Core, you need to pass document description, for a json path library, you could try fast-json-patch.

API
    public async Task<IActionResult> UpdateModelWithJsonPatch(Guid id, [FromBody]JsonPatchDocument<TestModel> modelDocument)
{
    return Ok();
}

install package
  npm install fast-json-patch --save

import the functions
import { compare } from 'fast-json-patch';

Compare objects and passing eh jsonpatch object.

export class FetchDataComponent {
  public forecasts: WeatherForecast[];
  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    const patch = compare(this.previousFormModel(), this.prepareFormModel());
    http.patch<any>(baseUrl + 'api/SampleData/UpdateModelWithJsonPatch/1', patch).subscribe(result => {
      console.log(result);
    }, error => console.error(error));;

    http.patch<any>(baseUrl + 'api/SampleData/UpdateModelWithOutJsonPatch/1', this.prepareFormModel()).subscribe(result =>     {
      console.log(result);
    }, error => console.error(error));;

  }
  previousFormModel() {
    //const formModel = this.testForm.value;
    const retVal: any = {
      title: "t2" as string,
      comment: "c2" as string,
      qualified: false as boolean
    };
    return retVal;
  }
  prepareFormModel() {    //const formModel = this.testForm.value;

    const retVal: any = {
      title: "t1" as string,
      comment: "c1" as string,
      qualified: true as boolean
    };
    return retVal;
  }
}

Note, for JsonPatch, you will need to implement something like below to get TestModel
[Route("api/[controller]")]
 public class PersonController : Controller
 {
private readonly Person _defaultPerson = new Person
{
    FirstName = "Jim",
    LastName = "Smith"
};

[HttpPatch("update")]
public Person Patch([FromBody]JsonPatchDocument<Person> personPatch)
{
    personPatch.ApplyTo(_defaultPerson);
    return _defaultPerson;
}
}


Q:

What should I do to solve my problem with dropna and fillna in python?

I see there are some missing data, in my data.
there are NaN values in "Type 2" column.

When i write this code to drop the rows which have NaN values;

When i write this code to add "empty" which have NaN values;

I restarted my jupyter notebook but its still the same.

A:

When you do data['Type 2'].dropna(inplace=True), that's creating a new series (for your "Type 2" column) and dropping the nans from that new data structure. It doesn't change your original dataframe.
If you want to dropna from the DataFrame, you need to do it directly on that object, not on the column object. The following drops nans directly on the DataFrame:
data.dropna(subset=['Type 2'], inplace=True)

Note that here we're calling dropna on data directly. subset is the argument that you can use to tell pandas which columns to use to determine which rows to drop.


Q:

.gitignore file is not working in my project

I have a project named "shortcut", here is my issue & steps
cd shortcut
vim .gitignore
git init
git add *
git status

I could still see all the .exe files and .pdb files are in the staging. what's wrong with my git operation steps ???
here is my .gitignore file
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
*.exe
*.pdb
*.dll

A:

I think you're confused, although it's hard to tell exactly where. Consider the following:
$ mkdir shortcut
$ cd shortcut

$ touch foo
$ echo foo > .gitignore

$ git init
Initialized empty Git repository in ~/shortcut/.git/

$ git add *
The following paths are ignored by one of your .gitignore files:
foo
Use -f if you really want to add them.
fatal: no files added


Q:

I'm stuck in an endless loading screen. Is this normal?

I have a Nintendo DS with a DSOne Flash Card with EOS installed on it.

Before the software update, it works completely fine.
Just recently, I've managed to find an software update. However, after the update - It seems to be stuck in an endless loading screen.

There's several things that were suggested to do to find the problem, such as using the troubleshooter (holding LT and RT while the DS is starting), but it is to avail.
In case, here's the results:

Test Flash
flash id ok!
flash ok!

Test sd card
sd ok! no find test file.

Test Psram
psram ok!

Now SuperCard DS Version:
English Ver1.01

Test finished.

Is there something else that I'm missing? Am I using the wrong EOS version for my card? Is there any other update steps I missed?

A:

I would suggest you do make sure you are using the right version for your card and that you removed the previous files required on the SD card so that only the new files are there, otherwise version conflicts may occur. You didn't specify your update method and as I recall this card had two options: one to simply rewrite files on the SD card, and another using a special update adapter.
I would suggest also trying to download and update the files from a different computer or internet connection if you have occasional issues with your ISP as many people do these days it is possible your download was actually corrupted but not in a way that your computer detected.


Q:

Node.js plesk - Sending emails with nodemailer not working

I'm using node.js with nodemailer on a fresh ubuntu plesk root server.
When trying to send an email like this:
module.exports = {
    SMTP_HOST: 'host',
    SMTP_USER: 'username',
    SMTP_PASS: 'password',
};

let transporter = nodemailer.createTransport({
  host: SMTP_HOST,
  //port: 465,
  port: 587,
  secure: true,
  auth: {
      user: SMTP_USER,
      pass: SMTP_PASS
  },
  tls:{
    rejectUnauthorized:false  // if on local
  }
});

... I'm getting this error message:
{ Error: connect ECONNREFUSED ip-adress:587
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
errno: 'ECONNREFUSED',
code: 'ECONNECTION',
syscall: 'connect',
address: 'ip-adress',
port: 587,
command: 'CONN' }

How can I send emails via a plesk root server?
... if I use port 465 I'm getting this error:
{ Error: Data command failed: 550 5.7.1 Command rejected
at SMTPConnection._formatError (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:605:19)
at SMTPConnection._actionDATA (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:1454:34)
at SMTPConnection._responseActions.push.str (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:1426:26)
at SMTPConnection._processResponse (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:764:20)
at SMTPConnection._onData (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:570:14)
at TLSSocket._socket.on.chunk (/home/project/node_modules/nodemailer/lib/smtp-connection/index.js:522:47)
at TLSSocket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
code: 'EENVELOPE',
response: '550 5.7.1 Command rejected',
responseCode: 550,
command: 'DATA' }

A:

Adding sendmail: true (https://nodemailer.com/transports/sendmail/) solved the issue:
let transporter = nodemailer.createTransport({
  sendmail: true,
  newline: 'unix',
  path: '/usr/sbin/sendmail',
  host: SMTP_HOST,
  //port: 465,
  port: 587,
  secure: true,
  auth: {
      user: SMTP_USER,
      pass: SMTP_PASS
  },
  tls:{
    rejectUnauthorized:false  // if on local
  }
});


Q:

Wait for abstract function to finish c#

I have two class (CLASS1 and CLASS2), from CLASS1 i call an abstract method and i need wait to end of it and show a message "End Process...", how can i solve this?
CLASS-1:
public abstract partial class CLASS1 : Form
{
    public CLASS1()
    {
        Console.WriteLine("Start Process ABSMethod1");
        ABSMethod1("var1", "var2");
        Console.WriteLine("End Process ABSMethod1");

        Console.WriteLine("Start Process ABSMethod2");
        ABSMethod2(1, 2);
        Console.WriteLine("End Process ABSMethod2");
    }

    protected abstract void ABSMethod1(String var1, String var2);
    protected abstract void ABSMethod2(int var1, int var2);
}

CLASS-2:
class CLASS2: CLASS1
{
    protected override void ABSMethod1(String var1, String var2)
    {
        if (var1 == "test")
        {
            Task.Factory.StartNew(() =>
            {
                Parallel.ForEach<clssmt>(items, item =>
                {
                    /* ... */
                });
            });
        }
        //if i use Task.Wait() freezes UI.
    }

    protected override void ABSMethod2(int var1, int var2)
    {
        Task.Factory.StartNew(() =>
        {
            Parallel.ForEach<clssmt>(items, item =>
            {
                /* ... */
            });
        });
    }
}

I solve this problem using protected virtual async Task and await, but i'm not sure if it is the best solution. And if i use this solution, the message "End Procces" is shown little before that Task is finished.

A:

i need wait to end of it and show a message "End Process...", how can i solve this?

You expose those executed Task's to the caller. You also don't invoke them via your constructor, but via an initialization method:
protected abstract Task FirstMethodAsync(string var1, string var2);
protected abstract Task SecondMethodAsync(int var1, int var2);

public async Task InitializeAsync()
{
     Console.WriteLine("Start Process ABSMethod1");
     await FirstMethodAsync("var1", "var2");
     Console.WriteLine("End Process ABSMethod1");

     Console.WriteLine("Start Process ABSMethod2");
     await SecondMethodAsync(1, 2);
     Console.WriteLine("End Process ABSMethod2");
}


Q:

how to print RTC use Assembly interrupt vector 1ah

I need to output an Interrupt 1h. (RTC).
But I don't know how to print RTC in console. Should I use interrupt 10h, or is there another way?
I already tried to find some in google, and I applied the interrupt 10 directly as below.
mov ah 0x02
int 0x1a

But it's not working. I know that the code is poor.
Please give me some help. If you can make example for me, I'd really appreciate it.

A:

Looking at docs for int 0x10, we see a number of functions.  You didn't specify which you tried to use, but let's look at ah=0x0e:
Expects: AH    0eH
         AL    character to write
         BL    (graphics modes only) foreground color number

The 'character to write' is the ascii value of the character we want to display.  So for example if you want to write the character '7', you would put the ascii value for it (55 aka 0x37) into al.  Just putting 0x7 into al would be the ascii character for BEL (and would make the speaker beep).
So, what if you want to print the number 1234?  Well, you would need to call this function 4 times, with each of 49, 50, 51, 52.
I know, you're wondering if there is some way to output a string?  Sure.  For example there is INT 0x10, ax=0x1300.  However, you STILL need to turn 1234 into the appropriate ascii characters, then call the BIOS function to output the string you have created.
Isn't there some sort of printf("%d") that does that conversion for me?  Not in the BIOS.  BIOS functions are designed to be very low level.  That's (part of) WHY there are operating systems, C runtime libraries, etc, so that people don't have to write all this junk.
If you don't want to write such a function yourself, there are asm 'libraries' out there that have collections of routines for performing this type of thing.


Q:

how to offline install .net core and sdk on linux (RHEL)?

I have to install .net core 2.0 and SDK on Linux machine (RHEL distribution) server, where there is NO internet connectivity. Any help on instructions would be appreciated.

A:

I extracted .net core 2.2 package into a directory /dotnet in linux opensuse 42.1
then in terminal
sudo ln -sf "/dotnet" "usr/bin/dotnet"
export PATH=/usr/bin/dotnet:$netcorepkgs
then in terminal dotnet command works
# dotnet --version
2.2.104


Q:

When to use worker and factory function in angularjs

i am learning angularjs from Pro angularjs by adam freeman.
This is an example he defined an directive in angularjs
myApp.directive("highlight", function () {
  return function (scope, element, attrs) {
    if (scope.day == attrs["highlight"]) {
      element.css("color", "red");
    }
  };
});

the first function the writer calls is factory function and it returns a worker function. I' m not able to understand why he returns another function.
When i write the code below, the code returns an error.
I don't know what i'm doing wrong.
myApp.directive("highlight", function (scope, element, attrs) {
  if (scope.day == attrs["highlight"]) {
    return element.css("color","red")
  }
});

A:

If you take a look at the Angular docs about directives, you'll see that there are two ways you can define a directive. One is to use the directive definition object and the other is to just return a postLink function.
The example in your book shows the latter form. The reason your function doesn't work is because Angular calls your function and expects it to return a directive definition object or a postLink function. Instead the function you defined returns nothing or the result of element.css("color", "red") depending on your if statement.


Q:

Normalising ugly method parameters using Guava

I have a class which contains an optional Map:
 private Optional<ImmutableMap<String, String>> stuff;

In my class constructor I am passed Map<String, String> inputStuff, where inputStuff could be:

null
an empty Map
a populated Map

For the first two instances I need to store Optional.absent() and for the third instance I need to store an Optional immutable copy of the map.  The best that I can come up with in terms of handling this is:
    final ImmutableMap<String, String> tmp = ImmutableMap.copyOf(Objects.firstNonNull(inputStuff, ImmutableMap.<String, String>of()));
    if (inputStuff.isEmpty())
    {
      this.stuff = Optional.absent();
    }
    else
    {
      this.stuff = Optional.of(inputStuff);
    }

Is there a cleaner way to handle this?

A:

Why not just simply do:
if (inputStuff == null || inputStuff.isEmpty()) {
  this.stuff = Optional.absent();
} else {
  this.stuff = Optional.of(ImmutableMap.copyOf(inputStuff));
}

I don't see a reason why should you create a temporary variable here. If you prefer using ternary operator, you can even avoid duplicated assigment to this.stuff.


Q:

Fixed DIV at 100% width covers scrollbar

I have a page with a div containing a large table of data. The div has the overflow values of overflow-x:hidden;overflow-y:scroll; Instead of the page scrolling you just scroll using this div's scrollbar. However the table header (thead) is fixed and stays at the top of the div when you scroll, but it covers the scrollbar.

I want the table header to be 100% of the div with the scrollbar but I want it to act like the rest of the table and not cover the scrollbar.

I have tested this in Chrome, Firefox and IE9 and they all look the same!

HTML

    Code
    Name

CSS
table#select-customer-results{
 width:100%;
 margin-top:-5px;
}
table#select-customer-results tr{
 border-bottom:1px solid #797979;
}
table#select-customer-results tr:nth-child(even){
 background:#EBF2F7;
}
table#select-customer-results td,table#select-customer-results th{
 font-family:Helvetica, Arial, sans-serif;
 padding:5px;
 border:1px solid #797979;
}
table#select-customer-results td{
 cursor:pointer;
}
table#select-customer-results tr.clickable:hover{
 background-color:#BCC2C6;
}
table#select-customer-results th{
 color:#FFF;
 padding:7px;
 padding-top:10px;
 font-weight:bold;
 text-align:left;
 box-shadow:0 2px 3px 0 #474747;
 -webkit-box-shadow:0 2px 3px 0 #474747;
 -moz-box-shadow:0 2px 3px 0 #474747;
 background: #878787;
 background: -moz-linear-gradient(top,  #878787 0%, #6E6E6E 50%, #5C5C5C 51%, #7B7B7B 100%);
 background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#878787), color-stop(50%,#6E6E6E), color-stop(51%,#5C5C5C), color-stop(100%,#7B7B7B));
 background: -webkit-linear-gradient(top,  #878787 0%,#6E6E6E 50%,#5C5C5C 51%,#7B7B7B 100%);
 background: -o-linear-gradient(top,  #878787 0%,#6E6E6E 50%,#5C5C5C 51%,#7B7B7B 100%);
 background: -ms-linear-gradient(top,  #878787 0%,#6E6E6E 50%,#5C5C5C 51%,#7B7B7B 100%);
 background: linear-gradient(to bottom,  #878787 0%,#6E6E6E 50%,#5C5C5C 51%,#7B7B7B 100%);
 filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#878787', endColorstr='#7B7B7B',GradientType=0 );
}

Here is the example on jsfiddle: http://jsfiddle.net/Q3sbp/

A:

There are a few problems I noted with your code. Firstly, it isn't semantic. The whole point of th tags is for it to be machine-readable, but you've split up your table so that your ths are for a table with no content, and the table that has content has no header.
Another issue is that you're using the same id for both tables. The id attribute is supposed to uniquely define an element. If you want to apply the same style to both tables, you should give them a class.
Those bits aside, let's look at some solutions. The first idea I had would be setting a negative margin on the th table, such that it appears outside the div (above it, to be precise). However, this doesn't work because the whole point of the div is to have its overflow-y set to scroll. Therefore, what you should do is move the table's code outside of the div.
Here's what it would look like, on JSFiddle.
I changed the code up just a bit. I got rid of the strange height: 35px div in there, and also removed the absolute positioning. It wouldn't be hard to absolute position both such that they line up.


Q:

Assigning NICs to a XenProject VM

I wish to install a VM on my Xen Project machine that will run a Zentyal Firewall. My machine has three networks cards: one integrated, and two discreet, similar cards (they have the same Realtek chip, but are from different manufacturers). For the firewall to work optimally, what I want to do is assign and dedicate the two discreet NICs to my firewall VM, and use the integrated card for Dom0 and other VMs. I have been able to do similar things with other virtualisation software in the past, but have not been able to find a way to do it with Xen Project.
This page provides many useful configurations, but I don't think any of them match what I want to do. Is this at all possible, or must I give up hope of virtualising my firewall computer?

A:

I think the best way to solve this would be using PCI passthrough in Xen. What this means is that you can leave 1 of your NICs attached to the dom0 (which can then be bridged to allow the other VMs to connect through the same interface - look at one of the Xen articles on network configuration for some examples of how to set this up, it'll be the same as if you only had a single NIC) and allow the firewall VM full control over the other two NICs.
The process for this is somewhat involved and can vary by distribution so I would advise you check the first article I linked but I will describe the basic process.
Check the PCI addresses of the two network cards you want to pass through using lspci. The lines of output for your cards will look something like the following (although the details will be very different the structure will be the same):
00:19.0 Ethernet controller: Intel Corporation 82579LM Gigabit Network Connection (rev 04)
00:19.1 Ethernet controller: Intel Corporation 82579LM Gigabit Network Connection (rev 04)

Make a note of the first column (00:19.0 and 00:19.1 in this example). Add this to the config for your firewall VM in the following format:
pci=['00:19.0','00:19.1']

On its own this will cause the VM to fail to boot as it will be unable to pass through the devices. In order for the devices to be passed through they will need to be bound to the pciback driver on dom0 with a command like:
xl pci-assignable-add 00:19.0
xl pci-assignable-add 00:19.1

This may not be possible in all situations but there are other methods if it is not. I strongly advise you to read the article I mentioned before to fully understand what the best way to do this is in your case.


Q:

Inserting a new element in vector using a braced init-list

Given the following struct:
struct TestStruct
{
  int mA;
  int mB;
};

and the following container:
std::vector<TestStruct> _testContainer;

The compiler throws an error when attempting to add items using a braced init list as follows:
_testContainer.push_back({1,2});

I am using visual studio's C++ compiler from 2010 which could be the culprit. Is this valid C++ or am I missing something?

A:

MSVS 2010 is not C++11 compliant.  I suggest upgrading to MSVS 2015 and trying again.  As you can see from this example
#include <iostream>
#include <vector>

struct foo
{
    int a;
    int b;
};

int main(void) {
    std::vector<foo> data;
    data.push_back({1,2});
}

Live Example
It is okay.


Q:

Why use a passphrase for RSA key?

Today I generated my first key pair, so my knowledge here is - so to speak  - very limited.
On client side I am using Windows and to log in I use PuTTY and I used PuTTYGen to create the keys.
Here (https://winscp.net/eng/docs/ui_puttygen) they say:

If you leave the passphrase fields blank, the key will be saved
  unencrypted. You should not do this without good reason; if you do,
  your private key file on disk will be all an attacker needs to gain
  access to any machine configured to accept that key. If you want to be
  able to passwordless log in without having to type a passphrase every
  time, you should consider using Pageant so that your decrypted key is
  only held in memory rather than on disk.

But here I am failing to see why I should even use RSA rather than regular password authentication when I need to use the passphrase. If I do a passphrase I still need to type in a password when logging in.
On a side I would ask a question about this part:

Pageant so that your decrypted key is only held in memory rather than on disk

Does it really protect anything? I don't know how to read things from memory but isn't it a fairly common thing to do for hackers? To read/replace bits in memory?

A:

You do not need a passphrase for your RSA key. But if your key gets compromised (for example, because you carry the key on a thumb drive and you lose it), an attacker could immediately access the assets the key is protecting.
Using a strong password will give you more time to change keys in case of a key compromise.
Related question on Superuser:

Do I need to have a passphrase for my SSH RSA key?


Q:

Should I check on NaN parameters of a coordinate object?

Using an { x: 0, y: 0 } object(and objects that have x and y properties) for geometrical calculations. Thinking on a checking function.
The question: do I need to check if x and y are numbers?
E.g. which variant is better:
function isCoordObj ( obj ) {
    if ( obj.hasOwnProperty( 'x' )
      && obj.hasOwnProperty( 'y' )
      && !isNaN( obj.x )
      && !isNaN( obj.y ) ) {
          return true;
    }
    throw new Error( 'not a Coord Object' );
}

or this one is enough:
function isCoordObj ( obj ) {
    if ( obj.hasOwnProperty( 'x' )
      && obj.hasOwnProperty( 'y' ) ) {
          return true;
    }
    throw new Error( 'not a Coord Object' );
}

A:

If x and y were never assigned to NaN, you do not need to do NaN check. On the contrary to this, if it were quite probable that x and y assigned to NaN and it cause critical problem to an application, you have to do NaN check. I think that it's a decision of problem.


Q:

Custom Image Attribute in Magento generates error when not set any image and called from product view page

I have created a custom image attribute and added it to default attribute set in Magento. My new attributes are img_support and img_upgrade. I've displayed both images on product view page using this piece of code:
<?php if ($_product->getimg_upgrade()):
 $_img = '<img src="'.$this->helper('catalog/image')->init($_product, 'img_upgrade')->resize(85).'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'"  "/>';
 echo $_helper->productAttribute($_product, $_img, 'img_upgrade');
 endif;
?>

Same code with the second custom image attribute name will display img_support image. When I set images and select them for these two attributes they'll display fine but when there is no image uploaded and selected for these attributes and I try to show it on product view page then it generates an error. Something like this:
a:5:{i:0;s:25:"Image file was not found.";i:1;s:3911:"#0 C:\Program Files\EasyPHP-    5.3.8.0\www\mymagentoroot\app\code\core\Mage\Catalog\Helper\Image.php(163):
Mage_Catalog_Model_Product_Image->setBaseFile('no_selection').....

And a long trace after that. So basically it fetches the image even though there is no image selected. Can anyone tell me how can I display my custom images in product view page of selected products? I have, say 10 products with default attribute set. So all of these 10 products CAN be set with img_support and img_upgrade but I want to show the custom images only on 5 selected products. If the images are set display. Otherwise don't. How can i do this? If there is any other proper or better way to do this then help me out here.
Thanks!

A:

When a product has no image for a given attribute, Magento uses a placeholder image instead.
Basically, each image attribute must have a placeholder image in the skin directory, named with the corresponding attribute code.
In your case, you should create two new placeholder images for your two new attributes img_support and img_upgrade, in this skin directory : images/catalog/product/placeholder/your_attribute_code.jpg (either with a new image, or with a copy of one of the base placeholders)


Q:

How to prevent round-off error with Math.sin(Math.PI)?

When evaluating Math.sin(Math.PI) in JavaScript, the result is 1.2246063538223773e-16 rather than 0. I suppose this is due to the limited precision of the JavaScript Number and limited precision of the sinus algorithm.
How could one prevent these round off errors? Would it help to use a BigNumber type with higher precision, and a higher precision sinus algorithm? Or would that just give you a smaller round-off error but still an error?

A:

I use Number.EPSILON to sort out rounding errors.  This is mostly supported but the linked page has a polyfill for IE
 var sinTheta = Math.sin(theta);
 if (Math.abs(sinTheta) < Number.EPSILON) {
   sinTheta = 0;
 }


Q:

EhCache, cloudfoundry (or other PaaS) replication issues

I want to use CloudFoundry as the PaaS for my Spring/Hibernate application.
I am considering using EhCache as a cache manager but I am worried it won't be able to replicate and/or integrate well with the cloudfoundry environment...
Can a cloudfoundry expert kick in and provide advice or alternative solutions to ehcache?

A:

EhCache replication could be tricky, especially when you bring up on the fly new application nodes in your cloudfoundry cluster (bootstrapping and/or race condition)
One thought: Have you looked at distributed caching instead of replicated caching? EhCache can be "distributed" using what's called the Terracotta Server Array, and all cache consistency needs across the cluster are taken care for you automatically. More at http://terracotta.org/products/bigmemorymax.
The advantage would be that when you bring up a new application node on the fly, it would seamlessly connect to the terracotta array (think about it as a sort of in-memory database for caches) and join the distributed caching environment (no bootstrapping or race condition issues)
And within a cloudfoundry environment, the terracotta server array would be considered an external service (like an oracle database would for example). More on that at http://docs.cloudfoundry.com/docs/running/architecture/services/service-connector.html (replace "oracle" with terracotta server array)
Hope that gives you a different perspective if you hadn't looked at that already.


Q:

Shared Objects in Cocoa

I'm working with CoreData in Cocoa (not document-based).
My problem is, that I want to access the SAME NSArrayController from different NIBs.
But every NIB has an own instance of this NSArrayController.
My question is now how I could generate sharedObjects (like the NSUserDefaultsController).
It would help me a lot. Thanks for your answers. =)

A:

You generally don't want to share an NSArrayController between nibs. It's probably better to have multiple NSArrayController (one per NIB) which are all bound to the same underlying model. If you want this model (e.g. an NSArray) to be application global, you can expose it via the NSApplication's delegate (e.g. instantiate your custom MyAppDelegate class in MainMenu.nib and connect the NSApplication's delegate outlet to the instance of your MyAppDelegate class). In other NIBs, you can then bind an NSArrayController's contentArray binding to Shared Application.delegate.myArray (assuming MyAppDelegate exposes—via KVC-compliant methods—an NSArray binding called myArray). You are essentially using IB and the MainMenu.nib to create your singleton instance of MyAppDelegate.
Keep in mind that this approach makes unit testing your application difficult, since there are now singletons in the object graph that you can't mock or stub out during testing. It would be much better to create an NSWindowController or NSViewController for each secondary (non MainMenu.nib) NIB and bind the NSArrayControllers in those nibs to File Owner.myArray. You can then instantiate the NSWindowController or NSViewController, passing it an array (or array KVC-compliant object) before loading the secondary NIB. In this way, you can test the functionality of the nibs in isolation (using a mock or stub for the array).


Q:

ImageField is not defined

I'm building a personal photography site using Django. I'm working on the models.py. My app is called "photoViewer", the site is called "photoSite". However, when I run makemigrations, I'm getting:
NameError: name 'ImageField' is not defined
I have 3 images stored in "photoSite\photoViewer\static\photoViewer\images" locally, that I'd like to display on my completed site.
Models.py:
from django.db import models

# Create your models here.
class Photo (models.Model):
    photo_title = models.CharField(max_length=200)
    photo_img = ImageField(upload_to = "images/") #Error here
    def __str__(self):              # __unicode__ on Python 2
        return self.photo_title
class Album (models.Model):
    photos= models.ManyToManyField(Photo)
    album_title = models.CharField(max_length=200)

    def __str__(self):              # __unicode__ on Python 2
        return self.album_title

settings.py:
...
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', 'static').replace('\\','/')
STATIC_URL = '/static/'
...

A:

Looks like you have a syntax issue...
photo_img = ImageField(upload_to = "images/")

Should be...
photo_img = models.ImageField(upload_to = "images/")


Q:

Dreamweaver how to get properties bar back

Oh my word. I struggle with the actual codeing of my website, and now something sooooo stupid has to happen....
In dreamweaver.. i think i pressed the wrong button or something, and now i cant fix it..
You know on the right hand side (usually) there is a window where you can set the properties of lets say a textbox. Like its name, its contents, its id etc.
That box has dissapeared... Now theres only some random boxes of properties i have NOOOO idea what for...
Can any one tell me how i can get that back please? The default ones back? (like a reset settings button somewhere?
Thank you!
Ruan.

A:

Go to the Window menu and select Properties to get it back.  Alternately, Control-F3.


Q:

Commands in asp.net always run a dot net build

Hello every time I type any dotnet command it will configure dotnet again.
I don't want to be like this, I don't want that every time I type command dotnet is configuring again. Help me turn this off.
configure again

A:

The error message "Failed to create prime the NuGet cache. new failed with: -2147352571" hints at a known problem when you install the 2.0 CLI next to the 1.0 one and then return to run anythin in 1.0 afterwards.
Latest information on this topic is from June this year when the 2.0.0 tools were still in preview phase. The info back then was to wait until 2.0.0 is released and then there might be another update to the 1.0 series to fix problems if both are installed together.
In the meantime, you can work around this by either uninstalling the 2.0 series dotnet cli or by making sure this environment variable is set before running the 1.0 cli again:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
This is the original problem report with the same error message you didn't mention: https://github.com/dotnet/cli/issues/6381
Here's the discussion for the temporary fix: https://github.com/dotnet/cli/issues/6550#issuecomment-301261209
And here you find the latest information about no updates for the 1.0 series until 2.0 is final (2.0 is final in the meantime, but apparently 1.0 hasn't received any updates since): https://github.com/dotnet/cli/pull/6633#issuecomment-311882413


Q:

How programatically set gravity_layout to NavigationView - Android

In my app user can chose in what side he'll have NavigationView
how set layout_gravity="end" programatically ?
<android.support.design.widget.NavigationView
    android:id="@+id/main_navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#FFF"
    >

    <ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="@color/light_grey"
    android:dividerHeight="0.5dp">

    </ListView>

</android.support.design.widget.NavigationView>

A:

you can play with this:
 DrawerLayout.LayoutParams params = new DrawerLayout.LayoutParams(DrawerLayout.LayoutParams.WRAP_CONTENT, DrawerLayout.LayoutParams.MATCH_PARENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            params.setLayoutDirection(Gravity.START);
        }
        navigationView.setLayoutParams(params);


Q:

Using Flask: bootstrap works but custom stylesheet doesnt't

I have checked the other topics, they seem similar but won't solve my problem:
I am writing a web application using flask and bootstrap works fine but my custom stylesheet gets completely ignored and I can't figure out why.
  <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
      <link href="/static/styles.css" rel="stylesheet">
      <title>C$50 Final_Project: {% block title %}{% endblock %}</title>
  </head>

A:

Browser cache needed to be cleared...
I am not sure why this question was downvoted so much, but I probably should have added, that the path for static.css is not the problem...


Q:

Clamp gameobject to within borders while slowly following another along x and y

I am trying to make an air hockey game and I need to clamp the AI into a specific area whilst it follows the puck around the board when it's in its half. I thought the following code would work but I'm getting some weird behaviour from the paddle where it will either a) get stuck at y=minY on start of the level or b) it will seemingly phase between minY and maxY continuously.
public float speed = 0.075f;
public float minX = -3.7f, minY = 6.7f, maxX = 3.7f, maxY = 0.5f;

void Update () {
    transform.position = new Vector3(Mathf.Clamp(Mathf.Lerp(transform.position.x, _puck.transform.position.x, speed), minX, maxX),
                                     Mathf.Clamp(Mathf.Lerp(transform.position.y, _puck.transform.position.y, speed), minY, maxY),
                                     transform.position.z);
}

Thanks for any help.
EDIT
I should add that if I only use the clamp on the y it works as expected, however it may clip out of the x over time if I don't clamp that too.

A:

Your minY is greater than maxY.
I think you should invert them.


Q:

GLSL #version gives syntax error (LWJGL on Mac)

Specifying the GLSL version gives a syntax error when using LWJGL. I haven't tried to reproduce this issue outside LWJGL. This is happening on multiple Macs running Lion.
I've gotten both vertex and fragment shaders to work without using #version. But I'm about to use the texture function, which seems to require a #version directive.
Here's the simplest failing example:
#version 120

void main() {
  gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

Compiling this fragment shader and calling glGetShaderInfoLog gives this error:
ERROR: 0:1: '' : syntax error #version

Replacing 120 with anything else, such as 110, also gives an error. Curiously, though, if I use 130 or higher, it gives the same error plus a complaint about the version not beig supported. (i know my system doesn't have GLSL 1.3, but it's still weird that this error displays when the compiler is acting like it doesn't understand the version tag.)
I'm on a Mac with an ATI Radeon HD 4670. GL_VERSION is 2.1 ATI-7.12.9 and GL_SHADING_LANGUAGE_VERSION is 1.20.
Given that, I don't see any reason why GLSL 1.20 should be unavailable. And it's really weird to me that it's saying #version is a syntax error, as opposed to saying something about an unsupported GLSL version.

A:

Solved! It had nothing to do with OpenGL. My file reader code was dropping all line breaks. This was fine in the body of the shader, which had semicolons. But the preprocessor directive had no semicolon to protect it from this error.
So for anyone with this problem, make sure the code you're actually passing to glShaderSource still has its linebreaks.


Q:

Does Outlook 2016 for Mac support Exchange 2010(v14.0)?

Some Mac users have updated from Outlook 2011 to 2016 and now are having troubles connecting to an on premise Exchange server with their credentials. The error is "Authentication failed. Check your information". Users get prompted twice to "Allow the autodiscover", but allowing it doesn't make Outlook work anyway.
Seems a majority says Outlook 2016 supports Exchange 2010 and up. Which one, the v14.0? There was only one blog that said minimum requirement is 2010 SP2. Does anyone know the specific minimum version supported?

A:

Here is the full Exchange supportability matrix, including all supported clients: https://technet.microsoft.com/library/ff728623(v=exchg.150).aspx.
It does indeed look like Outlook 2016 for Mac (included in Office 365 for Mac) supports Exchange 2010, but it needs to be Exchange 2010 SP3; this means previous Exchange 2010 versions might or might not work, but they are not supported.
As a side note, if your Exchange 2010 is not already at SP3 level, I strongly suggest you upgrade it, and also apply the latest available update rollup (currently UR12, but see http://social.technet.microsoft.com/wiki/contents/articles/240.exchange-server-and-update-rollup-build-numbers.aspx); running outdated software is almost never a good idea.


Q:

Scala general performances and code optimization

What about performance of the compiled code of scala related to normal Java?
And What about the overhead of recursion instead of "the standard for/while loop"? It's less performance?
and if Yes,  what are the trade off of losing performance?
EDIT
The Answer gave me from Andreas Neumann was almost of I wanted to know. Just missing:
When It's better use Scala instead of Java.
Narrowing the question:
When Scala it would preferred for a consistent project instead of Java, or is it better a mix of both?
I don't know, just guessing, maybe for code maintainability?

A:

A short answer to your Question:
It depends.
A longer answer:
In most cases you would end up with as fast code as you would get with Java. It depends a lot on your coding experience in Java as it does in in Scala.
In a lot of cases the compiler will be able to turn a recursive implementation in a while-loop under the hood -> see @tailrec Annotation for information on that matter.
A good/scientific answer:
Here is a good paper on that Question done by Google Research: Loop Recognition in C++/Java/Go/Scala . Take a look at their findings.
Abstract -> http://research.google.com/pubs/pub37122.html
PDF -> http://static.googleusercontent.com/media/research.google.com/de//pubs/archive/37122.pdf