text: Q: Vb6 form inside a panel in .net framework I have a vb.net program that I need to call a vb6 form and place into a panel. I'm trying to find the code to do this through the interop layer and I'm having issues finding examples. Any ideas how to make the panel load the vb6 control. The form I'm trying to call is the frmAccount


text:
Q: Bridge rectifier output higher than input I have an electromagnetic dc brake rated at 110 Vdc. When voltage is applied, the brake is on. The main power source is 380Vac which is connected to a step down transformer with 110 Vac output. The 110 Vac output is then connected to bridge rectifier which produce 104 Vdc output.
I noticed that when I connect the positive lead from the rectifier to the brake, the voltage on the rectifier output jumped from 104 Vdc to 194 Vdc. Please note that I have not connected the negative lead from rectifier to brake.
I would like to know why the voltage jumped to 194 Vdc while the circuit is still open. Will it damage the brake if I close the circuit? The brake is rated at 110 Vdc. Please refer to my drawing.

A: The bridge isn't producing true DC, rather a rectified sine wave with peaks at 1.414*110V ie 154V, like so:

You have several issues here. First, your multimeter when in DC position will "interpret" this waveform as it sees fit. If it's a good multimeter, it should average the DC value which is what you expect, then you would get around 98V ; 104V isn't too far. If it's a junk multimeter, it will display "something".
Now this gets more subtle. You drew a pretty large rectifier, and these big diodes have capacitance and non-zero leakage currents. The multimeter however has a very high input impedance. When measuring the output of a rectifier with only the multimeter as a load, diode capacitance and leakage (which are not matched between diodes) will change the value.
Solution is to add a dummy load, since the output is supposed to be 110V you can use a resistor of suitable value and voltage rating, or an incandescent lightbulb. But your 104V measurement looks OK.
Anyway. I think this also explains why you get 194 volts in the second measurement. Since you only connected one wire to the bridge, the brake will have a parasitic capacitance to whatever it's connected with (probably a large piece of machinery which is earthed). The transformer also has interwinding capacitance. To the high impedance input of the multimeter, a tiny current coupled through these parasitic capacitances appears like a legitimate measurement. Adding a load to the output of the bridge will fix this measurement problem.
Or you can simply connect the brake: if the bridge has 110VAC on the input, it isn't going to increase the voltage on the output...

redpajama_set_name: RedPajamaStackExchange


text: Q: How can I manipulate the error messages that sbt outputs? I want to make them more readable in the context of the common errors for our specific project - without actually recompiling sbt if that is even possible.


text:
Q: How to make a fixed header with SlickNav I need to make a fixed header containing a slicknav menu.
This is the homepage of the JQuery plugin:  http://slicknav.com/
I know how to make a slicknav menu:   http://jsbin.com/UqUloNO/4
And i know how to make a basic fixed header:  http://jsbin.com/AwEDura/1/
But i don't know how can i put them together.
This is an example of what i am doing: http://jsbin.com/OzOgaFO/1/
There is the fixed header but the slicknav disappear under.
Someone knows how can i make a fixed header containing a slicknav menu?
Thank you!

A: Just apply position: fixed style to your menu element. Example:
.slicknav_menu {
    display:block;
    position: fixed;
    width: 100%;
    top: 0;
}

Working sample: http://jsbin.com/UqUloNO/2/


text:
Q: phpunit no tests executed I have a 'No tests executed' with phpunit..
This line works
$ phpunit install/InstallDbTest.php
...
<result expected>
...

$ cat suites/installtests.xml
<phpunit>
    <testsuites>
        <testsuite name="database">
            <file>install/InstallDbTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>

$ phpunit -c suites/installtests.xml
PHPUnit 4.7.4 by Sebastian Bergmann and contributors.

Time: 130 ms, Memory: 11.25Mb

No tests executed!

Does anyone can tell me what I am doing wrong ?
Thanks in advance!

A: You need to correct the path in your phpunit.xml.
It is trying to find the filesuites/install/InstallDbTest.php.  Since the file doesn't exist, no tests are run and you get the message.
Change the configuration to the following:
<phpunit>
    <testsuites>
        <testsuite name="database">
            <file>../install/InstallDbTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>

File paths in phpunit.xml are all relative to the location of the xml file.

A: Maybe in the InstallDbTest.php file you are missing:
<?php
...

A: For those of you who you use a different bootstrap file than the Composer's autoload file, make sure you don't use one of your test case classes.
Indeed, PHPUnit (version 6.2 in my case) add to the running TestSuite all PHP files for which no class is loaded yet (see how it's done in the code). From the TestSuite::addTestFile($filename) method:
$classes = get_declared_classes();
$filename   = Fileloader::checkAndLoad($filename);
$newClasses = \array_diff(\get_declared_classes(), $classes);

So if your class already belong to the get_declared_classes it will be ignored.
To summarize: don't use your test class before ;)


text:
Q: What are the cases in which it is better to use unconditional AND (& instead of &&) I'd like to know some cases in Java (or more generally:
in programming) when it is preferred in boolean expressions to use the unconditional AND (&) instead of the conditional version (&&).
I know how they work, but I cannot think about a case when use the single & is worth it.

A: If there are side effects that must happen, but that's a little ugly.
The bitwise AND (&) is mostly useful for just that - bitwise math.

A: Input validation is one possible case.  You typically want to report all the errors in a form to the user in a single pass instead of stopping after the first one and forcing them to click submit repeatedly and only get a single error each time:
public boolean validateField(string userInput, string paramName) {
   bool valid;
   //do validation

   if (valid) {
       //updates UI to remove error indicator (if present)
       reportValid(paramName);
   } else {
       //updates UI to indicate a problem (color change, error icon, etc)
       reportInvalid(paramName);
   }
}

public boolean validateAllInput(...) {

   boolean valid = true;
   valid = valid & validateField(userInput1, paramName1);
   valid = valid & validateField(userInput2, paramName2);
   valid = valid & validateField(userInput3, paramName3);
   valid = valid & validateField(userInput4, paramName4);
   valid = valid & validateField(userInput5, paramName5);

   return valid;
}

public void onSubmit() {

   if (validateAllInput(...)) {
       //go to next page of wizard, update database, etc
       processUserInput(userInput1, userInput2, ... );
   }

}

public void onInput1Changed() {
   validateField(input1.Text, paramName1);
}

public void onInput2Changed() {
   validateField(input2.Text, paramName2);
}

...

