text:
Q: Unit Testing an SOA WCF system...finding it difficult to get decent coverage We are currently replacing a 20 year old C based system with a modern SOA WCF system built in .NET3.5. Our industry requires rigorous testing including good automated unit test converage. We are having issues, however unit testing our SOA system to anywhere near the extent that the C based system was unit tested.
The single biggest problem is that most of the methods in the system are actually dependant on calling into code across service boundaries, for example we are heavily data driven but we don't access the database directly within our system: we call into a WCF Data Access Service.
Running any unit tests in visual studio is almost impossible as doing almost anything results in cross service calls of some kind. If its not data access its one of the other services. I reckon we can get about 5% coverage.
I see alot of people struggle with testing SOA so I take it this is not unique to us. The thing is QA is going to question why we are not unit testing more of the system.
To be honest I see VSTS unit testing as more of a regression testing than a validation (fit for use) tool. What options are there for unit testing SOA? Is it realistic in peoples experience to achieve good coverage? Is there a way to mock a Data Access Service (or any service: NOTE we dont use WCF proxies) or do we have to explain to QA that unit testing ability has gone backwards over the last 20 years...
Any sort of suggestions are welcome, I guess this is a general opinion question.

A: I'd have to say that unit-testing an SOA is a lot like unit-testing anything else.  If anything it should be easier because it forces you to isolate dependencies.
Unit tests shouldn't generally cross service boundaries.  Really, the idea of a service is that it is completely independent and opaque.  You test the service directly - not over the WCF channel, but by unit-testing the actual classes that compose the service.  Once you've tested the service itself (which you should be able to get near 100% coverage), you don't need to involve it in client-side tests.
For client-side unit tests, you mock the service.  WCF actually makes this very easy for you because every WCF client implements an interface; if you normally use the FooService or FooServiceSoapClient in your code, change it to use the corresponding IFooService or FooServiceSoap that the proxy class implements.  Then you can write your own MockFooService that implements the same interface and use that in your client tests.
Part of what sometimes trips people up here is the idea that the service can do wildly different things depending on the specific message.  However, a client test that involves the service interface should generally only be testing one or two specific messages per test, so it's easy to mock the exact request/response you need for a given client test using a tool like Rhino Mocks.
Duplex gets a little tricky but keep in mind that duplex services are supposed to be based around interfaces as well; even the MSDN example introduces an ICalculatorDuplexCallback.  Callbacks will be interfaces, so just like you can mock the service methods on the client side, you can mock the client callbacks on the service side.  Just have mock/fake callbacks that you use for the service unit tests.
Mark Seeman has a pretty good blog post all about Unit-Testing Duplex WCF Clients, with example code and all.  You should give that a read, I think it will help you out here.

A: It sounds like the testing you are doing now is integration tests or system tests.  Where the test methods are calling external sources.  To truly perform unit testing on a service you will need to somehow abstract the external calls out so you can mock (for example moq) or stub the calls to that service.
For example Code that is tightly coupled to the Data Access Service:
public class SomeSOA
{
 public bool DoSomeDataAccess()
 {
  //call the real data service
  DataService dataService = new DataService()
  int getANumber = dataService.GetANumber();
  return getANumber == 2;
 }
}

Slightly refactored to reduce coupling to the DataService
public class SomeSOA
{
 IDataService _dataService;
 public SomeSOA(IDataService dataService)
{
  _dataService = dataService;
}
public SomeSOA() :this(new DataServiceWrapper()){}
 public bool DoSomeDataAccess()
 {
  int getANumber = _dataService.GetANumber();
  return getANumber == 2;
 }
}

public DataServiceWrapper : IDataService
{
  public int GetANumber()
  {
   // call the real data service
  }
}

Now with the re-factored code you can modify your tests to use a stub that can return expected results without calling the real DataService.
[TestMethod]
public void GetANumber_WithAValidReturnedNumber_ReturnsTure()
{

  IDataService dataService = new DataServiceFake();
  SomeSOA someSoa = new SomeSOA(dataService);
  Assert.IsTrue(someSoa.DoSomeDataAccess();
}

public class DataServiceFake :IDataService
{
  public int DoSomeDataAccess()
  {
    //return a fake result from the dataService.
    return 2;
  }
}

Now granted all of this is just pseudo code, but decoupling your service from the real implamentation of the DataAccessSerive will allow you to unit test your code and not rely on a real DataAccessService for them to perform correctly.
Hope this helps and makes sense!

A: Here's my suggestion: step away from the "Unit Testing" paradigm, and work on a suite of integration tests.
I assume that your system has a front end which calls the services.
Write a test suite that actually connects to running services (in your test environment obviously) and makes the same sequence of calls as your front end does.
Your test environment would have the latest services running against an empty test database. Just like with unit tests, each test would make the calls that populates the test data with just what it needs, invoke functionality, test that the visible information now matches what it should, then clears the database again.
You may have to create one other service that services the integration tests by clearing the database on request. (Obviously, you wouldn't actually deploy that one...)
While they are not "Unit tests", you would be getting full coverage.


text:
Q: Is it right that the fundamental recurrence of an arbitrary continued fraction cannot be proved without induction? Let $\dfrac{A_{n}}{B_{n}}$ be the $n^{th}$ convergent (approximant)
$$

\frac{A_{n}}{B_{n}}=b_{0}+\dfrac{a_{1}}{b_{1}+\dfrac{a_{2}}{b_{2}+\dfrac{a_{3}}{\begin{array}{c}
b_{3}+ \\
\\
\end{array}
\begin{array}{cc}
\ddots  &  \\
&
\end{array}
+\dfrac{a_{n-1}}{b_{n-1}+\dfrac{a_{n}}{b_{n}}}}}}
$$
of a continued fraction. $A_{n}$, $A_{n-1}$, and $A_{n-2}$ satisfy the
recurrence
$$
\begin{eqnarray*}
\begin{pmatrix}
A_{n} \\
B_{n}
\end{pmatrix}
&=&
\begin{pmatrix}
A_{n-1} & A_{n-2} \\
B_{n-1} & B_{n-2}
\end{pmatrix}
\begin{pmatrix}
b_{n} \\
a_{n}
\end{pmatrix}
\quad \text{for }n\geq 1, \\
&& \\
\text{and }
\begin{pmatrix}
A_{-1} & A_{0} \\
B_{-1} & B_{0}
\end{pmatrix}
&=&
\begin{pmatrix}
1 & b_{0} \\
0 & 1
\end{pmatrix}
,
\end{eqnarray*}
$$
which may be proved by induction.
Question: Is there a non inductive proof?
EDIT: I changed the title. Based on the comment below by anon

The numerators and denominators are defined inductively - and I don't
  believe you'll find an explicit formula for the n-th convergent of an
  arbitrary continued fraction (though maybe of particular ones with
  specific patterns, like $\varphi$) - so I don't see any other way to
  say prove anything about the convergents except inductively.

I reformulate the question to
Question: Is it right that the fundamental recurrence of an arbitrary continued fraction cannot be proved without using mathematical induction?

A: A continued fraction may be defined

*

*as a composition of linear fractional transformations;

*as an expression of the form
$$b_0 + \cfrac{a_1}{b_1 + \cfrac{a_2}{b_2 + \cfrac{a_3}{b_3 + \cfrac{a_4}{b_4 + \ddots\, \quad }}}}$$

*by the fundamental recurrence itself.

In both cases 1 and  2 the recurrence relation is proved by induction, as far as I have seen, namely in recent books.
For a generic continued fraction I now think there is no other way of deriving the fundamental recurrence either from 1 or 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to print all check and print all prime number from an array index? I have an array each index has a five(5) digit number. I would like to check & print all the prime numbers that are in each of the five digit index. How can I do this?
My code:
public static void employeeID() {
    Scanner in = new Scanner(System.in);
    int emplID[] = { 43233, 71753, 97135 };

    for (int i = 0; i < emplID.length; i++) {
        if ((emplID[i] > 10000) && (emplID[i] < 99999)) {
            System.out.print(emplID[i] + " - Valid ID length\n");

        } else {
            System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
            emplID[i] = in.nextInt();
        }

        for (int j = 2; j < emplID[i]; j++) {
            if (emplID[i] % j == 0) {
                // isPrime = false;
                System.out.println(emplID[i] + " - valid prime");
            } else
                System.out.println(emplID[i] + " - not prime");
            break;
        }
    }
}

A: Update your loop with
for (int i = 0; i < emplID.length; i++) {
        if ((emplID[i] > 10000) && (emplID[i] < 99999)) {
            System.out.print(emplID[i] + " - Valid ID length\n");

        } else {
            System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
            emplID[i] = in.nextInt();
        }
        boolean isPrime = true;
        for (int j = 2; j < emplID[i]; j++) {
            if (emplID[i] % j == 0) {
                System.out.println(emplID[i] + " - not prime");
                isPrime = false;
                break;
            }
        }
        if(isPrime) System.out.println(emplID[i] + " - valid prime");
    }

A: You were on the right track with your commented out line isPrime = false;.  Your current problem is that you have your if statement inside your for loop, which means the program makes a determination about whether the number is prime on the first iteration.  That means that unless the number is divisible by 2, your program prints "not prime" and breaks out of the loop.  You need to use a boolean flag to keep track of whether the number has been declared prime yet, and then only print after the whole loop has completed.  Below is an example of how to do this, with comments at every step:
boolean isPrime = true; //assume the number is prime to start with
for (int j = 2; j < emplID[i] / 2; j++) { //you only need to loop up to emplID[i] / 2
    if (emplID[i] % j == 0) { //if the number is divisible by j
        isPrime = false; //set the boolean flag to false (this number is not prime)
        break; //break out of the loop (we have no more testing to do)
    }
}

if (isPrime) { //now that the loop has finished, if the boolean flag is still true, the number must be prime
    System.out.println(emplID[i] + " - valid prime");
} else {
    System.out.println(emplID[i] + " - not prime"); //otherwise, it was divisible by some number in the loop, so it is not prime
}

It's worth noting that your test case {43233, 71753, 97135} contains only composite numbers, so you aren't really testing your program.  Try adding a number like 14717.


text:
Q: Curved block in CSS3 I was wondering if there is a way to have a block with [this shape][1] (any CSS solution, 3D too).
I tried with border-radius but you can't have negative values.
Thanks.
EDIT:
I'm sorry for the lack of informations but I's lie a block, not a border (the image wasn't good, my bad).
Actually it's for a ribbon, I'd like it to be a bit curved, like this one, and because I have to write text in it, it can't be a border.
And it would be great if it is doable in CSS and not Canvas/SVG.
Thanks again.
EDIT:
Done! More details here: http://forrst.com/posts/CSS3_Curved_Ribbon-IyB

A: http://jsfiddle.net/efortis/E6SRf/1

.shape{
 border-radius: 600px;
 width: 600px;
 height: 600px;
 border: 4px solid black;
}

.clipper {
 width: 610px;
 height: 150px;
 overflow:hidden;
}

A: Directly copying from this site:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

var centerX = 288;
var centerY = 160;
var radius = 75;
var startingAngle = 1.1 * Math.PI;
var endingAngle = 1.9 * Math.PI;
var counterclockwise = false;

context.arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise);

context.lineWidth = 15;
context.strokeStyle = "black"; // line color
context.stroke();

This produces this arc.

A: Here's one more using the :after psuedo-element. Same clipping idea as the other CSS answer, just hiding the overflow so the border appears less round.
Markup:

CSS:
div:after {
    content:" ";
    height:80px;
    display:block;
    width:160px;
    border-radius:80px 80px 0 0;
    border:2px solid #000;
    border-bottom:0;
}

div {
    height:40px;
    overflow:hidden;
}

Demo: http://jsfiddle.net/Cbm7n/1/


text:
Q: Get Entity subobject id without joining or new sql request Example I have a Entity User which have a Contact. How I get the Contact ID without joining the contact table.
$user = $entityManager->userRepository->findUserById(1);
$contactId = $user->getContact()->getId();

when `getContact() is called the whole contact is loaded from the DB. How I can avoid this SQL request without add a join in findUserById. I only need to contactId which is in my users table, but there is no simple function like $user->getContactId().

A: Look at this post Getting only ID from entity relations without fetching whole object in Doctrine. I tested a simple example in a ManyToOne relation and the related object was not loaded.

A: Your situation sounds perfect for the Doctrine Second Level Cache
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/second-level-cache.html
With this, the first query will be gotten from DB but every subsequent query will be from the second level cache, plus if you change the data using doctrine then the cache is automatically updated. For this reason, I suggest you set a very long time for the cache my personal favourite is 1 month approx 2592000 seconds.
Enable it in your user entity like so
<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="users_region")
* @ORM\Table(
*   name="site_users",
*   indexes={
*       @ORM\Index(name="username_index", columns={"username"}),
*       @ORM\Index(name="email_index", columns={"email"}),
*       @ORM\Index(name="enabled_index", columns={"enabled"}),
*       @ORM\Index(name="last_login_index", columns={"last_login"})
*   }
*)
*/
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

......
Then in your config.yml like so
    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        entity_managers:
            default:
                connection: default
                auto_mapping: true
                naming_strategy: doctrine.orm.naming_strategy.underscore
                second_level_cache:
                    enabled:            true
#                    region_lock_lifetime: 60
                    region_lifetime:    300
                    log_enabled:        %kernel.debug%
                    region_cache_driver: apc
                    regions:
                        users_region:
                            region_lifetime:    2592000
                            region_cache_driver: apc

............
More information here
http://symfony.com/doc/master/bundles/DoctrineBundle/configuration.html
Note this method also ensure that the popular check for an authenticated user $user = $this->getUser(); does not hit your DB as well.

A: I suggest you to change fetch mode in the specific query, as described here in the doc.
So you can describe your query as follow:
// Supposing this method in the repository class
public function findUserById($idUser)
{
$qb =  $this->createQueryBuilder('u')
        ->where("u.id = :idUser")
        ->setParameter("idUser", $idUser);

        $query = $qb->getQuery();
        // Describe here all the entity and the association name that you want to fetch eager
        $query->setFetchMode("YourBundle\\Entity\\Contract", "contract", ClassMetadata::FETCH_EAGER);
        ...

return $qb->->getResult();
}

NB:

Changing the fetch mode during a query is only possible for one-to-one
  and many-to-one relations.

Hope this help


text:
Q: What is a password dialog in plymouth? I was currently learning to create plymouth themes/scripts from this link while following the guide i came across the Plymouth.SetDisplayPasswordFunction area, and after quite an amount of searching on the internet i got lots of information on creating password dialogs in plymouth themes.
I don't understand what is a password dialog doing at such an early phase of booting.I assume that it should show when the GDM has started and plymouth has exited.
I am totally confused, please someone explain me what is it in details and what does it do..

A: Certain cases of disk encryption require you to enter a passphrase during boot to unlock the root partition, else the system can't continue booting, because it can't get its data from disk.
Only the boot partition won't be encrypted (or is unlocked by GRUB), so the kernel and the initramfs can still be loaded. But that alone makes a very poor experience, with only BusyBox as a shell and no files to work with.
Without a Plymouth splash, the password prompt will simply be written on the TTY, e.g. something like this:

With Plymouth, you can have a password prompt drawn over the boot splash. Here are some examples:

(All images taken from Google Image Search)


text:
Q: Setting up VNC viewer for remote server I have a remote server (Unix) that I've used via PuTTY SSH from my laptop (Windows 7). However, I want to have a GUI to run a certain program on that server. I've tried X11 forwarding, but the GUI it created was far too slow.
So I thought maybe something like TightVNC viewer could work better. I installed it, tried logging into my server, and got the following error:
Error in TightVNC viewer: No connection could be made because the target machine actively refused it.

I ensured no other programs were connected to the server.
Do I need to install and set something up on my server first to make the VNC thing work? If so, how? Thanks, and excuse my temporary cluelessness.

A: The error you received is due to the fact that there is TightVNC server running on your (no pun intended) server. You have to install it there. Tightvnc has its own server, but it does not run on Unix machines.
However, there are many possibilities, depending exactly on the brand of Unix you are running. Just Google it.


text:
Q: can not display image from jsp file I am trying to display image from jsp file, below it is shown, and directory in java file : webapp/webresources/images/img.jpg.   And jsp files also in webapp folder: webapp/index.jsp.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<html>
<head>

      <link rel="stylesheet" type="text/css" href="<c:url value = "/webresources/styles/style.css"/>" />

</head>
<body>[enter image description here][1]

    <img src="${pageContext.request.contextPath}/webresources/images/eclipse.png" alt="photo"/>

</body>
</html>


text:
Q: Mongoose Query update, $pull, multi A short and simple question.
Would someone be kind enough to tell me what the Mongoose equivalent of this Mongo query would be...
db.users.update({ groups: "d" },{ $pull: { groups: "d" } },{ multi: true })

Just getting my head around more basic mongoose queries but struggling with some of the more complex stuff. Think this will help me see lots of the basic principles.
Thanks!!!
Schema as requested (relevant part only)...
var UserSchema   = new Schema({
    //....other fields
    group: [Schema.Types.ObjectId],
    //....other fields
});

....

module.exports = mongoose.model('User', UserSchema);

The 'd' in my question was just an example, it would actually be a 'group id' in my app.
Solution thanks to chridam...
var conditions = { group: groupId };
var update = { $pull: { group: groupId }};
var options = { multi: true };

User.update(conditions, update, options, callback);
function callback (err, numAffected) {
    // Do things here
}


text:
Q: How to know whether the intent is finished or not? I want to know after my application call an intent, it is finished or not. If it is finished, then call another activity. How can do this? Thank you.
 Intent callintent = new Intent(Intent.ACTION_CALL);
 callintent.setData(Uri.parse("tel:" + num));
 startActivity(callintent);
 if(callintent is finished)
 {
     startActivity(new Intent(MakeCall.this, NewActivity.class));
 }

A: PhoneStateListener helps    when a phone call is ended, come back to the original activity (actually, it just restart the activity).
MainActivity .java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

final Context context = this;
private Button button;

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    button = (Button) findViewById(R.id.buttonCall);

    // add PhoneStateListener
    PhoneCallListener phoneListener = new PhoneCallListener();
    TelephonyManager telephonyManager = (TelephonyManager) this
        .getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);

    // add button listener
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:1234567890"));
            startActivity(callIntent);

        }

    });

}

//monitor phone call activities
private class PhoneCallListener extends PhoneStateListener {

    private boolean isPhoneCalling = false;

    String LOG_TAG = "LOGGING 123";

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {

        if (TelephonyManager.CALL_STATE_RINGING == state) {
            // phone ringing
            Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
        }

        if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
            // active
            Log.i(LOG_TAG, "OFFHOOK");

            isPhoneCalling = true;
        }

        if (TelephonyManager.CALL_STATE_IDLE == state) {
            // run when class initial and phone call ended,
            // need detect flag from CALL_STATE_OFFHOOK
            Log.i(LOG_TAG, "IDLE");

            if (isPhoneCalling) {

                Log.i(LOG_TAG, "restart app");

                // restart app
                Intent i = getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(
                        getBaseContext().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);

                isPhoneCalling = false;
            }

        }
    }
}

}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/buttonCall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="call 1234567890" />

 </LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    <activity
        android:label="@string/app_name"
        android:name=".MainActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


text:
Q: Swift debugging on Linux - Missing Backtrace I have a crash which I am trying to locate, and even building the application as debug and executing it I don't seem to get any symbolic information.
The output I receive at the console is:
fatal error: unexpectedly found nil while unwrapping an Optional value
Current stack trace:
0    libswiftCore.so                    0x00007f1c51ca51c0 swift_reportError + 120
1    libswiftCore.so                    0x00007f1c51cbfbe0 _swift_stdlib_reportFatalError + 62
2    libswiftCore.so                    0x00007f1c51ab9be6 <unavailable> + 1186790
3    libswiftCore.so                    0x00007f1c51c18ead <unavailable> + 2625197
4    libswiftCore.so                    0x00007f1c51ab9be6 <unavailable> + 1186790
5    libswiftCore.so                    0x00007f1c51bd4060 specialized _fatalErrorMessage(StaticString, StaticString, file : StaticString, line : UInt, flags : UInt32) -> Never + 96
6    myProgram                          0x000000000045909e <unavailable> + 364702
7    myProgram                          0x0000000000423f37 <unavailable> + 147255
8    libdispatch.so                     0x00007f1c5276e177 <unavailable> + 278903
9    libdispatch.so                     0x00007f1c52779edd <unavailable> + 327389
10   libdispatch.so                     0x00007f1c5277a890 <unavailable> + 329872
11   libdispatch.so                     0x00007f1c5277c5f4 <unavailable> + 337396
12   libdispatch.so                     0x00007f1c5279aa18 <unavailable> + 461336
13   libpthread.so.0                    0x00007f1c50c6f6ba <unavailable> + 30394
14   libc.so.6                          0x00007f1c4f7b9370 clone + 109
Illegal instruction (core dumped)

I simply cannot find any way to expand on this information, and although I could go looking through a map file.  I feel that we have moved very much beyond that territory now with modern tooling.
Does anyone have any pointers, or indeed knows how to produce a build with more information in it.
Ubuntu 16.04, Swift 3.1.1

A: So, sadly this seems to be a bug in lldb, which uses local symbols in ELF executables, and dladdr cannot find them on linux platforms.
See the bug report here:
https://bugs.swift.org/browse/SR-755
ATTENTION:
Great news though, there is a bash script which does all the work for you.  Instruction's are slight, but this is what you need to do:
Download this script:
https://raw.githubusercontent.com/apple/swift/master/utils/symbolicate-linux-fatal
Exectute your crashing app.
$ myApp &> crash.log

Then execute the script.
$ ./symbolicate-linux-fatal myApp crash.log

It has helped me out no end.
Using LLDB
You can also use the swift debugger to help if still in the development stage.
Also if you execute lldb yourexecutable, then run.  You will pause and able to fully debug your application.

A: Enable Core Dumps on Linux, and use gdb to get a back trace.

*

*Enable core dumps by modifying /etc/security/limits.conf

*

*In that file, add the following two lines

*

** soft core unlimited

** hard core unlimited

*Log out of the shell, then log back in (no restart required)

*Double check the modification worked

*

*$ ulimit -c should return unlimited

*Run your program, when it crashes, a file name core will appear in the same directory

*debug using $ gdb <executable> <core-file>
Example
$ mkdir testCore && cd testCore
$ touch app.swift
// app.swift
func thisWillCrash()
{
    fatalError("crashing on purpose")
}

func wrapperFn()
{
    thisWillCrash()
}

wrapperFn()

$ swiftc -g app.swift
This will output an executable named app. Run it:
$ ./app
It will crash and now you will have a file named core alongside app.swift and app
Use gdb to get the backtrace:
$ gdb app core
After gdb starts and you get to the gdb prompt, run the bt command. On my Raspberry Pi 3B running Raspbian Buster, running Swift 5.1.5 this is the back trace I get:
(gdb) bt
#0  0x76d5c974 in $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_SSAHSus6UInt32VtFTf4xnnnn_n () from /home/pi/swift/usr/lib/swift/linux/libswiftCore.so
#1  0x76aa07b8 in $ss17_assertionFailure__4file4line5flagss5NeverOs12StaticStringV_SSAHSus6UInt32VtF
    () from /home/pi/swift/usr/lib/swift/linux/libswiftCore.so
#2  0x004f4ab8 in $s3app13thisWillCrashyyF ()
#3  0x004f4ad0 in $s3app9wrapperFnyyF ()
#4  0x004f49c4 in main ()

When I do this on a real project with multiple files and using spm to build, the back trace includes correct file names and line numbers.


text:
Q: Anti-Cauchy Sequences We say a real valued sequence $(a_{n})_{n\geq0}$ is anti-Cauchy if $\forall\varepsilon>0$, there exists some $N\in\mathbb{N}$ such that :
$$
|a_{n}-a_{m}|>\varepsilon\quad\forall m,n>N,\;m\neq n
$$
For natural numbers K, we define the $K^{th}$ difference sequence $D_{i}(k)$ of a sequence $a_{n}$ and the $K^{th}$ sum sequence $S_{i}(k)$ of a sequence $a_{n}$ as follow : (note that $i\geq0$)
$$
\begin{align}
D_{i}(k)=&
\begin{cases}
D_{i}(0)=a_{i}\\
D_{i}(k+1)=D_{i+1}(k)-D_{i}(k)&\text{for $k\geq0$}
\end{cases}
\\
\\
\qquad
S_{i}(k)=&
\begin{cases}
S_{i}(0)=a_{i}\\
S_{i}(k+1)=\displaystyle\sum_{r=0}^{i}S_{r}(k)&\text{for $k\geq0$}
\end{cases}
\end{align}
$$
$1)$ Does there exist for each natural number $K$, a sequence such that its $k^{th}$ difference sequence is actually anti-Cauchy if and only if $k\leq K$ ?
$2)$ Does there exists a real valued sequence, not identically $0$ such that its $K^{th}$ sum sequence is never anti-Cauchy for any natural $K$?
UPDATE :
I would like to thank mathworker21 for his partial answer, I would also thank for T.H. Shehadi for his guess for part $(1)$ yet I am unsure if it is a correct answer or not I am still looking for a credible answer for $(1)$.
PROPOSITION :
T. H. Shehadi has offered an alternative definition for the $K^{th}$ difference sequence and $K^{th}$ summation sequence that would describe difference sum an in terms of partial sum I hope it could help in solving $(1)$  :

$(1)$ : Let Λ map sequences to sequences so that $\Lambda(a_{0})=a_{0}$ and $\Lambda(a_{n+1})=a_{n+1}−a_{n}$. We say that $\Lambda^{k}(a)$, i.e. $\Lambda$ composed with itself $k$ times, is the $k^{th}$ difference sequence of $a$.

$(2)$ : Let $\Omega$ map sequences to sequences such that $\Omega(a_{n})=a_{0}+a_{1}+\cdots +a_{n}$. We say that $\Omega^{k}(a)$ i.e. $\Omega$ composed with itself $k$ times, is the $k^{th}$ summation sequences of $a$ where $\Omega^{0}(a)=a$

A: The answer to (2) is yes.
Consider the pattern $x_1,x_2,\dots = 1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,\dots$.
Our real-valued sequence will start off with $a_1 = 1$. With $a_1,\dots,a_{n-1}$ chosen, we choose $a_n$ so that $S_n(x_k) = S_{n-1}(x_k)$, which is possible, since $S_{n-1}(x_k)$ just depends on $a_1,\dots,a_{n-1}$ and since $S_n(x_k)$ depends linearly on $a_n$.
We claim the $K^{\text{th}}$ sum of $(a_n)_n$ is anti-cauchy for all $K \ge 1$. Indeed, fix $K \ge 1$, and just note that, by construction, we have $S_n(K) = S_{n-1}(K)$ for infinitely many $n$.


text:
Q: MongoDB GetDate Syntax In SQL Server while trying to insert records you have the option to specify
GETDATE()-1, GETDATE()

I tried below statement for MongoDB
db.TableA.insert({Name:ABC,SaleDate:this.date.getDate-1,SaleValue:2500,City:XYZ})

This does not work. What is the MongoDB equivalent syntax to insert getDate value for a table column?
I am also looking into MongoDB documentation, but I am still figuring it out.

A: Just typing "new Date()" should do it.
http://www.mongodb.org/display/DOCS/Dates


text:
Q: AddressBook with Automatic Reference Counting Hi I have the following piece of code:
ABMultiValueRef multi = ABRecordCopyValue([people objectAtIndex:i], kABPersonPhoneProperty);

I'm getting an error saying that there is no matching function for call to ABRecordCopyValue. I'm using automatic reference counting and I'm almost certain thats why I'm getting this error. At this point in development it will be a paint to revert to normal reference counting.
Anyone know a solution?
Thanks

A: Please try below
ABRecordRef people = ABPersonCreate();

ABMultiValueRef multi = ABRecordCopyValue(people,kABPersonPhoneProperty);


text:
Q: Sys admin logging in as Integration user and creating accounts. Should you see the integration user be the account owner If I have a sys admin logging on as an integration user and creating accounts.  Shouldn't the integration user be the account owner and not the sys admin.
Does SF look at the IP address when a user is logging in? I have a user in the sandbox who is a sys admin and he logged out and cleared his cache and logged in as a integration user but SF looks at the IP address and I wonder they see that IP address and automatically think this is the sys admin user.

A: The session ID is explicitly tied to a user. By default, the owner of a record is the person who creates it. However, there are a number of reasons why the ownership could change, including triggers, workflow rules, territory assignment rules, process builders/flows, and more. In order to determine what's causing it, you'd need to turn on the debug logs (Setup > Monitoring > Debug Logs) for that user and search through it for a change to the OwnerId field.


text:
Q: sort an array of object inside that is object inside array var Arryofobject = [{
a= "string",
b = {pos:[1,2,...],kind:[bar,bar1,...],name:[foo,foo1,...],val:[20,30,...]}
}]

the above syntax presenting my question,
the variables are taken from an html input ,
the output is of course without the key ,
1 bar foo 20
2 bar1 foo1 30
i need to run a function that sorts b.val and arrange all object with the bigger value  to be the first position in the output , meaning
2 bar1 foo1 30
1 bar foo 20

*

*the pos need to be left with the value .

*foo1- could be blabla as well so the 1 attached to foo shpuld not be considered.

i have tried to use the map , but return always blocking me to continue count my index .


text:
Q: Creating types for nested destructuring I'm attempting to set a type for nested destructured object.
Here is the code in which I'm handling:
import { useGLTF, useTexture } from "@react-three/drei";
import * as THREE from "three";

interface ModelInterface {
  [name: string]: THREE.Mesh;
}

export default function Room() {
  const {
    nodes: { Room },
  }: { nodes: ModelInterface } = useGLTF("./models/room/room.glb");
  const bakedTexture = useTexture("./models/room/baked.png");
  bakedTexture.flipY = false;

  return (
    <mesh geometry={Room.geometry}>
      <meshBasicMaterial map={bakedTexture} />
    </mesh>
  );
}

I will be receiving this response, This is the nodes log.
{
   Room: Mesh {
      ...data from mesh
   },
   Scene: Group {
      ...data from group
   }
}

for some reason the Room.geometry was no getting caught it was saying it was not a property, although it is, this is why I'm creating a type.

This is the type error I get from the destructured Room:
Type 'GLTF & ObjectMap' is not assignable to type '{ nodes: ModelInterface; }'.
  Types of property 'nodes' are incompatible.
    Type '{ [name: string]: Object3D<Event>; }' is not assignable to type 'ModelInterface'.
      'string' index signatures are incompatible.
        Type 'Object3D<Event>' is missing the following properties from type 'Mesh<BufferGeometry, Material | Material[]>': geometry, material, isMesh, updateMorphTargetsts(2322)

One detail is, the destructuring from nodes, in my case the name Room can come with different names, It could be Bed, or other names...


text:
Q: How to return null in a float method I have a filereader problem where I want to return null if the value is not found. But the method is a Float method.
public float getBalance(int accountNo) throws FileNotFoundException {
        Scanner reader = new Scanner(new FileReader(bankfile));
        String currentline = "";
        try {
        while((currentline = reader.nextLine())!= null) {

            String line[] = currentline.split(",");
            System.out.println(currentline);
            System.out.println(line[0]);
            if(Integer.parseInt(line[0]) == accountNo) {
                this.accountBalance = Float.parseFloat(line[1]);
            }
        }
        }
        catch(NoSuchElementException e) {
             System.out.println("The account number is not found");
            // I want the method to end here if the account number is not found or just return null.
        }

        return this.accountBalance;
    }

This is the file.
File:
2,2.0,Active
1,1.0,Active
3,3.0,Active
4,4.0,Active
5,5.0,Active

I want this code
System.out.println(name.getbalance(6));

to return just the print line "This account number is not found" and not return 0.0
I can't do
if(balance == 0.0){
System.out.println("This account number is not found");
}

since some account might have 0 balance.

A: Root Cause : Your return type is primitive and primitives can not be assigned null values.
Solution : Change the method signature to the equivalent wrapper class.
FYR code:
Modify the following line
public float getBalance(int accountNo) throws FileNotFoundException {

to
public Float getBalance(int accountNo) throws FileNotFoundException {

After this you can add the return null statement in your catch block as follows:
catch(NoSuchElementException e) {
     System.out.println("The account number is not found");
     return null;
}

Note : Kindly add a generic exception also in your catch block to make your code more resilient to the unexpected exceptional cases.
FYR
catch(Exception e) {
   // write some error message or something
}


text:
Q: Can I find my stolen iPhone if someone reset it and uses different AppleID? I recently bought an iPhone iOS 9.2.1. I am worried, if someone stole it, reset it and uses different AppleID, can I find it?

A: Just be sure to switch on Find My iPhone in Settings > iCloud
then not only can it not be reset by anyone without your AppleID & password, but can be

*

*Pinged to play a sound [if you just lost it in the house],

*remotely put into Lost Mode [which will enable you to put a message on the lock screen, with another phone number to be contacted at, if someone finds it],

*or in extreme circumstances, remotely wiped [though this will itself then disable Find my iPhone].
All this can be done from another iPhone or on the iCloud web site at https://www.icloud.com/#find
See this question & answer to see just how impossible it is for a thief to be able to reset it once you've secured it - How can I bypass Activation Lock?


text:
Q: Deleting CAMetalLayer for NSView I have a custom NSView class which is layer backed. I make a CAMetalLayer for this NSView which is created in makeBackingLayer.
In makeBackingLayer I create a layer CAMetalLayer *backingLayer = [CAMetalLayer layer]; and set properties as required by me.
My question is, do I need to dealloc this layer explicitly while destructing NSView?
I do not create this layer in an overridden function, is it my responsibility to delete this or the NSView will take care of it?
I do not see any documentation around this. Moreover, all the samples that I see do not mention about deleting layers anywhere.
Thanks

A: You likely do not need to manually free your layer. Assuming your program has ARC (Automatic Reference Counting) enabled, your NSView should automatically free whichever CALayer is set to its .layer property upon its destruction.
If you're not sure if ARC is enabled, you can go to Build Settings in your Xcode project and search for Automatic Reference Counting. It's been on by default for new Xcode projects for several years now.
Note: Your NSView will only be able to free your layer if it is the only object holding a reference to it. If other objects in your program are holding references to your CAMetalLayer, your layer would not be freed until they remove their references.


text:
Q: Error while using history method in react router I tried using the history method to navigate to the home page after the contact is added but i keep getting this error in the console and the form is not navigating
Search for the keywords to learn more about each error.
ERROR in [eslint]
src\App.js
  Line 43:17:  Unexpected use of 'history'  no-restricted-globals

This is my code

  render(){
    return(
      <div className="appName">
        <Routes>
          <Route  path="/" element={
            <ListContacts
              contacts={this.state.contacts}
              deleteContact={this.removeContact}
            />
          }/>
          <Route path="/create" element={
            <CreateContact
              onCreateContact = {(contact)=>{
                this.createContact(contact)
                history.push("/")
              }}
            />
          }/>
        </Routes>
      </div>
    )
  }
}

export default App;

A: To get access to the history instance, you have to get a hold of it.
The error
You are getting that error because without useHistory, the history reference actually points to the global Window.history object. For that reason, you get "Unexpected use of 'history'  no-restricted-globals".
The fix
If you are using class components, you can get the history instance via this.props.history. For this, make sure you are using the withRouter HOC. After that you could just use:
this.props.history.push("/")

If you are using function components, you could leverage useHistory():
import { useHistory } from "react-router-dom";  // <-- added this import

  const history = useHistory();            //  <----- added this line
  return(
      ...
              onCreateContact = {(contact)=>{
                this.createContact(contact)
                history.push("/")
              }}
      ...


text:
Q: Push notification not works in firebase I have created one new app for push notification in https://console.firebase.google.com. I have followed all steps mentioned at last it shows -unknown app- under the head Targeting user segment.
How to test push notification in firebase?
AndroidManifest.xml
`

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

`

A: First, for using firebase push notifications add the dependencies
dependencies {
    compile 'com.google.firebase:firebase-messaging:11.6.2'                   // this line must be included to use FCM
}

Add a service that extends FirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
 private static final String TAG = "FCM Service";
 @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    }
}

In your Manifest add this
 <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

Add a service that extends FirebaseInstanceIdService
public class FirebaseIDService extends FirebaseInstanceIdService {
    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}

Add it into the AndroidManifest.xml file, this makes sure that the service is loaded
 <service android:name=".FirebaseIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

You are done implementing firebase push notifications !
Test and send your first push notification from firebase console !
hope it helped
For more info check this: https://firebase.google.com/docs/cloud-messaging/android/client?hl
happy coding !


text:
Q: To hear something makes it audible, to see is visible, so what are touch and smell? As the title states, if sound is audible, light is visible, what is a smell? And what is an object when you touch it?

A: Another option to Frank H's answer would be
Touch: tactile
Smell: fragrant / pungent / fetid (depends on experience)

A: Smell is olfactible
Touch is tangible

A: 'Smellable' is a legitimate, though perhaps not a very euphonious adjective. Other alternatives are 'aromatic' and 'odoriferous'.
'Palpable' is the most germane one for touch.

A: Things capable of being seen are visible, things capable of being heard are audible, things capable of being touched are tangible or palpable, things capable of being smelled are odorous, things capable of being tasted are gustable.
Gustable is rarely used and primarily in technical settings.  The concept is most often expressed as "tastable" when we reach for the concept in common usage.  Because of the "-ible" "-able" endings of the other sensate adjectives, "odorous" is an unexpected form but a perfectly correct expression of the concept (though today most of us are more likely to use "malodorous" to describe a bad smell than to use the word "odorous" itself).
Some prefer "palpable" to "tangible" for things capable of being touched because tangible has slipped into being a synonym for the more general and inclusive "sensible", particularly in the use of the word in the practice of law.

A: See - Visible/(Seeable*)
Hear - Audible/(Hearable*)
Smell - Olfactible (used very rare)/Smellable
Taste - Edible (for food)/Potable (for water)/(Tastable*)
Touch - Tangible/Palpable/Tactile/(Touchable*)
*Note: They can be used but word on the first column (except for olfactible) are commonly
used, but smellable is rather used than olfactible

A: Remember that some things are tastable or edible.
I would also think that some poorly-defined proprioceptive feelings, like earthquake phenomena, are sensible (in the generic)


text:
Q: Testing Hibernate DAO, without building the universe around it We have an application built using spring/Hibernate/MySQL, now we want to test the DAO layer, but here are a few shortcomings we face.
Consider the use case of multiple objects connected to one another, eg: Book has Pages.

*

*The Page object cannot exist without the Book as book_id is mandatory FK in Page.

*For testing a Page I have to create a Book.

This simple usecase is easy to manage, but if you start building a Library, till you don't create the whole universe surrounding the Book and Page, you cannot test it!
So to test Page;

*

*Create Library

*Create Section

*Create Genre

*Create Author

*Create Book

*Create Page

*Now test Page.

Is there an easy way to by pass this "universe creation" and just test the page object in isolation. I also want to be able to test HQLs related to Page. eg:
SELECT new com.test.BookPage (book.id, page.name) FROM Book book, Page page.

JUnit is supposed to run in isolation, so I have to write the code to build all the supporting objects in the test case to create the Page. Any tips on how to accelerate the process.
Edit: Spring follows the philosophy of transaction roll-back after the tests have been run, thereyby reverting all changes. Schema changes are expected as we develop further, I want to be able to test it against the production db (backup!) on a regular basis.

A: I just finished a project with this exact configuration.  We had great success using a stand-in HSQLDB database for the unit tests and then turning off referential integrity on the schema for those tests.
Since you're using Spring, these are the steps:

*

*Create a new context configuration file for testing. Set up hibernate to do create-drop for the schema in this configuration.

*Create your junit test. Inherit from AbstractTransactionalJUnit4SpringContextTests, the greatest abstract class in the history of the universe, and annotate the class with your new @ContextConfiguration.  Also use the @TransactionConfiguration annotation to run each test in a transaction with an automatic rollback.

*run the command "SET REFERENTIAL_INTEGRITY FALSE;" through the inherited simpleJdbcTemplate property in your @Before method.

*dedicate the rest of the @Before to simpleJdbcTemplate calls that set up the database.  Note that you no longer need to specify every referenced column, just what you're testing!

*Finally write your unit tests against your DAO's.

Here's a few references that will get you moving in this direction:

*

*http://static.springsource.org/spring/docs/2.5.x/reference/testing.html

*http://www.theserverside.com/news/1365222/Unit-Testing-Hibernate-With-HSQLDB
As usual with this stuff, getting the config just right is the hard part.  But once it's all working, you'll be a styling unit tester!

A: The Unitils extensions to junit or testng have very nice support for this. They allow you to define datasets tuned for your class under test so it only needs the part of the universe your class is seeing and then it initializes the database before the tests start.
checkout : link text
We are using it and it just works fine. A lot better that the "MockRepositories" which we used before which do not test the HQL and, also important, the hibernate transaction behaviors.


text:
Q: Magento2: Different domain for each store view I'm struggling to get my magento2 website set up on different domains for each storeview and was wondering whether anyone could please advise how I can get this working?
I've created my store views for each language and have changed my Base URL within the store configuration for each to be correct domain.
I've also added the following SetEnvIf Host within my .htaccess file however visiting each store domain it redirects me back to my default store view?
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine on

    SetEnvIf Host .*staging.autosmart.fr.* MAGE_RUN_CODE=fr
    SetEnvIf Host .*staging.autosmart.fr.* MAGE_RUN_TYPE=website

    SetEnvIf Host .*staging.autosmart.de.* MAGE_RUN_CODE=de
    SetEnvIf Host .*staging.autosmart.de.* MAGE_RUN_TYPE=website

    SetEnvIf Host .*staging.autosmart.nl.* MAGE_RUN_CODE=nl
    SetEnvIf Host .*staging.autosmart.nl.* MAGE_RUN_TYPE=website

    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
    RewriteRule .* - [L,R=405]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule .* index.php [L]
</IfModule>

How can I get different domains for each store view?

A: You need to set the MAGE_RUN_TYPE to store, not to website here.
See http://devdocs.magento.com/guides/v2.1/config-guide/multi-site/ms_over.html
Also you have an extra whitespace after your Host name .* (beetween . and *). You can even remove this, as Host doesn't contain Uri anyway

A: Update root/pub index.php file after created stores and set domain for stores and websites
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
//$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
//$bootstrap->run($app);
$params = $_SERVER;
$host = $params['HTTP_HOST'];

if($host == "{domain1.com}")
{
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = '{website_code1}';
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website';
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
}

else if($host == "{domain2.com}")
{
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = '{website_code2}'; // Website Code
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website'; // website
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
}
elseif($host == "{domain3.com}") // For specific store view domain
{
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = '{storeview_code1}'; // Store view code
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'store'; // For Store
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
}
else
{
    $params = $_SERVER;
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = 'base';
    $params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = 'website';
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
}
$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);


text:
Q: Mockito doThrow() not throwing exception There's been similar questions, but none of those can solve my current problem
Say I have a fairly simple class:
public class ClassA {
    private final Object someVariable;

    public classA(Object obj) {
        this.someVariable = obj
    }

    public void Object someMethod(Object obj) throws SomeException {
    //does stuff
    }
}

Now, I create an instance of this class in a diff class
public class ClassB {
    private final Object anotherVariable;

    public void Object anotherMethod() throws SomeException {
        try {
            ClassA objectA = new ClassA(anotherVariable)
            objectA.someMethod()
        } catch {
            // does stuff
        }
    }
}

The end goal is to test the catch block by throwing an exceptions as so
@Mock
ClassA myObject = new ClassA(obj)

...

@Test(expected = SomeException.class)
public void myTest()throws Exception {
    doThrow(new SomeException()).when(myObject).someMethod(any());
}

For some reason the exceptions is just never thrown. I've also tried replacing the any() with both valid and invalid objects, and it still doesn't work.
Edit1:
Whilst fishing for a solution, this for some reason passes the test:
@Test(expected = SomeException.class)
public voif Test() throws Exception {
    doThrow(new someException()).when(myObject).someMethod(any());
    when(myObject.someMethod(any())).thenThrow(new someException());
}

Any explanation as to why this works? Is this bad practice or something?

A: I believe the reason is that you never call the method:
@Test(expected = SomeException.class)
public void myTest(0 throws Exception {
    // here you stub the method
    doThrow(new SomeException()).when(myObject).someMethod(any());
    // also it should probably be like this:
    // doThrow(new SomeException()).when(myObject).someMethod();
    // because the method in ClassA does not have any params

    // you need it to be called somewhere
    // you can do that explicitly
    myObject.someMethod(/*perhaps some param here*/);

    // or you can call some other method which calls this one
    // on the mock - then you should get an exception as well
}

Also, there is a little issue in ClassB:
public void Object anotherMethod() throws SomeException {
    try {
        // you instantiate obj of type ClassA here
        // which means you cannot mock it if you need
        // to test anotherMethod()
        ClassA objectA = new ClassA(anotherVariable)
        objectA.someMethod()
    } catch {
            // does stuff
    }
}

If you'd like to test ClassB.anotherMethod() you need to get rid of this super tight coupling:
ClassA objectA = new ClassA(anotherVariable)

Consider approach like this:
public class ClassB {
    private final ClassA objectA;

    public ClassB(ClassA obj) {
        // now you can provide any instance of ClassA instead
        // of having it created in try-block later
        // so when you need ClassB in real code, you can create
        // some real instance of ClassA and pass to this conctructor
        // and for test you can pass mock
        this.objectA = obj;
    }

    public void Object anotherMethod() throws SomeException {
        try {
            objectA.someMethod()
        } catch {
            // does stuff
        }
    }
}

What this gives us:
@Mock
ClassA myObject = new ClassA(obj)

...

@Test(expected = SomeException.class)
public void myTest()throws Exception {
    // stub someMethod on object of ClassA
    doThrow(new SomeException()).when(myObject).someMethod();

    ClassB objB = new ClassB(myObject);

    // now you can test it, and inside anotherMethod()
    // there will be a call to someMethod() on a mock
    // so you will get an exception
    objB.anotherMethod();
}

A: I assume since u are mocking Class A below line
@Mock
ClassA myObject = new ClassA(obj) //u r creating new instance

do
@Mock
ClassA myObject; //assuming u r using initMock or @InjectMocks

or
ClassA myObject = Mockito.mock(ClassA.class);

then Mock the behavior how u mock a method call
when(myObject.someMethod(any()))
      .thenThrow(new SomeException());


text:
Q: How to check if a variable crossed certian value in php I'm using php to build a dynamic site. In my DB I have an field named points in table siteuser, which is the points of the site user.
It is loaded to variable $points in the controller. Every time point increases the value in variable in updated to the field. A flash message will be displayed at point were the point value crosses 100.
I am having trouble in checking if the $points crossed 100 mark. If I write the condition as
if($points>=100) {echo msg;}

The message will appear for all values above 100. The Message should only be displayed once. So, how to write the condition?

A: You have a few options here as this is very simple logic.
Option 1: Keep your if statement as it is and simply add a boolean for if the message has already been displayed.
$msg_flag = false;
if ($points >= 100 && !$msg_flag) {
    $msg_flag = true;
    echo $msg;
}

Option 2: Assume that points are only incremented by a value of 1 and therefore only display the message on a value of 100
if ($points === 100) {
    echo $msg;
}

Option 3: Add a second table for logging a users milestones such as when they reach a certain amount of points. Basically you will query this table to check if a record for the 100 point milestone exists for a specific user. If one does not display the message to the user and then create a milestone record.
This approach would also be good if you intend to have some sort of achievement timeline display area so that a user can see his/her progress over time and when certain milestones were reached.

A: You can check like this
if($points>=100 && $_SESSION['isdisplay']=='notDisplayed')
{
  echo msg;
  $_SESSION['isdisplay']='displayed';
}

So this will show only once when it will reach to 100.

A:  $variable = select <your_column_name> from table_name where <your_dynamic_value> > 100;echo $variable;


text: Q: Got this error "Diff: /../Podfile.lock: No such file or directory" after adding library using cocoapods I keep getting this issue after installing new library using Cocoapods. I'm using Swift 2.2 and Xcode 7.3.1. CocoaPods version is 0.39.0. If you faced with this issue before, could you share how you solved it, please?


text:
Q: Pandas Boolean indexing with two dataframes I have two pandas dataframes:
df1
'A' 'B'
 0   0
 0   2
 1   1
 1   1
 1   3

df2
'ID' 'value'
 0   62
 1   70
 2   76
 3   4674
 4   3746

I want to assign df.value as a new column D to df1, but just when df.A == 0.
df1.B and df2.ID are supposed to be the identifiers.
Example output:
df1
'A' 'B' 'D'
 0   0   62
 0   2   76
 1   1   NaN
 1   1   NaN
 1   3   NaN

I tried the following:
df1['D'][ df1.A == 0 ] = df2['value'][df2.ID == df1.B]

However, since df2 and df1 don't have the same length, I get the a ValueError.
ValueError: Series lengths must match to compare

This is quite certainly due to the boolean indexing in the last part: [df2.ID == df1.B]
Does anyone know how to solve the problem without needing to iterate over the dataframe(s)?
Thanks a bunch!
==============
Edit in reply to @EdChum: It worked perfectly with the example data, but I have issues with my real data. df1 is a huge dataset. df2 looks like this:
df2
    ID  value
0   1   1.00000
1   2   1.00000
2   3   1.00000
3   4   1.00000
4   5   1.00000
5   6   1.00000
6   7   1.00000
7   8   1.00000
8   9   0.98148
9   10  0.23330
10  11  0.56918
11  12  0.53251
12  13  0.58107
13  14  0.92405
14  15  0.00025
15  16  0.14863
16  17  0.53629
17  18  0.67130
18  19  0.53249
19  20  0.75853
20  21  0.58647
21  22  0.00156
22  23  0.00000
23  24  0.00152
24  25  1.00000

After doing the merging, the output is the following: first 133 times 0.98148, then 47 times 0.00025 and then it continues with more sequences of values from df2 until finally a sequence of NaN entries appear...
Out[91]: df1
    A   B   D
0   1   3   0.98148
1   0   9   0.98148
2   0   9   0.98148
3   0   7   0.98148
5   1   21  0.98148
7   1   12  0.98148
...     ...     ...     ...
2592    0   2   NaN
2593    1   17  NaN
2594    1   16  NaN
2596    0   17  NaN
2597    0   6   NaN

Any idea what might have happened here? They are all int64.
==============
Here are two csv with data that reproduces the problem.
df1:
https://owncloud.tu-berlin.de/public.php?service=files&t=2a7d244f55a5772f16aab364e78d3546
df2:
https://owncloud.tu-berlin.de/public.php?service=files&t=6fa8e0c2de465cb4f8a3f8890c325eac
To reproduce:
import pandas as pd

df1 = pd.read_csv("../../df1.csv")
df2 = pd.read_csv("../../df2.csv")

df1['D'] = df1[df1.A == 0].merge(df2,left_on='B', right_on='ID', how='left')['value']

A: Slightly tricky this one, there are 2 steps here, first is to select only the rows in df where 'A' is 0, then merge to this the other df where 'B' and 'ID' match but perform a 'left' merge, then select the 'value' column from this and assign to the df:
In [142]:

df['D'] = df[df.A == 0].merge(df1, left_on='B',right_on='ID', how='left')['value']
df
Out[142]:
   A  B   D
0  0  0  62
1  0  2  76
2  1  1 NaN
3  1  1 NaN
4  1  3 NaN

Breaking this down will show what is happening:
In [143]:
# boolean mask on condition
df[df.A == 0]
Out[143]:
   A  B   D
0  0  0  62
1  0  2  76
In [144]:
# merge using 'B' and 'ID' columns
df[df.A == 0].merge(df1, left_on='B',right_on='ID', how='left')
Out[144]:
   A  B   D  ID  value
0  0  0  62   0     62
1  0  2  76   2     76

After all the above you can then assign directly:
df['D'] = df[df.A == 0].merge(df1, left_on='B',right_on='ID', how='left')['value']

This works as it will align with the left hand side idnex so any missing values will automatically be assigned NaN
EDIT
Another method and one that seems to work for your real data is to use map to perform the lookup for you, map accepts a dict or series as a param and will lookup the corresponding value, in this case you need to set the index to 'ID' column, this reduces your df to one with just the 'Value' column:
df['D'] = df[df.A==0]['B'].map(df1.set_index('ID')['value'])

So the above performs boolean indexing as before and then calls map on the 'B' column and looksup the corresponding 'Value' in the other df after we set the index on 'ID'.
Update
I looked at your data and my first method and I can see why this fails, the alignment to the left hand side df fails so you get 1192 values in a continuous row and then the rest of the rows are NaN up to row 2500.
What does work is if you apply the same mask to the left hand side like so:
df1.loc[df1.A==0, 'D'] = df1[df1.A == 0].merge(df2,left_on='B', right_on='ID', how='left')['value']

So this masks the rows on the left hand side correctly and assigns the result of the merge


text:
Q: Delete appended Div on-click (JQuery) I'm having a bit of a problem deleting appended divs on the click of a button.
When I use hide(), I get the correct behaviour aesthetically but it doesn't actually delete the new div's, which I want as this data will be getting sent to a webservice.
JQuery:
$('a.addListOVM').click(function(e){
    e.preventDefault();
    $('.addCardOVM').append('
' + $('.my_select').find(':selected').val() + '' + '-
');

    $('.removed').click(function(e){
        e.preventDefault();
        $(this).closest('.divform').hide();
    });
});

Template HTML:

 <select class="my_select" name="vlans_{$NetworkDTO->id}[]">
  {foreach from=$arrNetworkDTO item=NetworkDTO name=arr}
    <option class="addOvmCardList" value="{$NetworkDTO->name|escape}">{$NetworkDTO->name}</option>
  {/foreach}
 </select>
+

The button itself is dynamically generated (see the 3rd line) and on-click, I want it to delete that specific appended div without closing the whole window, which it seems to be doing when I use .remove() instead of hide().
So, can anyone tell me:

*

*Why using remove() instead of hide() closes my whole template window instead of deleting that individual div, like hide() LOOKS like it's doing.

*Why, when I have created multiple instances of the appended div, does the .removed click handler get called multiple times (if you create two instances, delete one it loops through once, delete the second it loops through twice etc.)

*How can I get the physical functionality of hide() while actually deleting the appended div?
Thanks

A:
1. Why using remove() instead of hide() closes my whole template window instead of deleting that individual div, like hide() LOOKS like it's doing.

I don't know what you mean by template window, so I cannot really help here.

2. Why, when I have created multiple instances of the appended div, does the .removed click handler get called multiple times (if you create two instances, delete one it loops through once, delete the second it loops through twice etc.)

Because whenever the click event handler is executed and you create a new div, you bind a new event handler to all .removed elements, the just created one and all other existing ones.

3. How can I get the physical functionality of hide() while actually deleting the appended div?

Maybe it is related to the problem above. Use event delegation for the event handler that removes the div:
$('a.addListOVM').click(function(e){
    e.preventDefault();
    $('.addCardOVM').append('
' + $('.my_select').find(':selected').val() + '' + '-
');
});

$('.addCardOVM').on('click', '.removed', function(e){
    e.preventDefault();
    $(this).closest('.divform').remove();
});

A: Use jQuery Live functions to select dynamically added HTML.
 $('.removed').live('click',function(e){
    e.preventDefault();
    $(this).closest('.divform').hide();
});


text:
Q: How to display images from specific folder in gallery application? I'm trying to make a gallery application which only shows images from screenshot folder in my internal storage.
I found a solution from here  but I'm having difficulties on how to specify the path to my desired folder.
This is the snippet:
cursor imagecursor = getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        columns,
                        MediaStore.Images.Media.DATA + " like ? ",
                        new String[] {"%/yourfoldername/%"},
                        null);

Can someone explain me what should I put in this " like ? " and how can I specify my folder name in this new String[] {"%/yourfoldername/%"},
This is my code.
String[] projection = { MediaStore.MediaColumns.DATA,
                    MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.MediaColumns.DATE_MODIFIED };

Cursor cursor = getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    projection,
                    MediaStore.Images.Media.DATA + " like ? ",
                    new String[] {"%/sdcard/DCIM/Screenshots"},
                    null);

Any corrections will be highly appreciated. Cheers!

A: try with this
public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        assert cursor != null;
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}


text:
Q: What is this ? in the beginning of the console output after reading a text file encoded with Unicode? I've been tinkering with reading files(text files encoded in Unicode) and for some reason I get a question mark in the beginning of the output.
Here's the code.
#include <iostream>

#include <Windows.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
    HANDLE hFile = CreateFile(L"dog.txt",
                              GENERIC_READ,
                              NULL,
                              NULL,
                              OPEN_EXISTING,
                              FILE_ATTRIBUTE_NORMAL,
                              NULL);

    _setmode(_fileno(stdout), _O_U16TEXT); //Making sure the console will
                                           //display the  wide characters
                                           //correctly. See below for link

    LARGE_INTEGER li;
    GetFileSizeEx(hFile,&li);

    WCHAR* pBuf = new WCHAR[li.QuadPart / sizeof(WCHAR)]; //Allocating space for
                                                          //the file.

    DWORD dwRead = 0;
    BOOL bFinishRead = FALSE;
    do
    {
        bFinishRead = ReadFile(hFile,pBuf,li.QuadPart,&dwRead,NULL);
    } while(!bFinishRead);

    pBuf[li.QuadPart / sizeof(WCHAR)] = 0; //Making sure the end of the output
                                           //is null-terminated.

    std::wcout << pBuf << std::endl;

    std::cin.get();

    return 1;
}

dog.txt
One Two Three

Console output
?One Two Three

I already eliminated a lot of gibberish by making sure the end of the output is null-terminated but the ? in the beginning puzzles me.
As for the
_setmode(_fileno(stdout), _O_U16TEXT);

see Output unicode strings in Windows console app
Note: My code is Windows-oriented and I intend to keep it that way if possible.
Thanks.

A: It's probably a byte order mark (BOM).  It's standard practice to insert a BOM at the beginning of a text file in UTF-16 to ensure it can be read correctly on different-endian systems (where the individual bytes encoding a UTF-16 double-byte value are in a different order).  You can strip it by checking whether the first wchar_t is codepoint U+FEFF i.e. has value 0xfeff.


text:
Q: Finding a set of congruences from a set of solutions Let $S_1, \ldots, S_m \in \mathbb{Z}_2^n$ be elements forming a subgroup of $\mathbb{Z}_2^n$. How can I find a set of congruences (mod 2) over $x_1, \ldots, x_n$ satisfying exactly $x_1 = S_j[1], \ldots, x_n = S_j[n]$ for all $j \in [m]$.
For exemple, given $S_1 = 000$ and $S_2 = 111$, this is an associated set of congruences: $$x_1 \equiv x_2 \, (\text{mod 2}) \text{ and } x_3 \equiv x_2 \, (\text{mod 2}).$$
I've also post the question of MathOverflow.

A: If I understand the question correctly, you're looking for the orthogonal complement of the subspace spanned by the vectors $S_1,\dotsc,S_m$ (considered as vectors in $\mathbb Z_2^n$ over $\mathbb Z_2$). Each congruence
$$\sum_{i=1}^nc_ix_i\equiv0\pmod2$$
is a constraint that all vectors $S_1,\dotsc,S_m$ are orthogonal to the vector $c$ with components $c_i$. So find a basis for the $S_1,\dotsc,S_m$, then find a basis for the orthogonal complement, and the set of all congruences satisfied by the $x_i$ corresponds to the subspace spanned by that basis. The $S_1,\dotsc,S_m$ forming a group (i.e. a subspace) isn't required for this; you just need to find a basis for the subspace they span.

A: Here's a method which is most likely very impractical when $n$ is large. First, write a matrix $A$ whose rows are your subgroup elements. In the example, $$A=\pmatrix{0&0&0\cr1&1&1\cr}$$ Then write a matrix whose columns are all possible $n$-tuples of zeros and ones. For $n=3$, this is $$B=\pmatrix{0&0&0&0&1&1&1&1\cr0&0&1&1&0&0&1&1\cr0&1&0&1&0&1&0&1\cr}$$ The order of the columns of $B$ is immaterial. Each column of $B$ corresponds to a congruence, e.g., the column $(0,1,1)$ corresponds to $x_2+x_3\equiv0\pmod2$. Now form the product: $$AB=\pmatrix{0&0&0&0&0&0&0&0\cr0&1&1&0&1&0&0&1\cr}$$ Look at the all-zero columns of the product (namely, columns 1, 4, 6, and 7). The corresponding columns in $B$ give the congruences you want. The first column is the trivial congruence $0\equiv0\pmod2$, but the other columns give you $x_2+x_3\equiv0\pmod2$, $x_1+x_3\equiv0\pmod2$, and $x_2+x_3\equiv0\pmod2$.


text:
Q: How do I find out if my MacBook Pro supports virtual extensions? I am curious to know if it's possible to use my MacBook Pro as virtual host to test application in different OS environments. I guess it would improve performance of applications running on virtual OS .

A: Yes, All recent Macs support virtualization.
Apple released native hypervisor functionality with their OS X Yosemite release, their Hypervisor.framework.
What this does is it allows you to run a VM natively on OS X, without the need for client hypervisor (such as VMware Fusion or VirtualBox).
Source

A: There are a handful of Intel processor extensions that indicate easy virtualization (VMX / APIC) - but anyone could write a virtualization engine on code alone with enough smarts, budget, engineering so just because a specific extension is lacking, you can't virtualize.
That being said - you'll be hard pressed to find a Mac running OS X (now macOS) that doesn't have VMX or better:

*

*https://en.wikipedia.org/wiki/X86_virtualization
sysctl machdep.cpu.features


text:
Q: creating a pdf from a template in itextsharp and outputting as content disposition. I would like to open an existing pdf, add some text and then output as content disposition using itext sharp. I have the following code. Where it falls down it is that i want to output as memory stream but need to filestream to open the original file.
Here's what i have. Obviously defining PdfWriter twice won't work.
   public static void Create(string path)
    {
        var Response = HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/pdf";
        System.IO.MemoryStream m = new System.IO.MemoryStream();
        Document document = new Document();
        PdfWriter wri = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
        PdfWriter.GetInstance(document, m);
        document.Open();
        document.Add(new Paragraph(DateTime.Now.ToString()));
        document.NewPage();
        document.Add(new Paragraph("Hello World"));
        document.Close();
        Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.OutputStream.Close();
        Response.End();
    }

A: The second part of your question title says:

"outputting as content disposition"

If that's what you really want you can do this:
Response.AddHeader("Content-Disposition", "attachment; filename=DESIRED-FILENAME.pdf");

Using a MemoryStream is unnecessary, since Response.OutputStream is available. Your example code is calling NewPage() and not trying to add the text to an existing page of your PDF, so here's one way to do what you asked:
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=itextTest.pdf");
PdfReader reader = new PdfReader(readerPath);
// store the extra text on the last (new) page
ColumnText ct = new ColumnText(null);
ct.AddElement(new Paragraph("Text on a new page"));
int numberOfPages = reader.NumberOfPages;
int newPage = numberOfPages + 1;
// get all pages from PDF "template" so we can copy them below
reader.SelectPages(string.Format("1-{0}", numberOfPages));
float marginOffset = 36f;
/*
* we use the selected pages above with a PdfStamper to copy the original.
* and no we don't need a MemoryStream...
*/
using (PdfStamper stamper = new PdfStamper(reader, Response.OutputStream)) {
// use the same page size as the __last__ template page
  Rectangle rectangle = reader.GetPageSize(numberOfPages);
// add a new __blank__ page
  stamper.InsertPage(newPage, rectangle);
// allows us to write content to the (new/added) page
  ct.Canvas = stamper.GetOverContent(newPage);
// add text at an __absolute__ position
  ct.SetSimpleColumn(
    marginOffset, marginOffset,
    rectangle.Right - marginOffset, rectangle.Top - marginOffset
  );
  ct.Go();
}

I think you've already figured out that the Document / PdfWriter combination doesn't work in this situation :) That's the standard method for creating a new PDF document.

A: You've got a couple of problems that I'll try to walk you through.
First, the Document object is only for working with new PDFs, not modifying existing ones. Basically the Document object is a bunch of wrapper classes that abstract away the underlying parts of the PDF spec and allow you to work with higher level things like paragraphs and reflowable content. These abstractions turn what you think of "paragraphs" into raw commands that write the paragraph one line at a time with no relationship between lines. When working with an existing document there's no safe way to say how to reflow text so these abstractions aren't used.
Instead you want to use the PdfStamper object. When working with this object you have two choices for how to work with potentially overlapping content, either your new text gets written on top of existing content or your text gets written below it. The two methods GetOverContent() or GetUnderContent() of an instantiated PdfStamper object will return a PdfContentByte object that you can then write text with.
There's two main ways to write text, either manually or through a ColumnText object. If you've done HTML you can think of the ColumnText object as using a big fixed-position single row, single column <TABLE>. The advantage of the ColumnText is that you can use the higher level abstractions such as Paragraph.
Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that show off the above. See the code comments for any questions. It should be pretty easy to convert this to ASP.Net.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            string existingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf");
            string newFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf");
            using (FileStream fs = new FileStream(existingFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                using (Document doc = new Document(PageSize.LETTER)) {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
                        doc.Open();

                        doc.Add(new Paragraph("This is a test"));

                        doc.Close();
                    }
                }
            }

            //Bind a PdfReader to our first document
            PdfReader reader = new PdfReader(existingFile);
            //Create a new stream for our output file (this could be a MemoryStream, too)
            using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                //Use a PdfStamper to bind our source file with our output file
                using (PdfStamper stamper = new PdfStamper(reader, fs)) {

                    //In case of conflict we want our new text to be written "on top" of any existing content
                    //Get the "Over" state for page 1
                    PdfContentByte cb = stamper.GetOverContent(1);

                    //Begin text command
                    cb.BeginText();
                    //Set the font information
                    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 16f);
                    //Position the cursor for drawing
                    cb.MoveText(50, 50);
                    //Write some text
                    cb.ShowText("This was added manually");
                    //End text command
                    cb.EndText();

                    //Create a new ColumnText object to write to
                    ColumnText ct = new ColumnText(cb);
                    //Create a single column who's lower left corner is at 100x100 and upper right is at 500x200
                    ct.SetSimpleColumn(100,100,500,200);
                    //Add a higher level object
                    ct.AddElement(new Paragraph("This was added using ColumnText"));
                    //Flush the text buffer
                    ct.Go();

                }
            }

            this.Close();
        }
    }
}

As to your second problem about the FileStream vs MemoryStream, if you look at the method signature for almost every (actually all as far as I know) method within iTextSharp you'll see that they all take a Stream object and not just a FileStream object. Any time you see this, even outside of iTextSharp, this means that you can pass in any subclass of Stream which includes the MemoryStream object, everything else stays the same.
The code below is a slightly modified version of the one above. I've removed most of the comments to make it shorter. The main change is that we're using a MemoryStream instead of a FileStream. Also, when we're done with the PDF when need to close the PdfStamper object before accessing the raw binary data. (The using statment will do this for us automatically later but it also closes the stream so we need to manually do it here.)
One other thing, never, ever use the GetBuffer() method of the MemoryStream. It sounds like what you want (and I have mistakenly used it, too) but instead you want to use ToArray(). GetBuffer() includes uninitialized bytes which usually produces corrupt PDFs. Also, instead of writing to the HTTP Response stream I'm saving the bytes to array first. From a debugging perspective this allows me to finish all of my iTextSharp and System.IO code and make sure that it is correct, then do whatever I want with the raw byte array. In my case I don't have a web server handy so I'm writing them to disk but you could just as easily call Response.BinaryWrite(bytes)
string existingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf");
string newFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf");
PdfReader reader = new PdfReader(existingFile);
byte[] bytes;
using(MemoryStream ms = new MemoryStream()){
    using (PdfStamper stamper = new PdfStamper(reader, ms)) {
        PdfContentByte cb = stamper.GetOverContent(1);
        ColumnText ct = new ColumnText(cb);
        ct.SetSimpleColumn(100,100,500,200);
        ct.AddElement(new Paragraph("This was added using ColumnText"));
        ct.Go();

        //Flush the PdfStamper's buffer
        stamper.Close();
        //Get the raw bytes of the PDF
        bytes = ms.ToArray();
    }
}

//Do whatever you want with the bytes
//Below I'm writing them to disk but you could also write them to the output buffer, too
using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    fs.Write(bytes, 0, bytes.Length);
}


text:
Q: Git retrieving lost branches So I decided I wanted to change a branch name,
and instead of creating a new branch I thought I will use this method, to rewrite the whole branch, but what it actually did was delete all my remote branches.
Any idea how I might get them back.
(Please note that I had more branches, but hopefully this will do)

→ git push -f --mirror
  Counting objects: 3, done.
  Delta compression using up to 4 threads.
  Compressing objects: 100% (3/3), done.
  Writing objects: 100% (3/3), 323 bytes | 0 bytes/s, done.
  Total 3 (delta 2), reused 0 (delta 0)
  remote: This repository moved. Please use the new location:
  remote:   ----
  To ----
   - [deleted]         some_branch
   - [deleted]         another_branch
   * [new branch]      support_page_changes -> support_page_changes
   * [new branch]      origin/master -> origin/master
   * [new branch]      origin/another_branch -> origin/another_branch
   * [new branch]      origin/some_branch -> origin/some_branch

Thanks.

A: You can use git reflog to get the SHA1 of the last commits you used. Once you find the right commit, just check it out, and create a branch there. For instance, if you find that your branch was previously on commit with SHA-1 xyz, then you just need to do
git checkout xyz
git branch my_brach

If you can't find the SHA-1 with git reflog, you may try to list all the commit not accessible by references:
git fsck --full --no-reflogs # don't worry if it takes time to run

#Now, let's see what are the commits show by the previous command
git show abc
git show def
...


text:
Q: Compiler cannot find an enum type. (Battleship game) I'm trying to write a Battleship game.
First i made a class called Tile to represent one block of a 2D array that will become the battleground board:
public class Tile {
    public enum type{SEA, SHIP, HIT, MISS};
    int x,y;
    public type tile_type;
    public Tile(int x,int y, type type){
        this.x = x;
        this.y = y;
        this.tile_type = type;
     }
}

Next i created a class called Board and in the constructor I want to make every tile to have the tile type SEA:
public class Board{
    static int Dimension = 7;
    Tile[][] Matrix = null;
    public Board(Tile[][] Matrix){
        Matrix = new Tile[Dimension][Dimension];
        for(int i=0; i<=Dimension;i++){
            for(int u=0;u<=Dimension;u++){
                Matrix[i][u].tile_type = type.SEA;
            }
        }
    }
}

Here is where the Java compiler says that it cannot find the variable type in type.SEA.
I don't understand where the problem is.

A: Seems you did not import type in Board, you can add the outer class explictly:
Matrix[i][u].tile_type = Tile.type.SEA;


text:
Q: How should I solve this c++ sorting problem #include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string.h>
#include<map>
#include<functional>
using namespace std;
map<string, int> m;
vector<pair<pair<string, int>, int>> v;
vector<pair<pair<string, int>,int>> v3;
vector<pair<pair<string, int>, int>> v2[1001];
int N;
int idx;
bool cmp(const pair<pair<string, int>,int>& n1, pair<pair<string, int>, int>& n2)
{
    return n1.first.first < n2.first.first;
}
bool cmp2(const pair<pair<string, int>, int>& n1, pair<pair<string, int>, int>& n2)
{
    if(n1.first.first==n2.first.first)
        return n1.first.second > n2.first.second;
}
bool cmp3(const pair<pair<string, int>, int>& n1, pair<pair<string, int>, int>& n2)
{
    if(n1.first.first==n2.first.first)
        if (n1.first.second == n2.first.second)
            return n1.second > n2.second;
}

int main(void)
{
    int N;
    string s;
    int num;
    cin >> N;
    for (int i = 0; i < N; i++)
    {
        cin >> s >> num;
        m[s]+= num;
        v.push_back(make_pair(make_pair(s, num), i));
    }
    sort(v.begin(), v.end(), cmp);
    sort(v.begin(), v.end(), cmp2);
    sort(v.begin(), v.end(), cmp3);
    //for (auto it = v.begin(); it != v.end(); it++)
    //{
    //  cout << "first: " << it->first.first << " second: " << it->first.second << " " << it->second << endl;
    //}
    for (int i = 0; i < v.size(); i++)
    {
        v3.push_back(v[i]);
    }
    for (auto it = v3.begin(); it != v3.end(); it++)
    {
        cout << "first: " << it->first.first << " second: " << it->first.second << " third: " << it->second << endl;
    }
}

I have a sorting problem and don't know y cmp3 is kept getting error...
trying to sort the third element descending(while the second element is the same)
how should I fix it?
the input data is
8
classic 1000
classic 500
pop 300
classic 1000
classic 600
pop 100
classic 1000
classic 1000

A: The comparison functions cmp2 and cmp3 have undefined behavior - they don't return a value for every input. So, they won't really sort the vector.
I suspect you might be trying to use all three comparison functions together, but they are actually completely re-sorting it 3 different times. You need to put the entire behavior in one sorting function:
bool cmp3(const pair<pair<string, int>, int>& n1, pair<pair<string, int>, int>& n2)
{
    if (n1.first.first != n2.first.first) {
        return n1.first.first < n2.first.first;
    }
    if (n1.first.second != n2.first.second) {
        return n1.first.second < n2.first.second;
    }
    return n2.second < n1.second; // descending
}


text:
Q: Difference between 2 Quotient Rings Consider the rings, $Z_2[x]/(1 + x^2)$ and $ Z_2[x]/(1 + x + x^2)$, despite having different polynomial as divisor, I have been told that -
$$Z_2[x]/(1 + x^2) = \{0, 1, x, 1 + x\}$$
and
$$Z_2[x]/(1 + x + x^2)= \{0, 1, x, 1 + x\}$$
Then what is the difference between $Z_2[x]/(1 + x^2)$ and $ Z_2[x]/(1 + x + x^2)$?

A: Well, both quotient rings are vector spaces over $Z_2$ of dimension 2, both with bases $\{1,x\}$.
In general, if $K$ is a finite field and $f(x)$ is a polynomial over $K$ of degree $n$, then $K[x]/\langle f(x)\rangle$ is a vector space over $K$ of dimension $n$.
The difference above is that $x^2+x+1$ is irreducible over $Z_2$, while $x^2+1=(x+1)^2$ is not. So $Z_2[x]/\langle x^2+x+1\rangle$ is a field, while $Z_2[x]/\langle x^2+1\rangle$ is not (it has zero divisors).

A: This is a notation issue. When you write $\mathbb{Z}_2[x]/(1 + x^2) = \{0, 1, x, 1 + x\}$, that's just an equality of equivalence classes. In addition, on the RHS of the equality, you're missing some relations that hold in $\mathbb{Z}_2[x]/(1 + x^2)$ as the notation $\{0, 1, x, 1 + x\}$ alone doesn't tell anything about relations.
The same with $\mathbb{Z}_2[x]/(1 + x^2) = \{0, 1, x, 1 + x\}$. Moreover the equivalence classes in the latter are not the same as the one in the former, because you're modding out be different ideals, so even as sets  $\{0, 1, x, 1 + x\}$ and $\{0, 1, x, 1 + x\}$ are are basically different. Hence one should use different notation to avoid confusion.


text:
Q: keepalived relocation not happening I have a problem with Keepalived.
If my application process goes down due to some reason, keepalived fail over the VIP to backup node. However, if the process fails again on backup node its not relocating to Master node. from /var/log/messages its clear that its registing the fail.
Below are my config files:
On Node1 ( Master)
vrrp_script chk { script "/root/test.sh" interval 2 # check every 2 seconds fall 1 rise 2 weight -60 }

vrrp_instance VRRP1 { state EQUAL priority 110 interface eth0 virtual_router_id 51 advert_int 1 authentication { auth_type PASS auth_pass 1111 }

notify_backup "/etc/keepalived/rtb.sh BACKUP"
notify_fault "/etc/keepalived/rtb.sh FAULT"

virtual_ipaddress {
    10.58.127.80/24
}

notify_master "/etc/keepalived/rtb.sh MASTER"

track_script {
chk
}
}

On Node2 (Backup)
vrrp_script chk { script "/root/test.sh" interval 2 # check every 2 seconds fall 1 rise 2 weight -50 }

vrrp_instance VRRP1 { state EQUAL priority 101 interface eth0 virtual_router_id 51 advert_int 1 authentication { auth_type PASS auth_pass 1111 }

notify_backup "/etc/keepalived/rtb.sh BACKUP"
notify_fault "/etc/keepalived/rtb.sh FAULT"

virtual_ipaddress {
    10.58.127.80/24
}

notify_master "/etc/keepalived/rtb.sh MASTER"

track_script {
chk
}
}

If I kill my application process on Node1, VIP is getting relocated to Node2. After a while, if I kill my application process again on Node2, it registers that there is failure but NOT relocating the IP.
Dec 11 11:29:50 rtb48 Keepalived_vrrp[25813]: VRRP_Script(chk) failed

No action post that.
Keepalived version : keepalived-1.2.13-5.el6_6.x86_64
Any clue?

A: Did you restart the process on Node #1 to make the check script pass?
Node #1 has a priority of 110 with a weight of 60 on the script.
Node #2 has a priority 0f 101 with a weight of 50 on the script.
So failure on #1 is 110 - 60 = 50. Failure on #2 is 101 - 50 = 51.
Node #2 in this case still has the higher priority and will be master.
Aside: you config looks odd, is it really in long lines like that? If so, shouldn't the comment in the middle of the line break it?


text:
Q: android:state_selected="true" doesn't work about ListView item I have a ListView which I want its item's background turn into green when the item is pressed and keep in grey when I release my finger.
I use a selector(listview_item_indicator.xml) to achieve this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/grey" android:state_selected="true" ></item>
    <item android:drawable="@color/green" android:state_pressed="true"></item>
</selector>

Then I update the xml file of the ListView item to apply this selecor like this:
android:background="@drawable/listview_item_indicator"

The result is it turn into green when I press the item,but it doesn't keep in grey when I release my finger(it turn to what it was before I pressed it).I think it means <item android:drawable="@color/green" android:state_pressed="true"></item> worked,but <item android:drawable="@color/grey" android:state_selected="true" ></item> didn't work.Why?

A: state_selected is for selection via trackball or d-pad
I think you are referring to the API 11 state_activated
See: http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
EDIT:
You also need to:
1) Set list view to single choice:
<ListView
        android:choiceMode="singleChoice" />

2) Highlight item using listView.setItemChecked(index, true);

A: You should probably use android:listSelector instead of android:background

A: Define default state.
Try this selector :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/grey" android:state_selected="true" ></item>
    <item android:drawable="@color/green" android:state_pressed="true"></item>
    <item android:drawable="@color/white" ></item>
</selector>


text:
Q: How to let MySQL NOW() function return the user time I ran into a very tricky MySQL issue..
Our DB is using type DateTime for the updated_at column, and now is too late to change it back to TimeStamp. I'm thus trying to add a trigger to update this updated_at column on table changing. The following is what I did:
CREATE TRIGGER foo_schema.bar_datetime_trigger BEFORE UPDATE ON foo_schema.bar
FOR EACH ROW
set NEW.updated_at = NOW();
The NOW() function here returns the DB time; however, what I actually want is to set the udpated_at as the user time (Meaning the time of the user who made changes to table bar). Is it possible to handle this in MySQL?


text:
Q: Event listener not working in external file When my JavaScript code is on the same HTML page, event listener is working:

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
    background-color: #3e8e41;
}

/* The container
 - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

  <button id="dropBtn" class="dropbtn">Dropdown</button>

       Link 1
       Link 2
       Link 3

But when I put same javascript code into external JS file, the event listener is not working.
I included JS file just before closing  tag:

How to make my event listener works from an external file, not just inside HTML page ?

A: You're missing the window.onload() function.
It should be:
window.onload = function () {

var dropdown = document.getElementById("dropBtn");

    function myFunction() {
         document.getElementById("myDropdown").classList.toggle("show");
    }

    dropdown.addEventListener("click", myFunction, false);

    // Close the dropdown menu if the user clicks outside of it
    window.onclick = function(event) {
      if (!event.target.matches('.dropbtn')) {

        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
          }
        }
      }
    }
}

Also, if this is an external JS, you should not include the