Granted, you could trivially avoid the need for short circuit evaluation in validateAllInput() by refactoring the if (valid)  { reportValid() ... logic outside of validateField(); but then you'd need to call the extracted code every time validateField() was called; at a minimum adding 10 extra lines for method calls.  As always it's a case of which tradeoff's work best for you.

A: I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional & instead of &&.  (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)
(To give specific examples, x > 0 is going to be super cheap and side-effect-free.  Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway?  Sure, since it's a boolean the end result is going to be used in a branch anyway, but if (x >= 0 && x <= 10) involves two branches, and if (x >= 0 & x <= 10) involves only one.)

A: If the expression are trivial, you may get a micro-optimisation by using & or | in that you are preventing a branch. ie.
if(a && b) { }
if(!(a || b)) { }

is the same as
if (a) if (b) { }
if (!a) if (!b) { }

which has two places a branch can occur.
However using an unconditional & or |, there can be only one branch.
Whetehr this helps or not is highly dependant on what the code is doing.
If you use this, I sugegst commenting it to make it very clear why it has been done.

A: There isn't any specific use of single & but you can consider the following situation.
if (x > 0 & someMethod(...))
{
  // code...
}

Consider that someMethod() is doing some operation which will modify instance variables or do something which will impact behavior later in processing.
So in this case if you use && operator and the first condition fails it will never go in someMethod(). In this case single & operator will suffice.

A: Because & is a bit-wise operator, you can do up to 32-checks in a single operation concurrently. This can become a significant speed gain for this very specific use cases. If you need to check a large number of conditions, and do it often and the cost of boxing/unboxing the conditions are amortized by the number of checks, or if you store your data on-disk and on-RAM in that format (it is more space efficient to store 32 conditions in a single bitmask), the & operator can give a huge speed benefit over a series of 32 individual &&. For example if you want to select all units that can move, is an infantry, has weapon upgrade, and is controlled by player 3, you can do:
int MASK = CAN_MOVE | INFANTRY | CAN_ATTACK | HAS_WEAPON_UPGRADE | PLAYER_3;
for (Unit u in allunits) {
    if (u.mask & MASK == MASK) {
        ...;
    }
}

See my other answers on a related question for more on the topic.

A: The only difference is that && and || stop the evaluation as soon as it is known. So for example:
if (a != null && a.get() != null)

works well with &&, but with & you could get a NullPointerException if a is null.
The only case I can think about where you want to use & is if the second operand has a side effect, for example (probably not the best example but you get the point):
public static void main(String[] args) {
    int i = 1;
    if (i == 0 & ++i != 2) {
    }
    System.out.println(i); //2
    i = 1;
    if (i == 0 && ++i != 2) {
    }
    System.out.println(i); //1
}

However, this looks like smelly code to me (in both cases).

A: The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.
A single & will run both sides regardless.
So, as a contrived example, you might have:
if (account.isAllowed() & logAccountAndCheckFlag(account))
    // Do something

In that example, you might always want to log the fact that the owner of the account attempted to do something.
I don't think I have ever used a single & in commercial programming though.

A: Wikipedia has nicely described the Short Circuit Evaluation
Where do you prefer non short-circuit operators ?
From the same link:

*

*Untested second condition leads to unperformed side effect

*Code efficiency

Short-circuiting can lead to errors in branch prediction on modern
  processors, and dramatically reduce performance (a notable example is
  highly optimized ray with axis aligned box intersection code in ray
  tracing)[clarification needed]. Some compilers can detect such cases
  and emit faster code, but it is not always possible due to possible
  violations of the C standard. Highly optimized code should use other
  ways for doing this (like manual usage of assembly code)

A: The only benefit I can think of is when you need to invoke a method or execute a code, no matter the first expression is evaluated to true or false:
public boolean update()
{
    // do whatever you want here
    return true;
}

// ...

if(x == y & update()){ /* ... */}

Although you can do this without &:
if(x == y){/* ... */}
update();

A: Short-circuiting can lead to errors in branch prediction on modern processors, and dramatically reduce performance (a notable example is highly optimized ray with axis aligned box intersection code in ray tracing)[clarification needed].


text:
Q: Why can't I modify my entity without persist his attribute? I have created a jpa entity named Mail, which have two foreign key.
public class Mail implements Serializable {

@ManyToOne(optional = false, fetch = FetchType.LAZY)

@JoinColumn(name = "auteur")
private User user;

@JoinColumn(name = "typeC")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Type typeMail;
....

and when I want to modify a mail, I do like this:
public void modifyMail(Mail mail) {
  Mail m = em.find(Mail.class, mail.getId());
  m.setUser(mail.getUser());
  m.setType(mail.getType());
  em.persist(m);
}

but it doesn't work. In the glassfich logs, "em.persist" work correctly but glassfich also indicate an insertion in the User table; in the table User, the name is unique, so it don't work and I don't know why glassfich try to create the user associate to the mail. If somebody knows why please can he tell me?

A: The entity manager keeps track of all objects/instances which you got from it. So if you use em.find() to load a user, it will know about this user instance.
If you keep user instances around after closing the transaction which you used to load them, they become stale. The entity manager doesn't really know about them anymore and assumes that they are new.
So the code above needs to be:
public void modifyMail(Mail mail) {
  Mail m = em.find(Mail.class, mail.getId());
  User u = em.find(User.class, mail.getUser().getId());
  m.setUser(u);
  m.setType(mail.getType());
  em.persist(m);
}

or
public void modifyMail(Mail mail) {
  Mail m = em.find(Mail.class, mail.getId());
  User u = em.refresh(mail.getUser());
  m.setUser(u);
  m.setType(mail.getType());
  em.persist(m);
}

The reason for this is that the entity manager doesn't know what "user" or "mail" means. All objects are the same for it. So if you change a user somewhere, the user instance in the Mail could be out of date.
But a better way is probably to change the code when the Mail instance is actually changed:
  em.getTransaction().begin();

  Mail mail = em.find(Mail.class, id);
  User u = em.find(User.class, userId);
  mail.setUser(u);

  em.getTransaction().end();

So instead of collecting changes, start the transaction, load all objects involved from the EM, make the changes and commit the transaction.


text:
Q: How to set QLabel using Base64 string or byte array I have code that's up and running creating images from files.  That code looks like this:
qlabel = QLabel()
qlabel.setText('')
w = QtGui.QPixmap(filename).width()
h = QtGui.QPixmap(filename).height()
qlabel.setGeometry(QtCore.QRect(0, 0, w, h))
qlabel.setPixmap(QtGui.QPixmap(filename))
qt_row_layout.addWidget(qlabel)

I've tried other techniques that I found on SO but none are working.  Here is my latest attempt
qlabel = QLabel()
qlabel.setText('')
ba = QtCore.QByteArray.fromBase64(base64data)
image = QImage()
image.loadFromData(ba)
pixmap = QPixmap()
pixmap.fromImage(image)
w = image.width()
h = image.height()
qlabel.setGeometry(QtCore.QRect(0, 0, w, h))
qlabel.setPixmap(pixmap)

I am porting code that I have up and running on tkinter. It's tricky doing the translations.
EDIT - as requested, one of my graphics...
mac_red = b'iVBORw0KGgoAAAANSUhEUgAAABgAAAAZCAYAAAArK+5dAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAGHRFWHRTb2Z0d2FyZQBwYWludC5uZXQgNC4xLjFjKpxLAAAGfklEQVR42o1W6VNTVxR/Kv4Htp1xZA0JhCWsAQmQAC4Yd0GtKBqXUUAREBdE8pYAWVhUotVWVOpGpzpVqI51pnas+sFtOnXUmXY6o10sErYASUAgybun5yUEoWOnfvjNOe/dc35nufe9cymO4ygBLMt6JMey01mansmaTJS5sVFRrdlsrpq/0LVNEk62RkTB5vBIvjBKRiqyFz0zlpQydUeOUFU6HcVoaT8fzwQXYgo5yzDTWGGhtpYyFO+u2afK7EBSt0Yk5ncEBUGJvz+UInYEBZMtoRKyPSaOr1i67EEDTS+r1usphqan+4jfBXhHPp3FTKppes6hJUvvbhWHQ1FgEDQEBpAboiB4mhQPr5Sp8EqVCk8T4+F6oD8cDphDivwDoCRBDrrtO3RCYsjjN6UC1tcWJGcrKz8pT1X+tkMkhkZRiPNhYABvkUoBtmkIGGsBmj/3os5ARlfnkI7AYHgSEuxuCPQfLcKEKtZvqNLp3wURIJDPoIWIWu3H5WnKX4pDxXAlVDTWKZGABdswuGwZcTc1grPtKrifPPLA9e01cNYboTNeTrok4dApCSPtIcFju0NEsD9v/QEdtktot6cCbVXVTKPROKsmd83z3WIJ3BaLXD3SCOjAjXwtkcLQVg3wF88B/9MTICMjHgg6f74F+ubPh9fiMNIRKYPeiEhyJzTEWYYclRpNuQ7bhXviR9EGPVVfVsaUR8mgTSIe60PjjugY8kYWAx1hUrCvWwv8hRZwP3oIZKAfeAFCJWeboSctHTqkkfAG7f+OjgFrVDRpw9YeTEyCOi2diZ2ZTh0xmRIPZas7T4QE813RMt4Sm0A6ZbFgiY2HTnTqmZsCTqYKyDeXgdy/C/y9H4FcvQKOokLoxKQsMXFeW1ksQV+wREW7zKIQol3z6S0WW0XpC4qauNg4eC4Nhz48DZa4BOiKT/TAIkh07sUg9o35MHLoIIxUHYTB9XnQHY92k2y78Bl9iTVBzt8Xi3itUvXaVFc3m+Jy1wx8KQ3jrXHx0C1PJt1YXo882YtxvRsDd2Om3UjUgxD0CZtJEHz7kubCXzKZ67AsGuh9+6TUfiS+FxUBtpRU6MZMe1MUU9CH7/sUiNQ06EXZ69Px/b9thXb2pKSS/uRk/hxW0cTpzJQ+Jpq8iI2BAUUaLiq8ZON4F0QxQewL5LHxrU+yFzhsqN+QhEKLlgXqs8hw+D0pEWyqDOhPV0K/UuWFoOO7wQULYDA7GwbVarAtXjwB4Xlw4UIYmDcPrJP8+hBDGZnkVkQYmItLXNTRSKn7ZbIcHJmZSKiCgYwMGEDpIczJAVturgf298C3ZluxAgYxkOBnRf9h5PouXAJnOQ6oRkUKPEtKIMP40fRnZZEBXLTlrALH5s1g27QJ7AjHuJwCjcYjbRs3gh1t7fn5nor6szLJcNY8cgMPTuuRo72UYX3+D3cSYmF4vFzb8uVgLyoCe2GhBw5B/x/YBNtduzxBbQsWglWV7vpakQwGjlNStfsrdp5PTXFZM1XEplYTzIo4DhwAe3k5OPbu/SAItnaUtj17yFBODv9nstx9Mjvbom9omEXp6utmNK7Lu/04IY68VatdtoICcHAcsdM0OBjmw+C1JTaUb1evdt7FU2koKGDp6mr82XEsZaKZeedxc96kK9wjBYXEXl8PQwYDDBmNHwSHwUDsJiOM1NTwHco0d8uiRf26mtqPWIaeSQnjkaupoYy7issvyxPcg4vVo6NGI3GcOEGGjh4lw2YzDB879p8YamoijqYmGGludg9szHdez1CCWVddSnvnjN/EqGQwyKmS0kc38Mh2r1ox5jx5gn/b2gqOlhYyfPo0vAdk6MwZMnzxIjhbW139xTvh+0wVmLX0floYXiwzg500MqcJ/26TyTT78K5i/Vcpc+FFlgo3rtzlPHPWPXbtGhlpayOjbe3gwbU2MtbeDs7LV9x2g8H568rlcCkr4w8TTS/iqms843f8AjE+9McfGIbBPeGo45WHmLOrVva1yxPhUUY6vNyQ5+7aWei2Vh4gVm0l6dm7x/1yi8b1eIkarmMyp/LWPahmOZHgyzHMjMkXiYnhzHrlNKFvQol6nS7gWFlZ48k1a38+hx/fJSS6kJwE5xGCfhG/m9Mb8p9+wenqaGHYe5OcQj4lADc+pH2Ggq7FY8YZDFQ9w8h1FQfjb5qPPb9pPv6cQ/1wba2cw7tTlUCGSSGm+Tox+dryD68sSIU4MRj4AAAAAElFTkSuQmCC'

A: Qt does not require the header data:image/png;base64,, so you must remove it.
from PySide2 import QtCore, QtGui, QtWidgets

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    base64data = b'[encoded data, 23432 characters]'
    qlabel = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
    ba = QtCore.QByteArray.fromBase64(base64data)
    pixmap = QtGui.QPixmap()
    pixmap.loadFromData(ba)
    qlabel.setPixmap(pixmap)
    qlabel.show()
    sys.exit(app.exec_())


text:
Q: How do I convert MultipartFile to required type byte[] I'm working with spring Data-Jpa using spring boot. I have a multipart form to upload file to the database with additional fields such as ( firstName, lastName, email, photo). But I keep getting this error message for converting multipart file into required byte[] type. How can I convert the image file from multipart file to byte[] type?
Here is my ControllerClass:
    @PostMapping("/save")
public String saveUserWithPhoto(@ModelAttribute("user") User user,
                         @RequestParam("file") MultipartFile file) throws IOException {
    String fileName = StringUtils.cleanPath(file.getOriginalFilename());

    if (!(fileName == null) || fileName.contains("..")) {
        byte[] photoBytes = file.getBytes();
        user.setPhoto(photoBytes);
        userService.saveUserWithPhoto(user);
        return "redirect:/profile";
    }
    .......
    return "redirect:/new-user";

}

Here is my serviceClass:
  @Override
public void saveUserWithPhoto(User theUser){
    userRepository.save(theUser);
}

Here is my EntityClass:
@Entity
@Table(name = "users")
public class User{

    @Id
    @GeneratedValue
    private long id;

    @Column(name = "first_name")
    private String firstName;

   @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Lob
    @Column(name="photo")
    private byte[] photo;

}

A: MultipartFile contais a byte array of content file. you can use from getBytes() method.
in application.properties add:
spring.servlet.multipart.enabled=true

or use YAML can add:
spring:
  servlet:
    multipart:
      enabled: true

and can get byte array from MultipartFile Like:
MultipartFile  file;
//for your segment file fill from client side(in request)
byte [] content = file.getBytes();

A: As an alternative approach, I would recommend you take a look at the community project Spring Content.  Designed to solve exactly your problem, this project provides an abstraction for storage of unstructured data, injects the service and controller implementations for you so that you don't need to implement either yourself and allows you to associate uploaded content with your Spring Data entities.
In addition, all Spring Content storage modules, including JPA, are all stream-based and therefore capable of handling very large files that the byte[] approach won't be able to do.
Adding it to your project would look something like this:

pom.xml (assuming maven)

    <!-- Java API -->
    <!-- just change this depdendency if you want to store somewhere else -->
    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>spring-content-jpa-boot-starter</artifactId>
        <version>0.8.0</version>
    </dependency>
    <!-- REST API -->
    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>spring-content-rest-boot-starter</artifactId>
        <version>0.8.0</version>
    </dependency>

Define a content store (same concept as a Spring Data Repository):

UserContentStore.java

  @StoreRestResource(path="photos")
  public interface UserPhotoStore extends ContentStore<User, UUID> {
  }

Associate content with your User entities:
@Entity(name = "users")
public class User {
    @Id
    @GeneratedValue
    private long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;

    // Spring Content annotations
    @ContentId
    private UUID contentId;

    @ContentLength
    private Long contentLen;

    @MimeType
    private String mimeType;

And that's it.  The UserPhotoStore is essentially a generic Spring ResourceLoader.  The spring-content-jpa-boot-starter  dependency will cause Spring Content to inject a jpa-based implementation of that interface and the spring-content-rest-boot-starter dependency will cause Spring Content to inject an implementation of an @Controller that forwards HTTP requests onto the methods of the UserPhotoStore service.
All up you will now have a fully functional (POST, PUT, GET, DELETE) REST-based file service at /photoso/{userId} that will use your UserPhotoStore to store (and retrieve) files in your database and associate them with your User entities.
So:
curl -F 'file=@/path/to/local/file.jpg' /photos/{userId}
will upload /path/to/local/file.jpg, store it in your database and associate it with User entity userId.
And:
curl /photos/{userId}
will retrieve it again.
Content can be associated in various ways as described in the docs (Patterns of Association).
HTH

A: I could be mistaken, but I believe Spring is trying to auto-map the entire "User" object that is passed into your endpoint and is failing because there either isn't a "photo" field in the incoming user object, or it is unable to auto-convert that field to a byte[].
For the sake of testing if this is the case or not you can do one of the following
1) If the incoming User object doesn't have a photo field, remove it from your User object
2) If it does and it is coming in as a MultipartFile then change from byte[] to multipartfile.
I know neither of these will help you get it into the database, but it'll help figure out if this is in fact your issue. Then I'd be happy to assist further.
EDIT
Okay, I've been working hard to get this working and at last I got it! See my changes below.
Change controller endpoint like so
@PostMapping
@ResponseBody
public void postUser(@ModelAttribute User user, @RequestParam("file") MultipartFile file) throws IOException {
        user.setPhotoByteArray(file.getBytes());
       //Do Service Call here(user)
    }

I updated the User object like so.
@Entity(name = "users")
public class User {
    @Id
    @GeneratedValue
    private long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;
    @Column(name = "photo")
    private byte[] photoByteArray;

    public User(long id, String firstName, String lastName, String email) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

And that's it! I verified this working by sending a form-data request through postman with all the necessary fields, I also added the following lines to save the file in a local directory so i could open it up to confirm that it correctly handled the image that i passed into postman
FileUtils.writeByteArrayToFile(new File("test.png"), user.getPhotoByteArray());

I also added a constructor to your entity that way when it created the object from model attribute it would allow it to start off being null, and i could set it later.
Let me know if you continue to have issues or questions.

A: Spring does not store the bytes in the class itself but force you to open a stream from  that.

The file contents are either stored in memory or temporarily on disk.
  In either case, the user is responsible for copying file contents to a
  session-level or persistent store as and if desired. The temporary
  storage will be cleared at the end of request processing.

I typically go with intermediate storage to a file or in memory with the following code:
private final Path rootLocation;
try (InputStream inputStream = file.getInputStream()) {
  byte[] in = StreamUtils.copyToByteArray(inputStream);
  //Files.copy(inputStream, this.rootLocation.resolve(filename),
  //                StandardCopyOption.REPLACE_EXISTING);
}

Of course you can use whatever you like instead to create byte[] from a stream. Could recommend StreamUtils if you are in Spring


text:
Q: How to prove the exponential expansion recursive form? Consider the following exponential expansion form:
$$ \exp\left[\sum_{k=1}^\infty \gamma_k x^k\right] = \sum_{j=0}^\infty\delta_j x^j $$
where $\gamma_k$'s are known, and $\delta_0=1$,
$$\delta_{j+1} = \frac{1}{j+1}\sum_{i=1}^{j+1}i\gamma_i\delta_{j+1-i}$$
Does anyone know how to prove it?

A: Srikant asks for a "more elegant approach."  Perhaps the following will respond to this challenge.
Let the argument of the exponential be $f(x)$ (so its power series coefficients are the gammas) and let the right hand side be $g(x)$ (with deltas as its coefficients), so that by definition
$$g(x) = \exp(f(x)).$$
Differentiating both sides and replacing $\exp(f)$ with $g$ yields
$$g' = f' * g.$$
Writing this out as power series gives the desired result: the delta comes from $g'$ while the convolution of the gammas and deltas comes from $f' * g$.
You don't have to worry about convergence (and the whole machinery of Taylor series), by the way: all these calculations can be performed in the ring of formal power series.

A: A brute-force approach would use a Taylor series expansion of $\exp(\cdot)$ at 0 and group terms appropriately to demonstrate the relationship. I have not attempted to do so myself but an inspection of the first few terms does indicate that the proposed relationship holds.
Perhaps, there is a more elegant approach?
$$\exp\left[\gamma_1 x^1\right] = 1 + \frac{\gamma_1 x^1}{1!} + \frac{\left(\gamma_1 x^1\right)^2}{2!} + \ldots$$
$$\exp\left[\gamma_2 x^2\right] = 1 + \frac{\gamma_2 x^2}{1!} + \frac{\left(\gamma_2 x^2\right)^2}{2!} + \ldots$$
$$\exp\left[\gamma_3 x^3\right] = 1 + \frac{\gamma_3 x^3}{1!} + \frac{\left(\gamma_3 x^3\right)^2}{2!} + \ldots$$


text:
Q: How to use center-block and vertical align together using Bootstrap? I have this HTML code:

And this CSS:
.icon-circle {
    float: none;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

The fa-desktop is aligned vertically and horizontally centered in the icon-circle class. Now I want to align the whole icon-circle within the col-md-3. But since there is display table cell, the display block in the center-block doesn't work. Do you have any idea how could I get it work?

A: the icon-circle parent need to be in table display mode
.col-md-3 {
    display: table;
}


text:
Q: How to combine two similar RxJS observable object arrays into one array of objects? I need assistance trying to get two HTTP GET responses that come object arrays and combine them into one object array for example
If possible I would like the array from http using rxjs more than likely to have a response that has all 3 objects in one array
like below
[{...}, {...}, {...}]

.ts
incidents$ = this.incidentService.getAll();
otherIncidents$ = this.otherIncidentsService.getAll();

ngOnInit() {

this.incidents$.subscribe(res => {
 console.log('first http GET request', res)
})

this.otherIncidents$.subscribe(res => {
 console.log('second http GET request', res)
 })

Console
second http GET request [{…}]
0: {incidentNumber: 19418, createdByName: "User", execSummaryFlag:
false, followupEmail: null, …}
length: 1__proto__: Array(0)
exec-summary.component.ts:140

first http GET request (2) [{…}, {…}]
0: {incidentNumber: 19380, createdByName: "User", execSummaryFlag: false,
followupEmail:null, …}
1: {incidentNumber: 19399, createdByName: "User", execSummaryFlag: false,
followupEmail: null, …}length: 2__proto__: Array(0)

A: You could try to use Rxjs forkJoin to combine multiple observables and map the response to your requirement (using spread operator). Try the following
import { forkJoin, pipe } from 'rxjs';
import { map } from 'rxjs/operators';

forkJoin({
  incident: incidents$,
  otherIncident: otherIncidents$,
})
.pipe(
  map(response => ([...response.incident, ...response.otherIncident]))
)
.subscribe(
  response => { // handle reponse },
  error => { // handle error }
);

RxJS forkJoin emits the last emitted value when all the observables complete.

A: Take a look at Concat
// RxJS v6+
import { of, concat } from 'rxjs';

concat(
  of(1, 2, 3),
  // subscribed after first completes
  of(4, 5, 6),
  // subscribed after second completes
  of(7, 8, 9)
)
  // log: 1, 2, 3, 4, 5, 6, 7, 8, 9
  .subscribe(console.log);

A: You have couple of options:

*

*zip function:
"After all observables emit, emit values as an array"

zip(this.incidents$, this.otherIncidents$).subscribe(...);

*withLatestFrom operator:
"Also provide the last value from another observable"

this.incidents$
   .pipe(
      withLatestFrom(this.otherIncident$),
   )
   .subscribe(...);

*combineLatest function (very similar to zip)
"When any observable emits a value, emit the last emitted value from each"

combineLatest(this.incidents$, this.otherIncidents$).subscribe(...);

The three of them emits an array of both of the observable.

A: you can

*

*use forkjoin to wait for both observables to return

*then use switchMap to change the result

*in the switchMap you can manipulate the arrays. in this case we use Array.concat() to generate a new array that combines the output of the two observables
forJoin({
  incident: this.incidents$,
  otherIncident: this.otherIncidents$
})
.pipe(
switchMap ( response => response.incident.concat(response.otherIncident))
).subscribe(
    response => {//do something},
    error => {//handle error}
);

A: Answer to my Question
ngOnInit(){

const incidents = this.incident.getAll();
const otherIncidents = this.otherService.getAll();
forkJoin([incidents, otherIncidents])
.subscribe(res => {
 this.execEntry=[...res[0], ...res[1]];
 console.log(this.execEntry);
})
}


text:
Q: Tips for Upgrading Gmaps v2 to v3 more quickly After upgrade my complete code i had here the most currents tips to upgrade your code.
Add other if you like.
Use : new google.maps. in place of G...

*

*GLatLngBounds() --> google.maps.LatLngBounds()

*GlatLng --> google.maps.LatLng

*GPoint --> google.maps.Point

*Event.addListener --> google.maps.event.addListener

*map.getInfoWindow().getPoint --> google.maps.getPosition()

*markers[i].getPoint() --> markers[i].getPosition()

*closeInfoWindow() --> map.InforWindow.Close();

*map.getBoundsZoomLevel(bounds) --> map.fitBounds(bounds)

*markers[i].setImage --> .setIcon

*map.InfoWindow.close() --> create a function to close

*find in maps for objects --> $('#id')[0] or $('#id').get(0) or document.getElementbyId
Happy coding.


text:
Q: Using mutexes to call separate tasks nXc I'm new to using nXc to code my NXT 2.0 robot and I need it to follow other robots and check for obstacles at the same time. However, the two tasks sometimes conflict with each other and when I meet an obstacle it treats it as an object and continues moving forward instead of stopping.
Aim of my project: Follow a leader robot, stop when it meets an obstacle and after the obstacle is cleared, continue to follow the leader robot that is in front of it.
Below is my code:
    #define NEAR 50
    #define TURNTIME 540
    #define MOVETIME 1000

    mutex moveMutex;

    //check for robot in front of it
    task check_robot(void)
    {
         while(true)
         {
             if (SensorUS(IN_2)<=NEAR)
             {
                 Acquire(moveMutex);
                 OnFwd(OUT_BC,50);  //if it is within range of 50cm, move
                 Release(moveMutex);
             }
             if (SensorUS(IN_2)>NEAR)
             {
                 Acquire(moveMutex);  //this section allows the robot to turn
                 OnFwd(OUT_C,50);     //left and right to look for the
                 Wait(TURNTIME);      //leader
                 OnRev(OUT_B,50);
                 Wait(TURNTIME);
                 OnRev(OUT_C,50);
                 Wait(TURNTIME);
                 OnFwd(OUT_B,50);
                 Wait(TURNTIME);
                 if (SensorUS(IN_2)<=NEAR)
                 {
                      Acquire(moveMutex);
                      OnFwd(OUT_BC,50);   //if it finds the leader, it moves
                      Release(moveMutex);
                 }
                 else
                 {
                      Acquire(moveMutex);
                      OnFwd(OUT_C,50);       //repeats the search process
                      Wait(TURNTIME);
                      OnRev(OUT_B,50);
                      Wait(TURNTIME);
                      OnRev(OUT_C,50);
                      Wait(TURNTIME);
                      OnFwd(OUT_B,50);
                      Wait(TURNTIME);
                      Release(moveMutex);
                 }
             }
             Release(moveMutex);
         }
    }

    task check_obstacles(void)
    {
         Acquire(moveMutex);
         until(((SENSOR_1)==1)||((SENSOR_3)==1));   //when any one of the
         OnRev(OUT_BC,50);                          //touch sensors are
         Wait(1000);                                //pressed, it is supposed
         Off(OUT_BC);                               //to stop until both
         until(((SENSOR_1)==0)&&((SENSOR_3)==0));   //are released, then
         OnFwd(OUT_BC,50);                          //continue moving
         Release(moveMutex);
    }

    task main(void)
    {
         SetSensorTouch(IN_1);
         SetSensorUltrasonic(IN_2);
         SetSensorTouch(IN_3);
         SetSensorColorFull(IN_4);

         while(true)
         {
             Precedes(check_robot,check_obstacles);
         }
    }

Any thoughts on how I can improve this? Would it be better to use subroutines instead of tasks and what is the benefit of using subroutines or tasks?

A: You can not use the nested function to acquire the same mutex variable that causes a crash in their task. Acquire function suspends the task until the mutex variable is released this link to read you understand how the tool works acquire.
Sorry my English used the google tranlate. :)


text:
Q: Reading DDB records for migration I have DDB with 1.4m records in it. For a particular migration I need the primary key of all records in table.
I can export only 100 records at one time in excel from export to csv option. I can create an AWS Data Pipeline but that is a costly operation. I can write a script to scan entire DDB and get all keys.
What are other possible ways?


text:
Q: Is infinite/countable subsets of infinite/countable topological spaces are dense? Let $X$ be a topological space where $X$ is either countable or infinite. If the topology is the co-finite topology, we can say that for any countable/infinite subset $H$ of  countable/infinite $X$ is dense in $X$. If we do not know the topology on $X$, what can we say about density of $H$?

A: In general there's no reason to expect an infinite set to be dense.  Consider for instance $H= \mathbb{N} \subset \mathbb{R}$ with the usual Euclidean topology.  Then $H$ is countably infinite but certainly not dense.  One can construct many more examples like this.


text:
Q: Select Current Database Name OR Not Current Database Name in SQL Server for a Table in SQL Server I have two databases in SQL Server. Let's say they are DB1 and DB2.
When the system starts, the current database is always DB1. BTW, I have to use DB2 for another table.
For the reason, I want to give a table name as a variable like @tablename and want to select a database name for the @tablename. Would it be possible to pull the database name associated with @tablename?
Also, I want to save the database name to a variable like @databasename to print it out.
When I tried to find a database name from the code below, I could get the database name of the table, ExampleTable, among DB1 and DB2.
EXEC sys.sp_msforeachdb
'SELECT ''?'' DatabaseName, name FROM [?].sys.Tables WHERE Name = ''ExampleTable'''

However, I can't go forward to process how to make a code using a variable @table instead of a fixed table name, ExampleTable.
I will use list of tables to input @tablename into the query one by one from the list.
DECLARE @table sysname = 'TableNames';
DECLARE @database_name sysname = 'dbo';
DECLARE @DatabaseName VARCHAR(50)

-- tbl_01 in dbo.DB1
-- tbl_02 in dbo.DB2
-- tbl_03 in dbo.DB1
-- tbl_04 in dbo.DB2

/*
   I need the code block
   (1) To input a table using @table
   (2) To save the database name to a variable like @database_name

EXEC sys.sp_msforeachdb
'SELECT ''?'' DatabaseName, name FROM [?].sys.Tables WHERE Name ='+@table

*/

Please help me to create a script for my work.

A: The below code contains a set of tools you can use to do what you want to do. I expect your requirements may change a bit as you do this, so that's why I'm giving you the tools first.
These tools are written as simple checks - easy to understand and relatively quick. They currently just do a SELECT 'Yes' if the database exists/etc - but of course you can change that as needed.
DECLARE @DBName_1 nvarchar(100) = N'DB1';
DECLARE @DBName_2 nvarchar(100) = N'DB2';
DECLARE @TableName nvarchar(100) = N'MyTable';
DECLARE @TableNameToCheck nvarchar(200);

-- Is the current database 'DB1'?
IF DB_Name() = @DBName_1 SELECT 'Yes' ELSE SELECT 'No';

-- Check if the database 'DB2' exists
IF DB_ID(@DBName_2) IS NOT NULL SELECT 'Yes' ELSE SELECT 'No';

-- Check if table is in first database
SET @TableNameToCheck = QUOTENAME(@DBName_1) + N'.[dbo].' + QUOTENAME(@TableName);
IF OBJECT_ID(@TableNameToCheck, 'U') IS NOT NULL SELECT 'Yes' ELSE SELECT 'No';

-- Check if table is in second database (note it uses @DBName_2)
SET @TableNameToCheck = QUOTENAME(@DBName_2) + N'.[dbo].' + QUOTENAME(@TableName);
IF OBJECT_ID(@TableNameToCheck, 'U') IS NOT NULL SELECT 'Yes' ELSE SELECT 'No';

Note that you do not actually need the variable @TableNameToCheck - you can just construct it within the OBJECT_ID() function e.g., OBJECT_ID(@DBName_2 + N'.dbo.' + @TableName , 'U'). However, it can be useful to set it first to check/ensure it's correct, and it has infinitesimal impact on performance.
For your actual task (recording whether the table exists in DB1 or DB2) you can do the following
DECLARE @DBName_1 nvarchar(100) = N'DB1';
DECLARE @DBName_2 nvarchar(100) = N'DB2';
DECLARE @TableName nvarchar(100) = N'MyTable';
DECLARE @DatabaseWithTable nvarchar(100);

IF OBJECT_ID(QUOTENAME(@DBName_1) + N'.[dbo].' + QUOTENAME(@TableName), 'U') IS NOT NULL
    BEGIN
    SET @DatabaseWithTable = @DBName_1;
    END
ELSE IF OBJECT_ID(QUOTENAME(@DBName_2) + N'.[dbo].' + QUOTENAME(@TableName), 'U') IS NOT NULL
    BEGIN
    SET @DatabaseWithTable = @DBName_2;
    END
ELSE
    BEGIN
    SET @DatabaseWithTable = N'Not Found';
    END;

SELECT @DatabaseWithTable;

Edit: Added QUOTENAME() as per suggestion/comment from @HABO


text:
Q: How to sign in using Firebase, C# Visual Studio WINFORMS I used Firebase in Android Studio and now I'm trying to use it in Visual Studio. I learned how to register a new user in Firebase Authentification but I struggle with signing in.
How I register:
FirebaseAuth firebaseAuth = FirebaseAuth.DefaultInstance;
[...]
System.Threading.CancellationToken cancellationToken;
UserRecordArgs user = new UserRecordArgs();
user.Email = email;
user.Password = pw;
try
{
    UserRecord x = await firebaseAuth.CreateUserAsync(user, cancellationToken);
    MessageBox.Show("Account created! You can login now.");
}
catch
{
    MessageBox.Show("Something went wrong! Try later.");
}

I can't find a function equivalent with signInWithEmailAndPassword(email, pw)

A: Use third party library FirebaseAuthentication.net
    public async Task<bool> SignIn(string email, string password)
    {
        try
        {
            FirebaseAuthProvider mAuthProvider = new FirebaseAuthProvider(new FirebaseConfig("YourFirebaseApiKey"));

            mAuthLink = await mAuthProvider.SignInWithEmailAndPasswordAsync(email, password);
            var firebase = new FirebaseClient(
                  "https://yourfirebasesite.firebaseio.com",
                  new FirebaseOptions
                  {
                      AuthTokenAsyncFactory = () => Task.FromResult(mAuthLink.FirebaseToken)

                  });

            // Process user info from mAuthLink
            Properties.Settings.Default.email_txt = mAuthLink.User.Email;
            Properties.Settings.Default.token_txt = mAuthLink.FirebaseToken;
            Properties.Settings.Default.refresh_token_txt = mAuthLink.RefreshToken;
            Properties.Settings.Default.Save();

            return true;
        }
        catch
        {
            return false;
        }
    }

For more information about how to use this library, I created a Account Manager to use and save all logging information to Properties.Settings
Because it's a Singleton so it's easy to handle User Account.
AccountManager.GetInstance().SignIn("email","password");
AccountManager.GetInstance().SignOut();
AccountManager.GetInstance().SignUp("email", "password");
AccountManager.GetInstance().IsSignOut; // Check it's signout yet?


text:
Q: Js appendChild not working I try to append a title and hr element to the popup,
but when i append this, the popup does not append to the body anymore.
What am i doing wrong? However if i don not append the title and hr to the popup he shows up perfectly.
// selecteer alle elementen met de class "editHose"
var edits = document.getElementsByClassName('editHose');

// voeg eventlistener toe aan elke knop om het edit kadertje te laten verschijnen
for(i=0; i<edits.length; i++)
{

    // eventListener toevoegen aan elke knop
    edits[i].addEventListener("click", function(e) {

        e.preventDefault();

            // maak overlay aan
            var overlay = document.createElement('div');
            overlay.setAttribute('id', 'overlay');

                // append overlay to body
                document.getElementsByTagName('body')[0].appendChild(overlay);

            // maak de popup div aan
            var popup = document.createElement('div');
            popup.setAttribute('id', 'popup');
            popup.setAttribute('class', 'form-signin')

            // maak title en regenboogbalkje onder titel aan
            var title = document.createElement('h3');
            title.setAttribute('class', 'form-signin-heading');
            var line = document.createElement('hr');
            line.setAttribute('class', 'colorgraph');

                // append title en line to popup
                popup.appendChild('title');
                popup.appendChild('line');

                // append popup to body
                document.getElementsByTagName('body')[0].appendChild(popup);

    });

}

thanks in advance!

A: I found out what the problem is:
            popup.appendChild('title');
            popup.appendChild('line');

should be
            popup.appendChild(title);
            popup.appendChild(line);


text:
Q: How to convert List of Edges to Adjacency Matrix in C++ with the number of edges connected to a vertex instead of ones? I am struggling to convert a list of Edges to Adjacency Matrix in a certain required way.
Problem:
The Adjacency matrix should have number of edges connected to a vertex, so it should not have only 1s where two vertexes are connected. For better explanation here is sample input.
Input
4 7
1 2
2 3
3 2
2 4
4 1
4 2
3 2
Where 4 is number of vertexes and 7 is the number of edges and each line represents edges.
Output:
4
0 1 0 1
1 0 3 2
0 3 0 0
1 2 0 0
Where 4 is number of vertexes and each line represents how many times a vertex is connected.
In my code I only managed to convert to normal Adjacency matrix with 1s, but I cannot understand if I can solve this task only with arrays and how?
Here is my code:
#include <iostream>

using namespace std;

int main()
{
    int adjMatrix[100][100] = { };
    int edgeList[100][100];
    int row, col;
    int N, M;

    cin >> N;
    cin >> M;

    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            adjMatrix[i][j] = 0;
        }
    }

    for (int i = 1; i < 8; i++)
    {
        for (int j = 1; j <= 2; j++)
        {
            cin >> row;
            cin >> col;
            adjMatrix[row][col] = 1;
            adjMatrix[col][row] = 1;

        }
    }

    for (int i = 1; i < 8; i++)
    {
        for (int j = 1; j <= 2; j++)
        {
            if (adjMatrix[i][j] == adjMatrix[j][i])
            {
                adjMatrix[i][j]++;
            }

        }
    }
    cout << N << endl;

    for (int i = 1; i <= N; i++)
    {
        for (int j = 1; j <= N; j++)
        {
            cout << adjMatrix[i][j] << " ";

        }
        cout << endl;
    }
    return 0;
}

A: Problem: Want count of connections, not simply that connection exists.
Solution: Use ++
adjMatrix[row][col]++;
adjMatrix[col][row]++;

It is worth noting that
This loop
for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        adjMatrix[i][j] = 0;
    }
}

Is rendered redundant by
int adjMatrix[100][100] = { };

because the = {} default initializes the array, setting all elements to 0.
In addition, what if N is greater than the 100 used to define the array dimensions? adjMatrix needs to be dynamic. Read up on and use a std::vector
The following loop conditions are incorrect
    for (int i = 1; i < 8; i++)
    {
        for (int j = 1; j <= 2; j++)
        {
            cin >> row;
            cin >> col;
            adjMatrix[row][col] = 1;
            adjMatrix[col][row] = 1;
        }
    }

14 lines will ALWAYS be read from the file regardless of the size of the file. The outer loop will always run 7 times (1..7) and the inner loop always twice (1..2).
M defines the number of rows in the file. Use that to control your loop.
This fixed number of lines is particularly bad if there are less than 14 lines in the file because the cin >> are not being tested for validity. The code could be loading the matrix with garbage and you would never know. Instead use something like
if (cin >> row >> col)
{
    do stuff
}
else
{
    handle error
}

A program must validate all input because you can't trust those slimy users. One minute they're making typos and the next trying to hack into the Pentagon.
This loop accomplishes nothing useful, but you knew that already. No thought went into this at all. It is exceptionally hard to write code without thinking. This is why I held off on answering the question so long. Not thinking is also a disincentive to others offering assistance.
for (int i = 1; i < 8; i++)
{
    for (int j = 1; j <= 2; j++)
    {
        if (adjMatrix[i][j] == adjMatrix[j][i])
        {
            adjMatrix[i][j]++;
        }

    }
}


text:
Q: How change exit code for ansible-playbook if exist change in running? I run playbook in check mode in Gitlab CI and I want that CI failed if exist changed in running.
Maybe exist other solution for my issue?
Now used bash script which parsing strings and if exist "changed" return exit code 1

A: you can use "register" along with "failed_when" parameter in your playbook.
error_handling
I will able to give your piece of code if you can elaborate your question with what is excepted and your playbook snippet.

A: Unfortunately, it isn't possible by using Ansible.
The only solution we have is to parse the output of the playbook


text:
Q: Access a webservice through an MS SQL assemby This question I think is related to the access of SQL accounts.
I created a visual studio project in which I created a dll that was placed as a stored procedure in SQL. The visual studio project consumes twice a webservice.
The DLLs are installed with access external_acess.
When installing on my local SQL (windows 7) everything works correctly. When calling the webservice it is called perfectly. The user that is running SQL is local system.
After placing these same DLLs and install them on another SQL server (windows server 2003) does not consume the webservice. In SQL also uses the location system.
If switching to the user network system that SQL consumes the webservices.
The question is: Where do I set this access (acess to consume webservices or http acess)? or how do I check it?
Thanks


text:
Q: Cannot login to Software Engineering via Yahoo OpenID I've been trying to logon to Software Engineering via Yahoo OpenID for the last 20 minutes, at the very least 15+ attempts, and it isn't working.
I am brought to a open.login.yahoo.com/openid/yaddayadda URL that freezes on a black while screen, and that's it.
I did manage to get through another Stack Exchange site, which logged me in for all sites, but still, maybe it is something that needs to be looked into.

A: I tried logging in with Yahoo last week and had issues as well. The code's all shared across the sites, though, so I'm about 95% sure the issue is somewhere on their end as a result.


text:
Q: Mongoengine: create a QuerySet from a MongoDB cursor Some part of the application I'm working in is expecting a mongoengine QuerySet.
I have a MongoDB cursor with the info I need, generated by an aggregation.
Since mongoengine documentation specifies that a QuerySet is a wrapper of a MongoDB cursor, is there any way to create a QuerySet with a given cursor?
Note: There is an obvious solution, querying the database again:
queryset = Model.objects.filter(_id__in=[r['_id'] for r in cursor])
But it's rather ugly. The ideal solution would be something like calling the constructor of QuerySet, since it is a wrapper of cursor. But constructor does not accept cursor as an argument.

A: QuerySet is nothing but just a list. So you can convert the output you get from aggregating into a list like below and directly use that list as QuerySet.
queryset = list(cursor)


text:
Q: JPA: query not fetching the latest data I'm finding that JPA is not fetching the latest data from the database.
My data model has a customer entity that owns a number of order entities.  I'm persisting an order:
em.persist(order);
em.getTransaction().commit();
em.close();

To view the orders, I call:
Collection<Order> orders = customer.getOrderCollection();

The orders collection is missing the latest order.  I've checked and the order is persisted to the database.  With the driver logging turned on, I don't see any calls to the database when getOrderCollection() is called.
In Netbeans 6.9, when I stop & redeploy the app, I see the latest order that I persisted appear.  So perhaps there's some sort of caching that may be interfering with getOrderCollection()?  For some reason, JPA is not going to the database.  Why?
How can I force JPA to go to the database when getOrderCollection() is called?

A: Try <shared-cache-mode>NONE</shared-cache-mode>, in your persistence.xml.

A: You must maintain bidirectional relationships in your object model.  When you add a new Order for a Customer, you must add the order to the Customer's orders.
i.e.
public void addOrder(Order order) {
  this.orders.add(order);
  order.setCustomer(this);
}

You could also refresh the object, or disable the cache, but fixing your code would be best.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Caching
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching


text:
Q: How to use float in an array in c i want to use float values inside the array for example,
array[4];

array[0] = 3.544
array[1] = 5.544
array[2] = 6.544
array[3] = 6.544

float array[] (is giving me error)

but i dont know how to use help me, i am a c beginner

A: You have to specify the size if you are going to define array float in this way:
float array[4];

You can define the array without the size. but it should be in this way:
float array[] = {3.544, 5.544, 6.544, 6.544};

see the following topic for more details: How to initialize all members of an array to the same value?

A: float array[4];

array[0] = 3.544;
array[1] = 5.544;
array[2] = 6.544;
array[3] = 6.544;

This should work buddy.

A: You can't create an array with no static size.
You can create an array like this on the stack, which is mostly when you have smaller arrays:
float myarray[12];

it is created in the scope and destroyed when that scope is left.
or you can create large arrays using malloc in C, the are allocated on the heap, these need to be
manually destroyed, they live until you do so:
// create array dynamically in C
float* myheaparr = malloc(sizeof(float) * 12);

//do stuff with array

// free memory again.
free(myheaparr);

A: Specify number of elements you wanna work with while declaring.
float array[number of elements];
this will statically allocate memory for  specified. Access each elements with index. eg
float array[4] will statically allocate memory for 4 floating point variables.
array[0] refers to the first element and so on.


text:
Q: Animate ImageView inside WindowManager in a Android Service I'm trying to animate an ImageView created dynamically in a service, but no way to get it working... I think the problem is because I'm using a windows manager and I  should have to use a FrameLayout or something similar and place the ImageView inside, but no idea how to do it programatically... Anyway, someone know how to get this working? Help pleaseee!
 @Override public void onCreate() {
    super.onCreate();

    final GestureDetector mGestureDetector = new GestureDetector(getApplicationContext(), new MyGestureDetector());

    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    chatHead = new ImageView(this);
    chatHead.setImageResource(R.drawable.btn_enable_floating);

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            100,
            107,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.TOP | Gravity.RIGHT;
    params.x = 0;
    params.y = 100;

    chatHead.setOnTouchListener(new View.OnTouchListener() {
        private int initialX;
        private int initialY;
        private float initialTouchX;
        private float initialTouchY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = params.x;
                    initialY = params.y;
                    initialTouchX = event.getRawX();
                    initialTouchY = event.getRawY();
                    chatHead.setImageResource(R.drawable.btn_enable_floating_hover);
                    return mGestureDetector.onTouchEvent(event);
                case MotionEvent.ACTION_UP:
                    chatHead.setImageResource(R.drawable.btn_enable_floating);
                    return mGestureDetector.onTouchEvent(event);
                case MotionEvent.ACTION_MOVE:
                    //params.x = initialX + (int) (event.getRawX() - initialTouchX);
                    params.y = initialY + (int) (event.getRawY() - initialTouchY);
                    windowManager.updateViewLayout(chatHead, params);
                    return mGestureDetector.onTouchEvent(event);
            }
            return mGestureDetector.onTouchEvent(event);
        }
    });

    windowManager.addView(chatHead, params);

    RotateAnimation ra = new RotateAnimation(
            0,
            -80,
            Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f);

    // how long the animation will take place
    ra.setDuration(210);

    // set the animation after the end of the reservation status
    ra.setFillAfter(true);
    // Start the animation
    chatHead.startAnimation(ra);
}

A: I've just had the same problem, here is a solution:
Instead of an ImageView, you need to add a FrameLayout, that has your ImageView.
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
floatingLayout = (FrameLayout) inflater.inflate(R.layout.floating_layout, null);

Save your button to deal with animations later:
mButton = (ImageView) floatingLayout.findViewById(R.id.mButton);

Instaed of adding a button, add a layout:
windowManager.addView(floatingLayout, floatingLayoutParams);

Animate!
Animation rotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotation);
    rotate.setDuration(1000);
    mButton.startAnimation(rotate);


text:
Q: Отправка HTML кода из Textarea Итак. Есть некий скрипт, часть из которого приведена ниже, который отправляет HTML код из поля <textarea>:
function editothers(id, fn, fv) {
    $('textarea[name=other' + fn + ']').removeClass('success').addClass('inprocess');
    console.log('textarea[name=other' + fn + ']');
    $.ajax({
        type: 'POST',
        url: '/php/other_shop/edit_other_shop.php',
        data: {
            item_id: id,
            o_field_id: fn,
            o_field_value: fv
        },
        success: function(response) {
            if (response) {
                getothers(id);
                setTimeout('classes('+fn+')', 1000);
            }
        }
    });
}

Далее - PHP:
<?php
//admin
echo $_SERVER['HTTP_REFERER'];

include_once('db.php');
$item_id = $_POST['item_id'];
$o_field_id = 'o_field_'.$_POST['o_field_id'];
$o_field_value = $_POST['o_field_value'];

    echo $o_field_id;
    if ( isset($_POST['item_id']) )
    {

            try{
                    $st_check_double = $db->query("SELECT item_id FROM other_shop1 WHERE item_id='".$item_id."'");
                    $resultscheck_double = $st_check_double->fetch();
                    if (!$resultscheck_double){
                        $db->exec("INSERT INTO other_shop1

                        ('$o_field_id', item_id)

                                             VALUES

                        ( '$o_field_value' ,  '$item_id' )

                                             ");
                        echo '
Код был только что добавлен
';
                    }
                    else
                    {
                        $db->exec("UPDATE other_shop1

                                            SET

                        '$o_field_id'='$o_field_value'

                                            WHERE

                        item_id='$item_id'

                                             ");
                    }
                }
                catch (PDOException $e)
                {
                    die($e->getMessage());
                    echo "Ошибка проверки дублей";
                }

    }

?>

Вопрос первый. Все данные отправляются, однако возле кавычек появляется обратный слеш (\"). Для чего происходит экранирование спец.символов в JS я знаю, а вот можно ли этого избежать на этапе отправки в конкретном примере? К слову, править php.ini или .htacces возможности нет.
Вопрос второй. Если все же избежать нельзя, то можно ли при выдаче данных пройтись по всему содержимому и убрать лишний символ, например, через .replace? Вот участки отвечающие за вывод данных:
function getothers(id) {
    $.ajax({
        type: 'POST',
        url: '/php/other_shop/show_other_shop.php',
        data: {
            item_id: id
        },
        success: function(response) {
            if (response) {
                var arr = new Array;
                var arr = jQuery.parseJSON(response);
                for (var i = 40; i >= 10; i--) {
                    if ( arr['o_field_' + i] != null && arr['o_field_' + i] != '' )
                    $('#others'+i).html(arr['o_field_' + i]).parent().show();
                }
            }
        }
    })
};

и php
<?php
//frontend
include_once('db.php');
$item_id = $_POST['item_id'];
try
            {
                $st2 = $db->query("SELECT * FROM other_shop1 WHERE item_id='".$item_id."'");
                $results2 = $st2->fetchAll();
                if ($results2)
                            {
                                foreach ($results2 as $row2)
                                {
                                  //echo "
";
                                      echo json_encode($row2);
                                  //echo "
";
                                }
                            }

            }
        catch (PDOException $e)
            {
                die($e->getMessage());
                echo "Ошибка.";
            }

?>

Если нужно добавить больше данных - сделаем. Буду благодарен за любую помощь.

A: Вообще то я не могу понять чем они вам мешают. Это делается автоматическим образом для того что бы избежать SQL инъекций. А если у вас в фронте строка экранированная то если его сунуть куда то в код HTML все ровно экранирование убирается браузером. А вот и пример, если я что то не так понял то скажите?
Это моя строка который я добавляю в textarea:
let str = '\"My name is Vsya\", My name is Petya\",....';

$(document).ready(function(){
    let str = '\"My name is Vsya\", My name is Petya\",....';
    $('#mytextarea').text(str);
});

<textarea id="mytextarea"></textarea>

А вот второй вариант который вы сказали, принудительно убрать экранирование прежде чем вывести контент на страницу. Для этого воспользуемся методом replase:
Вот второй пример кода:

$(document).ready(function(){
  let str_spec = '

$$<\/dt>
\"Вставляет \"$\"

$&<\/dt>
Вставляет \"совпавшую подстроку<\/dd>
$\`<\/dt>
Вставляет часть строки, которая предшествует совпавшей подстроке

$\'<\/dt>
Вставляет \"часть строки, которая следует за совпавшей подстрокой<\/dd>
$n или $nn, где n/nn<\/code> - десятичные цифры<\/dt>
Вставляет n-ю скобку в совпадении, если первый аргумент - объект RegExp<\/code><\/dd><\/dl>';

  str_spec = str_spec.replace(/\\/g,"")

  $('.no_spec').val(str_spec);
});

<textarea class="no_spec"></textarea>

Просто с помощью регулярки удалили обратный слеш.

A: Что-то мне подсказывает, что данный вопрос необходимо решить все же во время отправки данных. Из вашего сообщения следует, что данные отправляются, а затем возвращаются с обратным слешем. Скорее всего ваш сервер раздает _GET и _POST массивам эти самые слэши возле кавычек.
Если вы знаете, что такое экранирование, следовательно уже изучали возможности отключения. Если так, то я все же повторюсь, при отсутствии возможности редактирования .htacces или php.ini, вы можете выполнить отключение этих волшебных кавычек прямо в скрипте. Вот первый попавшийся пример из сети:
<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_gpc(&$value)
    {
        $value = stripslashes($value);
    }
    array_walk_recursive($_GET, 'stripslashes_gpc');
    array_walk_recursive($_POST, 'stripslashes_gpc');
    array_walk_recursive($_COOKIE, 'stripslashes_gpc');
    array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}
?>

Однако, далеко не всегда это может помочь. В этом случае, можно перейти к плану "Б". Использовать костыль. Воткну его в ваш пример, а вы уж потестируйте и сообщите, помогло ли это решению вашей задачи.
Весь участок копировать не буду, думаю, знаете где он находится:
$o_field_value = $_POST['o_field_value']; меняем на $o_field_value = html_entity_decode(stripslashes($_POST['o_field_value']),ENT_QUOTES,'UTF-8');
Не забывайте, что отключение экранирования может негативно сказаться на безопасности и работоспособности сайта.


text:
Q: how to Bind the EVT_TASKBAR_LEFT_DOWN in wxPyton for TaskBarIcon class I am new to Python and using wxPython to build a tool which can be minimize to system tray icon and can be restored when left clicked.
I have following code in Python 3. While searching online I found that I can bind the key like following snippet:
self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.OnTaskBarLeftClick)
However this is causing error saying that wx doesn't have this attribute.
I want to restore the main window when the task bar icon is left clicked, while right click creates a pop-up menu.
import wx
import wx.adv

class SysTrayMenu(wx.adv.TaskBarIcon):
    def __init__(self, frame, icon=None, menu=None):
       wx.adv.TaskBarIcon.__init__(self)
       self.frame = frame
       self.menu = menu
       self.icon = icon
       app_icon = wx.Icon()
       app_icon.CopyFromBitmap(wx.Bitmap(self.icon, wx.BITMAP_TYPE_PNG))
       self.SetIcon(app_icon)

       self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.OnTaskBarLeftClick)

   def OnTaskBarLeftClick(self, evt):
       self.frame.Show()
       self.frame.Recover()

   def CreatePopupMenu(self):
       new_menu = wx.Menu()
       return self.menu

A: Since the TaskBarIcon class is in the wx.adv module then the coresponding event binders and event type IDs are also in wx.adv.

A: I was doing it wrong. To make the menu pop-up I had to bind it with wx.EVT_MENU.
self.Bind(wx.EVT_MENU, self.click_me, id=self.m_cb.GetId())

A: Use the code below instead. Pls. note the event should be wx.adv.EVT_TASKBAR_LEFT_DOWN, not wx.adv.wxEVT_TASKBAR_BALLOON_CLICK. I was mislead by the prompts of pycharm before.
self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)


text:
Q: NSTableView weird issue I have implemented viewbased NSTableView. When i scroll downwards, lines are drawn at the bottom of the NSTableView. Even the text of the buttons which are not the part of NSTableView get darker. I removed the NSTableView Datasource method and buttons' texts are fine, but still lines are drawn at the bottom of the NSTableView.
I do not know weather these two things are connected. I would greatly appreciate your help.
Thanks.

A: This is general problem of NSScrollView, inside which lies your table view.
If table view's enclosing scroll view drawsBackground property is NO, uncheck Copy On Scroll too.
If the scroll view is overlapped by other views, either enable Core Animation layer on that views or eliminate overlapping.


text:
Q: two models in one action I get the feeling I am violating MVC best practise here, but I don't see how.
I have a form with two buttons with different names so when it gets posted to the action, I can do different things based on which button is pressed.
 @using (Html.BeginForm("Display", "PlayBoard")
// form properties
<button class="btn btn-primary" type="submit" name="Display">Filter PlayBoard</button>
<button class="btn btn-primary" type="submit" name="Report">Report View</button>

then in the controller:
[HttpPost, FlexAuthorize]
public ActionResult Display(FormInput filter )
{
    if (Request["Report"] != null)
    {
          var model = queryRepository.Load<FormInput , ReportViewPlayBoardView>(filter);
          return View(model);
    }
    if (Request["Display"] != null)
    {
        var model = queryRepository.Load<FormInput , DisplayPlayBoardView>(filter);
        return View(model);
    }

When I click the report button, it runs through the query ok but then comes back with the exception: "The model item passed into the dictionary is of type '...ReportViewPlayBoardView', but this dictionary requires a model item of type '...DisplayPlayBoardView'."
I don't really follow why this has to be a DisplayBoardView model that gets returned.
edit: fixed it, I just had to change the view command on the report branch to: return View("ReportView", model);

A: fixed it, I just had to change the view command on the report branch to:
 return View("ReportView", model);


text:
Q: JSplitPane won't resize when I use java.awt.Canvas? I have a simple example where I'm using java.awt.Canvas for components within a JSplitPane, and the JSplitPane won't allow adjustment. Could anyone explain why? (and more importantly, how to fix)
VerticalSplit.java:
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

abstract public class VerticalSplit {
    public VerticalSplit(JPanel panel)
    {
        panel.setLayout(new BorderLayout());
        JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            createComponent1(), createComponent2());
        jsp.setResizeWeight(0.5);
        panel.add(jsp, BorderLayout.CENTER);
    }
    abstract protected Component createComponent1();
    abstract protected Component createComponent2();
}

CanvasTest1.java:
import java.awt.Canvas;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CanvasTest1 extends VerticalSplit
{
    static public class PlainCanvas extends Canvas
    {
        @Override public void paint(Graphics g)
        {
            Dimension d = getSize();
            int h = getHeight();
            int w = getWidth();
            g.drawRect(0,0,w,h);
            g.drawLine(0,0,w,h);
            g.drawLine(0,h,w,0);
        }
    };

    public CanvasTest1(JPanel panel) {  super(panel); }

    @Override protected Component createComponent1() {
        return new PlainCanvas();
    }

    @Override protected Component createComponent2() {
        return new PlainCanvas();
    }

    public static void main(String[] args) {
        JPanel panel = new JPanel();
        CanvasTest1 test = new CanvasTest1(panel);

        JFrame frame = new JFrame(test.getClass().getName());
        frame.setContentPane(panel);

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

A: Changing from Canvas to JPanel (as @tulskiy suggested -- thanks!) made it work properly.


text:
Q: How do I stop a script from running on a mobile device How do I stop this --!DOCTYPE html-- with two scripts in it from running on mobile devices?
Hiding the div with the URL in it does not work, so apparently stopping one or both of the scripts is necessary. Thanks!
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-left-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-left-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};

</script>

<body>

<div w3-include-left-html="borders/border-left.html"></div>

<script>
includeHTML();
</script>

</body>
</html>

A: Detect a mobile browser using one of the methods here:
Detecting a mobile browser
If detected, return immediately.
Eg
<script>
function includeHTML() {
  if (mobilecheck()) {
      return;
  }

... code to run on desktops only

</script>


text:
Q: Audio power meter with PAM8403 and LM3915 I have a PAM8403 3W dual channel audio amplifier board bought from Amazon and I would like to connect one of it's output signals to LM3915 dot/bar display driver.
The problem is that PAM8403 outputs differential signals and I can't use that as an input to LM3915.

simulate this circuit – Schematic created using CircuitLab
I tried to couple R+ signal to the led driver using a 100uF electrolytic capacitor but that didn't work for some reason. How do I source the signal to the LM3915?

A: That PAM8403 is a class D amplifier so its output signal will be PWM (switched). So you need to filter the signal. Also, on average it will be half the supply voltage (as it switches between Vdd and ground) so you need to AC couple the signal as well as the LM3915 expects a ground referenced signal.
That the outputs af the amplifier are differential does not matter much, you can just use only one output. The other output carries the same signal but inverted (upside down). If you'd connect a speaker with a series capacitor between any of the outputs and ground, you'd hear the same signal (although inverted but your ear cannot detect that, only relative to another signal).
You could try this:

simulate this circuit – Schematic created using CircuitLab
C1 is the AC blocker cap
R1 and C2 are a low-pass filter with a cutoff frequency of around 10 kHz
This is just a suggestion and staring point. Don't blame me if it doesn't work as expected ;-)
You could also consider using the input signal of the PAM8403 as a signal for the LED driver. Optionally with a simple audio amplifier. A basic LM386 audio amplifier module will do the job and these are cheap.


text:
Q: How do I format my computer to be unrecoverable? I have a 500Gb HDD hard disk in my Laptop, and I want to sell it, so I am asking if I can format it such that no one can recover my old  data, and if yes, How can I do that?
Thanks in advance

A: You can securely delete all the files with a program like shred
It overwrites the files before deleting them, so that a recovery wont get success

You can also overwrite all the HDD and, then, format it

See shred program : http://manpages.ubuntu.com/manpages/trusty/man1/shred.1.html

Or overwrite with dd if=/dev/urandom of=/dev/sdX bs=4096 status=progress then format the drive


text:
Q: Ivy resolve failing for some users Certain developers on my project are unable to successfully execute an ivy resolve.  We use an ivy ssh resolver to a remote server/file system.  Impacted developers are typically resolving all but 1 or 2  dependencies successfully.  The dependencies that fail to be resolved are the larger jars (example: nasa worldwind).  Again, most users are able to resolve all dependencies with no problem. The eclipse project, ivy.xml and ivysettings.xml all come from the software repo and are identical between impacted and unimpacted users. If I copy the failed dependency from my ivy2 cache into an impacted users ivy2 cache, the problem goes away.  The ivy resolve is initiated through eclipse/ivyDE.
Things I believe are eliminated:

*

*differences in ivy.xml, ivysetings.xml, and eclipse project

*existance of dependency on server

*file permission issues on remote file system

*network connectivity

*version differences in eclipse/ivyDE

Question: What could be causing ivy resolves to fail for some users? I am starting to suspect this may be a timeout issue with ivy, given that it happens with larger jars.
Configuration:

*

*Eclispe Kepler

*IvyDE 2.2.0

example ivysettings.xml:
<ivysettings>
  <settings defaultResolver="test-chain" />
    <resolvers>
      <chain name="test-chain">
        <ssh name="test-cm" host="IPaddress">
          <ivy pattern="/cm/lib/[organisation]/[module]/ivys/ivy-[revision].xml"/>
          <artifact pattern="/cm/lib/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]"/>
        </ssh>
        <url name="test-cm-file">
          <ivy pattern="file://cm/lib/[organisation]/[module]/ivys/ivy-[revision].xml"/>
          <artifact pattern="file://cm/lib/[organisation]/[module]/[type]s/[artifact]-[revision].[ext]"/>
        </url>
      </chain>
    </resolvers>
</ivysettings>

example ivy.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="test"
        module="Application"
        status="integration">
    </info>
    <dependencies>
        <dependency org="nasa" name="worldwind" rev="1.4.0"/>
    </dependencies>
</ivy-module>

A: Using Eyad Ebrahim's suggestions, I was able to examine the IvyDE console and gain insight into the problem.  The issue turned out to be that several developers did not have an ivysettings.xml set in either the eclipse global or project IvyDE properties.  IvyDE was attempting to use an internet resolver by default, which resulted in two subsequent issues including no public repo for products like worldwind, and blocking of certain files by my company network infrastructure. After correctly configuring the ivysettings.xml file, the custom file/url resolvers listed above were used and everything worked.
Thanks!


text:
Q: guava-libraries: List with n instances The Java Collections class has the following method:
static <T> List<T> nCopies(int n, T o)

I need a similar method, but slightly more generic, which provides n instances of a given class. Something like:
static <T> List<T> nInstances(int n, Supplier<T> supplier)

In particular, if supplier is Supplier.ofInstance(o), we get the same behavior as the nCopies() method. Is there such a method somewhere in the Guava API?
Thank you.

A: No there isn't, and any equivalent construct (that just stores the int n and the supplier and calls the supplier for each get) seems like a terrible idea. That said, apparently you just want to read n objects from a Supplier and store them in a list. In that case, Sean's answer is probably best.
Just for fun though, here's another way you could create an ImmutableList of size n by calling a Supplier n times (transform, limit and cycle all from Iterables):
public static <T> ImmutableList<T> nInstances(int n, Supplier<T> supplier) {
  return ImmutableList.copyOf(transform(
      limit(cycle(supplier), n), Suppliers.<T>supplierFunction()));
}

I uh... wouldn't recommend this over a straightforward loop implementation though (for readability reasons mostly).

A: Like many other idioms, Java 8 finally delivers with a short and sweet version that doesn't need any external libraries. You can now do this with Streams.generate(Supplier<T> s). For example, for n instances of Foo:
Streams.generate(Foo::new).limit(n)...

You'd finish that line off in different ways depending on how you wanted to create your List. For example, for an ImmutableList:
ImmutableList.copyOf(Streams.generate(Foo::new).limit(n).iterator());

A: No, but it's easy enough to implement:
public static <T> List<T> nInstances(int n, Supplier<T> supplier){
    List<T> list = Lists.newArrayListWithCapacity(n);
    for(int i = 0; i < n; i++){
        list.add(supplier.get());
    }
    return list;
}


text:
Q: ERROR: invalid input syntax for type json DETAIL: Token "'" is invalid. while importing csv in pgadmin I have made a new table with three columns
customer_id,media_urls,survey_taste

in a db in pgadmin with attributes as
int,text[],jsonb

respectively.
I have a csv that I was trying to import into this table using pgadmin and
the contents of that file are like this
1,"{'http://example.com','http://example.com'}","{'taste':[1,2,3,4]}"

but I am getting this error
ERROR:  invalid input syntax for type json
DETAIL:  Token "'" is invalid.
CONTEXT:  JSON data, line 1: '...
COPY survey_taste, line 2, column survey_taste: "{'taste': [-0.19101654669350904, 0.08575981750112513, 0.07133783942655376, -0.10579014363010293, 0.0..." ```

A: To address your comments in reverse order. To have this entered in one field you would need to have it as:
'[{"http":"abc","http":"abc"},{"taste":[1,2,3,4]}]'
Per:
select '[{"http":"abc","http":"abc"},{"taste":[1,2,3,4]}]'::json;
                       json
---------------------------------------------------
 [{"http":"abc","http":"abc"},{"taste":[1,2,3,4]}]

As to the quoting issue:
When you pass a dict to csv you will get:
d = {"taste":[1,2,3,4]}
print(d)
{'taste': [1, 2, 3, 4]

What you need is:
import json
json.dumps(d)
'{"test": [1, 2, 3, 4]}'

Using json.dumps will turn the dict into a proper JSON string representation.
Putting it all together:
# Create list of dicts
l = [{'http': 'abc', 'http': 'abc'}, {'taste': [1,2,3,4]}]
# Create JSON string representattion
json.dumps(l)
'[{"http": "abc"}, {"taste": [1, 2, 3, 4]}]'


text:
Q: what is the difference between using the same value for two case labels and using several case labels for a single case? I was reading from Bjarne's Programming and Principles using C++.
I ran into the following details about switch:

You can use several case labels for a single case.
You cannot use the same value for two case labels.

I think I clearly understand the 2. one. It should mean that:
switch (a) {

  case 'c':{//some code}

  case 'c':{//some (different) code}
}

Is not legal.
However, I am not sure if the first one means, that if case no.1 and case no.2 and so on are different then I can have any number of cases(, of course them being constant expressions) or it means that I can have any number of cases, but some of them doing the same thing.
I have found a similar question regarding this:
 multiple label value in C switch case
Do I interpret it right? If not, what is it I am missing or get wrong?

A: This is allowed:
switch ( expression )
{
    case 1:
    case 2:
    case 3:
          //some code
          break;
    //...
}

And this is NOT allowed:
switch ( expression )
{
    case 1:
          //some code
          break;
    case 1:
          //some other code
          break;
    //...
}

A: It seems he means the following construction
switch ( expression )
{
    case 1: case 2: case 3:
       //some code
       break;
    //...
}

A:
You can use several case labels for a single case.

This just means that for any case you can use as many labels.
For example,
switch(choice) {
    // This is valid
    case 1:
    case 2:
        .
        .
    case n:
        printf("\nCase 1 and 2");
        break;
}

You might be wondering what's the use of having multiple labels for same case?
Consider an example of asking a user his/her grades of a subject. The user can enter the grades as A or a for grade A, B or b for grade B and so on. But you want to handle the cases ignoring whether the user input is capital or small. You can do this:
char choice;
printf("Enter your grades : ");
scanf("%d", &choice);

switch(choice) {
    case 'A':
    case 'a':
        printf("Excellent");
        break;

    case 'B':
    case 'b':
        printf("Good");
        break;
        .
        .
    case 'E':
    case 'e':
        printf("You failed");
        break;

    default:
        printf("Invalid grades");
}

A: I think it's a poorly worded way of saying you can have several labels (in reality, case labels or regular ones) on a single statement, or in other words, that you can make use of implicit fall-through.
Example:
bool a_or_b_eh(char Ch)
{
    switch(Ch){ //return true; is a single statement so the {} are optional here
        case 'a': case 'b': case 'A': case 'B': return true;
    }
    return false;
}


text:
Q: Why does LD_LIBRARY_PATH only works in ~/Desktop/? If I run application app from ~/Desktop/ I am getting:
/home/me/Desktop/app: error while loading shared libraries: somelib.so.0: cannot open shared object file: No such file or directory

So I have created this script called app.sh:
DIR="$(dirname "$0")"
export LD_LIBRARY_PATH=$DIR
$DIR/app

And then app runs.
However, I decided that I don't want to have it on the Desktop, but to have under ~/dev/apps/. So I move all files (app, somelib.so.0, app.sh) and get this error when I run the script:
/home/me/dev/apps/app: error while loading shared libraries: somelib.so.0: cannot open shared object file: No such file or directory

If I move it to ~/foo/bar/ still doesn't run.
Please note:

*

*All directories and files have the same permissions.

*All files are in the same directory.

*I call the script from ~/Destop/app.sh or ~/dev/app/app.sh.

*I am running it from /home/me
Is this a normal behavior or is there something wrong with my setup or configuration?

A: You can add explicit path in LD_LIBRARY_PATH like this:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/Desktop/app/lib

(use example path to the library)
Also you can add this in your .bash_profile
Also you can create softlink in /usr/lib to your library

A: I have realized that when copying all the files in Nautilus, the dynamic library was being copied as a soft link and the file size was much smaller.
Deleting library it and copying it again from bash fixed the problem.
I am adding Nautilus as a tag to the question.
However I cannot reproduce this issue anymore, even when copy-pasting again from Nautilus.


text:
Q: Endless 'Loading...' message after Login in Sugar 7.2.1 I am using the latest commercial version of SugarCRM, with 7.2.1 in Ubuntu 14.04.
I have logged-in to the sugar and it shows Endless 'Loading...' message. And there is one Fatal Error in my console i.e., TypeError: error.payload is undefined at cache/include/javascript/sugar_sidecar.min.js?v=v05JhcpoUqgUDSTVs1g86g on line 599"

A: I've seen this endless 'Loading...' message appear when some of the file & folder permissions are incorrectly set. The article here has resolved it for me: http://support.sugarcrm.com/04_Find_Answers/02KB/02Administration/100Install/Required_File_System_Permissions_on_Linux/
Ben.

A: Endless loading can be caused by a number of things, probably all of them JavaScript issues. The last few I encountered had to do with accessing the cached javascript files. Make sure you have mod_rewrite enabled if you're using Apache, and that .htaccess has the RewriteBase setting correctly pointing to the site. Also check config.php that site_url is correct.

A: The SugarCRM PHP code is horrendous and generates loads of errors (warnings/notices/etc.)
I would add the following, either in your Apache settings or the .htaccess file in the root directory of SugarCRM.
# Avoid all those strict warnings
php_value error_reporting 0

This technically turns off all the warnings and notices, some of which would be transformed to errors as your question seems to show.


text:
Q: A Counter Examples in Linear Algebra (Vector Space) I have been studying linear algebra for a few years now and in fact, also teaching it. What makes learning (and teaching) mathematics more interesting is to find examples and/or counterexamples of what we learn. As a process, I am trying to find counterexamples of sets along with two operations $+$ and $\cdot$, which we will call for the time being "addition" and "scalar multiplication" which do not form a vector space because they fail to satisfy exactly one of the axioms of a vector space.
If I am to list out the axioms and hence the definition, it proceeds as follows:-
A set $V$ along with two operations $+: V \times V \rightarrow V$ and $\cdot: \mathbb{F} \times V \rightarrow V$, where $\mathbb{F}$ is a field, is called a "vector space" over the field $\mathbb{F}$ if:

*

*$\forall x, y, z \in V$ we have $\left( x + y \right) + z = x + \left( y + z \right)$

*$\forall x, y, \in V$ we have $x + y = y + x$

*$\exists 0 \in V$ such that $\forall x \in V$, we have $x + 0 = x$

*$\forall x \in V$, $\exists y \in V$ such that $x + y = 0$

*$\forall x, y \in V$ and $\forall \alpha \in \mathbb{F}$, we have $\alpha \cdot \left( x + y \right) = \alpha \cdot x + \alpha \cdot y$

*$\forall x \in V$ and $\forall \alpha, \beta \in \mathbb{F}$, we have $\left( \alpha + \beta \right) \cdot x = \alpha \cdot x + \beta \cdot y$

*$\forall x \in V$ and $\forall \alpha, \beta \in \mathbb{F}$, we have $\alpha \cdot \left( \beta \cdot x \right) = \left( \alpha \beta \right) \cdot x$, where $\alpha \beta$ denotes the multiplication of $\alpha$ with $\beta$ in the field $\mathbb{F}$

*$\forall x \in V$, we have $1 \cdot v = v$, where $1 \in \mathbb{F}$ is the unity.

It is not so difficult (if not easy) to find counterexamples of sets, fields and operations which satisfy all but one property from $1$ through $7$. However, I have not yet been able to find an example which satisfy all properties except $8$ and hence fails to be a vector space. I would like some help in constructing such a counter example.

A: Take any nontrivial abelian group $V$ and any field $\mathbb{F}$, and define $c\cdot v = 0_V$ for all $c \in \mathbb{F}$ and $v\in V$.


text:
Q: sympy hangs when trying to solve a simple algebraic equation I recently reinstalled my python environment and a code that used to work very quickly now creeps at best (usually just hangs taking up more and more memory).
The point at which the code hangs is:
solve(exp(-alpha * x**2) - 0.01, alpha)

I've been able to reproduce this problem with a fresh IPython 0.13.1 session:
In [1]: from sympy import solve, Symbol, exp
In [2]: x = 14.7296138519
In [3]: alpha = Symbol('alpha', real=True)
In [4]: solve(exp(-alpha * x**2) - 0.01, alpha)

this works for integers but also quite slow. In the original code I looped over this looking for hundreds of different alpha's for different values of x (other than 14.7296138519) and it didn't take more than a second.
any thoughts?

A: The rational=False flag was introduced for such cases as this.
>>> q=14.7296138519
>>> solve(exp(-alpha * q**2) - 0.01, alpha, rational=False)
[0.0212257459123917]

(The explanation is given in the issue cited above.)

A: Rolling back from version 0.7.2 to 0.7.1 solved this problem.
easy_install sympy==0.7.1

I've reported this as a bug to sympy's google code.

A: I am currently running sympy ver: 1.11.1
This is for all I know the latest version.
However, hanging as was described, when solving a set of 3 differential for 3 angular double differentials persist.
Eg.:
sols = solve([LE1, LE2, LE3], (the_dd, phi_dd, psi_dd),
             simplify=False, rational=False)


text:
Q: Symbolic Expectation Value Evaluation Suppose an expression $Y=a +b X$, where $X$ is a random variable. I would like to find the 2nd order central moment of $Y$ in terms of the expectation value of $X$. For example,
$$E[Y] = a + b E[X]$$
and
$$E[Y^2] = a^2 + 2a b E[X] + b^2E[X^2]$$
which gives
$$Var(Y) = E[Y^2] - E[Y]^2 = b^2E[X^2] - b^2E[X]^2$$
Can this be done using Mathematica? I am new to this environment, so please pardon me if I have not shown enough effort.
Arvind


text:
Q: how to get type of auto variable in C++ I want gets the type of the auto variable and forces another variable become this type,i don't know whether  c++ has such feature or function.

A: Use decltype.
auto a = 42;
decltype(a) b;


text:
Q: Changing IP of the machine at regular intervals I have a pool of public IP addresses. There are some services in my box which binds to these. What i'm trying to achieve is to automate the IP change process.
Best way to do this is to write a script which will do the following:
0) Kill the services which are bound the current IPs
1) Read the current IP address of an interface.
2) Pick a IP from the pool statically given in the script with the restriction that it won't pick the IP which is currently in use.
3) Change the IP using $ip or $ifconfig
4) Restart the Services
I do this manually like below:
ifconfig eth0:0 "existing ip" netmask "address" broadcast "address" down
ifconfig eth0:0 "new ip" netmask "address" broadcast "address" up
pkill service1
./service -l "new ip address"

How should i do this?

A: I am not quite sure how you can change IP without modifying all ip bindings in the application configurations.
What about move to IPv6 and use lifetime in RA to perform graceful host ip change?
What's the purpose of changing IP addresses? I think it might be easier to deal with ip change from a higher level (load-balancer, firewall etc.)


text:
Q: Can't find Truffle Worm I have defeated all of the main bosses except for Duke Fishron. But i have been searching for about a week and haven't seen a Truffle Worm! So i was wondering if there where any tips or tricks out there, since there's nothing on the Official Wiki.

A: Truffle Worms can actually be found in glowing mushroom biomes which are mostly underground. In order for them to spawn you need to have hard mode enabled so that means you need to defeat the Wall of Flesh first before they start spawning in glowing mushroom biomes. You can catch a Truffle Worm by using a bug net.