Q:

Core Data - get/create NSManagedObject performance

I'm creating an iphone/ipad app that basically reads XML documents and creates tableviews from objects created based on the xml. The xml represents a 'level' in a filesystem. Its basically a browser.
Each time i parse the xml documents i update the filesystem which is mirrored in a core-data sqllite database. For each "File" encountered in the xml i attempt to get the NSManagedObject associated with it.
The problem is this function which i use to get/create either a new blank entity or get the existing one from database.
+(File*)getOrCreateFile:(NSString*)remotePath
        context:(NSManagedObjectContext*)context
 {
        struct timeval start,end,res;
        gettimeofday(&start,NULL);
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];
        [fetchRequest setFetchLimit:1];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"remotePath == %@",remotePath];
        [fetchRequest setPredicate:predicate];

        NSError *error;
        NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
        [fetchRequest release];

        File *f;
        if ([items count] == 0)
            f = (File*)[NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:context];
        else
            f = (File*)[items objectAtIndex:0];

        gettimeofday(&end, NULL);
        [JFS timeval_subtract:&res x:&end y:&start];
        count++;
        elapsed += res.tv_usec;
        return f;

}
For eksample, if i'm parsing a document with 200ish files the total time on a iPhone 3G is about 4 seconds. 3 of those seconds are spent in this function getting the objets from core data.
RemotePath is a unique string of variable length and indexed in the sqllite database.
What am i doing wrong here? or.. what could i do better/different to improve performance.

A:

Executing fetches is somewhat expensive in Core Data, though the Core Data engineers have done some amazing work to keep this hit minimal. Thus, you may be able to improve things slightly by running a fetch to return multiple items at once. For example, batch the remotePaths and fetch with a predicate such as
[NSPredicate predicateWithFormat:@"remotePath IN %@", paths];

where paths is a collection of possible paths.
From the results, you can do the searches in-memory to determine if a particular path is present.
Fundamentally, however, doing fetches against strings (even if indexed) is an expensive operation. There may not be much you can do. Consider fetching against non-string attributes, perhaps by hasing the path and saving the hash in the entity as well. You'll get back a (potentially) larger result set which you could then search in memory for string equality.
Finally, do not make any changes without some performance data. Profile, profile, profile.


Q:

Texture Memory Usage

I am trying to find out how much texture memory does consumed from my application. There are following types of texture and calculations by me:

RGB textures -> textureWidth * textureHeight * 3 (memory usage)
RGBA textures -> textureWidth * textureHeight * 4 (memory usage)

As a result I am wondering that can graphics driver allocate much more memory than above calculated memory?

A:

A few simple answers:
To the best of my knowledge, it's been around 2 decades since (the majority of) hardware devices supported packed 24bit RGB data. In modern hardware this is usually represented in an "XRGB" (or equivalent) format where there is one padding byte per pixel. It is painful in hardware to efficiently handle pixels that straddle cache lines etc.   Further, since many applications (read "games") use texture compression, having support for fully packed 24bit seems a bit redundant.
Texture dimensions: If a texture's dimensions are not 'nice' for the particular hardware (e.g,. maybe, say, x is not a multiple of 16bytes, or, say, 4x4 or 8x8 blocks), then the driver may pad the physical size of the texture.
Finally, if you have MIP mapping (and you do want this for performance as well as quality reasons), it will expand the texture size by around 33%.

A:

In addition to the answer from Simon F, it's also worth noting that badly written applications can force the driver to allocate memory for multiple copies of the same texture. This can occur if it attempts to modify the texture while it is still referenced by an in-flight rendering operation. This is commonly known as "resource copy-on-write" or "resource ghosting".
Blog here explains in more detail:
https://community.arm.com/developer/tools-software/graphics/b/blog/posts/mali-performance-6-efficiently-updating-dynamic-resources


Q:

App Engine editing an instance in a repeated KeyProperty via the instance itself

Lets say I have the following models:
class Author(ndb.Model)
    books = ndb.KeyProperty(kind='Book', repeated=True)

class Book(ndb.Model)
    title = ndb.StringProperty()

So at a certain point you'll have an author with a list of n books.
Questions:
When I'm editing a book how do I change the author without a reference to the 'current' author? Do I need to add a reverse relation with a KeyProperty on Book?
When changing the author I have to remove the book from the old author's list and add it to the new one. That feels kind of cumbersome. Is there a better way?
Bonus question: What if a book gets deleted? There will be a None value in the author's books list. Do I have to remove that?
Note: I'm using a repeated KeyProperty because this makes ordering the books easy, which in my case is important.

A:

When I'm editing a book how do I change the author without a reference to the 'current' author?

you can use ndb.Model.allocate_ids to reserve a key before the entity is saved

Do I need to add a reverse relation with a KeyProperty on Book?

Given your model, the addition of a reverse lookup key can make your life easier

What if a book gets deleted? There will be a None value in the author's books list. Do I have to remove that?

The key in Auther.books will not automatically becomes null in this case. You have to remove it yourself.

I'm using a repeated KeyProperty because this makes ordering the books easy, which in my case is important.

A potential problem is that an entity has a size limit of 1mb. If an author is very prolific writer (e.g. Edwy Searles Brooks has 800+ published works), it can exceed the limit.
I would design the model this way:
class Author(ndb.Model):
    name = ndb.StringProperty()

class Book(ndb.Model):
    authors = ndb.KeyProperty('Author', required=True)  # Usually it is at most a couple of authors
    title = ndb.StringProperty()

To find out all books written by a particular author with id 1234, you can
  Book.query(Book.authors == ndb.Key('Author', 1234)).fetch()

Apparently the ordering of books must be stored explicitly, I would suggest a third entity to keep track of this information:
class BookList(ndb.Model):
  name = ndb.StringProperty()
  book_keys = ndb.KeyProperty(kind='Book', repeated=True)

Then you can retrieve books in this manner
stephen_king_book_list = stephen_king_book_list_key.get()
books = ndb.get_multi(stephen_king_book_list.book_keys)
# Some of key can lead to None if the underlying book is already deleted
# You can define some background job to sweep clean the list from time to time
# But let filter out the bad guys first
books = [b for b in books if b]

If you think your lists are going to be very very long, you can break a list down into segments like a linked list structure
class BookList(ndb.Model):
  prev_segment = ndb.KeyProperty(kind='BookList', required=False)
  next_segment = ndb.KeyProperty(kind='BookList', required=False)
  name = ndb.StringProperty()
  book_keys = ndb.KeyProperty(kind='Book', repeated=True)

You can find the fist segment easily by:
  starting_point = BookList.query(BookList.name == 'Stephen_King',
     BookList.prev_segment == None
  ).fetch()

Of course if insertion is very frequent, you might want to use an alternative structure to hold the book list


Q:

How many tries to guess

I have a lottery program that I would like to ask me to take a guess at the 'winning' numbers and then will generate said numbers. When it's done, it will print those numbers back to me, and tell me how many tries it took to arrive at the correct answer.
My code is below. I thought I'd gotten the answer from another thread, was so sure that I closed it - and can't find it now. My question is really just a 'What's wrong with my code?' type, as I think that the code is working, but since the array is 6 numbers I figure it will take the computer some time.
For that reason, I changed the array to just 1 number and it was still taking forever to come back with a "You guessed it in...!" Leading me to believe there is something else wrong I'm missing.
package lottery;

import java.util.Scanner;

public class lottery { // Begin lottery class
    public static void main(String[] args) { // Begin MAIN method

        // Define variables
        Scanner keyboard = new Scanner(System.in);
        int[] lottery = new int[6];
        int randomNum = 1 + (int) Math.random() * 59;
        int noTimes = 1;
        int guess = 0;
        // End variable definition

        System.out.println("Generating lottery numbers, what is your guess?");
        while (guess != randomNum) {
            guess = keyboard.nextInt();
            guess++;
        }

        // Input received - generate numbers now
        System.out.println("Thank you. Generating lottery numbers now...");

        for (int i = 0; i < 6; i++) {
            randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
            for (int x = 0; x < i; x++) {
                if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
                {
                    randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
                    x = -1; // restart the loop
                }

            }
            lottery[i] = randomNum;
        }

        for (int j = 0; j < noTimes; j++) {
            for (int i = 0; i < lottery.length; i++) {
                System.out.print("The winning numbers are: " + lottery[i] + " ");
            }
            System.out.println("\n");
            System.out.print("You correctly guessed in " + guess + " tries.");
        }
    } // End MAIN method
} // End Lottery class

Apparently, I don't know how to do the regular code tag? colors?

A:

There are various problems in your code, which are explained below.

To generate a random integer between 1 and 59 inclusive (but not 60), please use the following code snippet in your 3 places:
int randomNum = 1 + (int)(Math.random() * 59);

The guess-check logic needs to be fixed (as outlined below):
int noTimes = 0;  // Corrected
...
while (guess != randomNum) {
    guess = keyboard.nextInt();
    noTimes++;  // Corrected
}

The last pair of for-loops (the ones just before the 3 consecutive prints) look weird. Here is a more sensible replacement:
System.out.print("The winning numbers are:");
for (int i = 0; i < lottery.length; i++) {
    System.out.print(" " + lottery[i]);
}
System.out.println();
System.out.println("You correctly guessed in " + noTimes+ " tries.");

Other than these, your code looks okay to me so far.
PS: Choosing 6 ordered items from 59 elements has 32.4 billion possibilities.


Q:

Call public function in Main Window from a User Control WPF

I have a Main Window which includes some User Controls that are initialized in the WPF XAML
MainWindow.xaml.
<Grid>
    <local:RegularUnit x:Name="ucRegularUnit" Grid.Row="0" />
    <local:Actions x:Name="ucActions" Grid.Row="1" />
    // .....
</Grid>

I have a public function in the Main Window which I want to call after clicking a Button in my User Control. After searching for some solutions, I found a way to get the parent window instance in my User Control class, but it can't find the function when I'm using parentWindow.myFunction().
User Control RegularUnit.cs:
public partial class RegularUnit : UserControl
{
    public RegularUnit()
    {
        InitializeComponent();
    }

    private void Button_SearchSerialNumber_Click(object sender, RoutedEventArgs e)
    {
        Window parentWindow = Window.GetWindow(this);
        //parentWindow.    //Can't find the function myFunction()
    }
}

MainWindow.cs:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public void myFunction()
    {
        // Do Some Stuff...
    }
}

What am I doing wrong, and how can I fix it?

A:

You can't call myFunction on parentWindow because it's not a member of the standard WPF Window class but of your custom MainWindow.
What you could do is to cast the result of Window.GetWindow(this) to MainWindow, like
MainWindow parentWindow = (MainWindow)  Window.GetWindow(this);
parentWindow.myFunction();

However this is a really bad class design because now your user control depends on being embedded in a specific window.
What you should rather do is to add an event to the user control on which the parent control can subscribe to.
public event EventHandler SerialNumberSearch;

private void Button_SearchSerialNumber_Click(object sender, RoutedEventArgs e)
{
    var handler = SerialNumberSearch;
    if (handler != null) handler(this, EventArgs.Empty);
}

Of course you could use a different kind of EventHandler, depending on what you need.


Q:

Sharing memory from the linux kernel to user space in single user mode

I have a kernel module that allocates memory and I would like to share this memory with a user process.  In normal mode we can only do that with: mmap, /proc, shmem, etc.  but in single user mode, for embedded devices, isn't there a way to share a simple pointer?

A:

"Single user mode" is a convention defined by userspace. It has no significance to the kernel; all of the same rules apply as "normal mode".
If you want to access memory -- any memory -- from userspace, you will need to map that memory into the process somehow. Using mmap() on a special file or device node is the most natural way of doing this.


Q:

Opencv: Changing a code that uses video to an image for color detection using trackbars

I have a project where i need to detect specific colors from leaves images, like green, brown and yellow.
I found this tutorial (http://opencv-srf.blogspot.com.br/2010/09/object-detection-using-color-seperation.html) that explains how to create a real time trackbar to find the best values for that, but it uses images from a webcam, and i want to use it with pictures.
Can you guys please help me do that?
Thank you.

A:

Here is the code for thresholding an HSV image, selecting the ranges with trackbars.
Note that, differently from a video (as described here), I used morphologyEx to perform morphological operations, and replaced C style cvCreateTrackbar with the C++ function createTrackbar.
The comments in the code should be clear. Please ping me if something is not clear:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    // Load BGR image
    Mat3b bgr = imread("path_to_image");
    if (bgr.empty())
    {
        cout << "Cannot open the image" << endl;
        return -1;
    }

    // Transform to HSV
    Mat3b hsv;
    cvtColor(bgr, hsv, COLOR_BGR2HSV);

    // Create a window called "Control"
    namedWindow("Control", CV_WINDOW_AUTOSIZE);

    // Set starting values for ranges
    int iLowH = 0;
    int iHighH = 179;

    int iLowS = 0;
    int iHighS = 255;

    int iLowV = 0;
    int iHighV = 255;

    //Create trackbars in "Control" window
    createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
    createTrackbar("HighH", "Control", &iHighH, 179);

    createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
    createTrackbar("HighS", "Control", &iHighS, 255);

    createTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
    createTrackbar("HighV", "Control", &iHighV, 255);

    //Show the original image
    imshow("Original", bgr);

    // Create kernel for morphological operation
    Mat kernel = getStructuringElement(MORPH_ELLIPSE, Size(5, 5));

    // Infinte loop, until user press "esc"
    while (true)
    {
        Mat mask;
        inRange(hsv, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), mask); //Threshold the image

        //morphological opening (remove small objects from the foreground)
        morphologyEx(mask, mask, MORPH_OPEN, kernel);

        //morphological closing (fill small holes in the foreground)
        morphologyEx(mask, mask, MORPH_CLOSE, kernel);

        //Show the thresholded image
        imshow("Thresholded Image", mask);

        if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl;
            break;
        }
    }
    return 0;
}


Q:

How to convert FBV to ListView in Django

I want to convert the FBV function to ListView.
But I don't know how to handle the value of slug.
How to get the value of slug in ListView?
view.py
def category(request, slug=None):
    current_ct = None
    categories = Category.objects.all()
    products = Product.objects.filter(ready=True)

    if slug:
        current_ct = get_object_or_404(Category, slug=slug)
        products = products.filter(category=current_ct)

    return render(request, 'home.html', {'current_ct': current_ct, 'categories': categories, 'products': products})

url.py
path('category/<slug>/', category, name="test"),

get_absolute_url() in model.py
def get_absolute_url(self):
    return reverse("test", kwargs={"slug": self.slug})

A:

You can get access to the parameters passed to the call with self.args (for positional parameters) and self.kwargs (for named parameters).
That being said, if you use a DetailView [Django-doc], you do not need to do this yourself at all. Indeed a DetailView and all other class-based views that use the SingleObjectMixin [Django-doc] will look for a slug and pk in these parameters, and do the filtering automatically.
We thus can make it a DetailView as:
class CategoryDetailView(DetailView):
    model = Category
    context_object_name = 'current_ct'
    template_name = 'home.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context.update(
            categories=Category.objects.all(),
            products=self.object.product_set.filter(ready=True)
        )
        return context
Here by overriding the .get_context_data(..) method [Django-doc], we thus inject extra items in the context we pass when rendering the template.


Q:

How to get semi-major axis from TLE?

This should be fairly straightforward, but, how do I get the semi-major axis (a) from at TLE.
For example if I have the TLE:
1 25544U 98067A 01260.91843750 .00059354 00000-0 74277-3 0 4795
2 25544 51.6396 342.1053 0008148 106.9025 231.8021 15.5918272116154

I know that 15.5918272 is the mean motion of the body ($n$). I also know that $n = \sqrt{\frac{\mu}{a^3}}$. If I use the given $n$ value I get a semi-major axis $a=11.79$ which is obviously incorrect. What am I missing here?

A:

The TLE gives mean motion ($n$) in $\frac{rev}{day}$. This needs to be converted to $\frac{rad}{s}$ which can be accomplished by multiplying the $n$ TLE value by $\frac{2\pi}{86400}$.
Therefore, to go directly from $n$ in TLE to the semi-major axis $a$. We can use the following formula: $a=\frac{\mu^{1/3}}{\frac{2n\pi}{86400}^{2/3}}$.
For $n=15.5918272 \,\, \frac{rev}{day}$, we get $a=6768.16 \,\, km$.


Q:

Reactjs ERR_INVALID_ARG_TYPE

there!
I bought some template from themeforest and everything works fine with previews version, but with the new one I'm having error like
> TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type
> string. Received type undefined
>         at validateString (internal/validators.js:125:11)
>         at Object.join (path.js:427:7)
>         at noopServiceWorkerMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at launchEditorMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)
>         at trim_prefix (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:317:13)
>         at C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:284:7
>         at Function.process_params (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:335:12)
>         at next (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\index.js:275:10)
>         at handleWebpackInternalMiddleware (C:\Users\Rade\Desktop\gComet-master\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7)
>         at Layer.handle [as handle_request] (C:\Users\Rade\Desktop\gComet-master\node_modules\express\lib\router\layer.js:95:5)

I believe that template is not supposed to have this error, but still I have it. What could be the problem?

A:

You can check this link https://github.com/ionic-team/ionic/issues/20503
To fix this issue simply upgrade to "react-scripts": "^3.4.0"

Overwrite the existing "react-scripts": "^3.x.x" with"react-scripts": "^3.4.0" in your package.json
Delete your node modules
and npm install or yarn install

i hope it will fix it.


Q:

Cambiar tipo de dato TIME a DATE - SQL SERVER

Buen día, tengo una duda ,ocurre que por error cambie el tipo de dato, en mi caso tenía DATETIME, pero al momento de cambiar el dato en el design del SQL por motivos de consulta mas sencilla yo le coloque TIME en vez de DATE por error a la columna FECHA, por lo que las fechas se me borraron y a parte no me deja volver a colocar el tipo de dato DATE, me muestra el mensaje que adjunto a continuación los cuales me indican que no es posible compatible TIME con DATE, como se observa solo tengo el tipo de dato time y solo se visualizan los 00:00 del tiempo, antes de este error me salía la fecha y la horas en cero, como lo podría cambiar a date y en el mejor de los casos recuperar las fechas que estaban en el inicio, se puede? o tengo que importarla otra vez y relacionarla con las otras tablas, ya que originalmente es una tabla de Access . Gracias de antemano , saludos.

A:

No podrás hacerlo directamente, tendrías que pasar primero a datetime y luego a date, algo asi:
ALTER TABLE TU_TABLA ALTER COLUMN NOMBRE_CAMPO DATETIME;
GO
ALTER TABLE TU_TABLA ALTER COLUMN NOMBRE_CAMPO DATE;

Aunque realmente nunca he hecho algo parecido, lo mas seguro es que no puedas recuperar la fecha ya que al cambiar a time la fecha se truncó en el registro original.


Q:

Unit Tests are never discovered

I have the following solution in Visual Studio 2017 Update 3 preview, which consists of a Xamarin.Forms project as NetStandard1.4 and a NetStandard1.4 dotnet Core Services.API project and a NetStandard1.6 dotnet Core unit test project.

The Unit Test project references the services project only. The csproj file looks like this, with the MSTest framework added for unit testing. The issue though is that the tests are never discovered.
csproj
<PropertyGroup>
    <TargetFramework>netstandard1.6</TargetFramework>
    <AssemblyName>FloatSink.Services.Api.Tests</AssemblyName>
    <RootNamespace>FloatSink.Services</RootNamespace>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>full</DebugType>
    <DebugSymbols>True</DebugSymbols>
</PropertyGroup>

<ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0"></PackageReference>
    <PackageReference Include="Microsoft.TestPlatform.TestHost" Version="15.0.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="1.1.17" />
    <PackageReference Include="MSTest.TestFramework" Version="1.1.17" />
</ItemGroup>

<ItemGroup>
    <ProjectReference Include="..\Services.API\Services.API.csproj" />
</ItemGroup>

Unit Test class
[TestClass]
public class AppBuilderTests
{
    private const string DebugBuild = "Debug build";
    private const string ReleaseBuild = "Release build";

    /// <summary>
    /// Test that the ToString() method returns the string we sent into the constructor
    /// </summary>
    [TestMethod]
    public void ToStringReturnsStringFromCtor()
    {
        // Act
        var build = new AppBuild(DebugBuild);

        // Assert
        Assert.AreEqual(DebugBuild, build.ToString());
    }
}

Finally this is the test output when I build and select Run All from the Test Explorer (which is empty).

[5/26/2017 6:38:23 PM Informational] ------ Load Playlist started ------
[5/26/2017 6:38:23 PM Informational] ========== Load Playlist finished (0:00:00.004501) ==========
[5/26/2017 6:38:24 PM Informational] ------ Discover test started ------
[5/26/2017 6:38:25 PM Informational] ========== Discover test finished: 0
  found (0:00:00.5716028) ==========

Why won't the MSTest unit tests show up in the Test Explorer and allow me to discover/run them?
Update
I changed the debug type from Full to portable and I've also tried this with xUnit and have the same issue. So this isn't specific to MSTest.
csproj with xUnit
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard1.6</TargetFramework>
    <AssemblyName>FloatSink.Services.Api.Tests</AssemblyName>
    <RootNamespace>FloatSink.Services</RootNamespace>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DebugType>portable</DebugType>
    <DebugSymbols>True</DebugSymbols>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Services.API\Services.API.csproj" />
  </ItemGroup>

</Project>

A:

The problem is that your TargetFramework is set to a .NET Standard version.
Although test projects look like libraries, they have more characteristics of a runnable output - the 15.0.0 test sdk even changes the output type to Exe to trigger generation of assets needed to run the tests. (In 2.0 / 15.3.0 this will change to a new HasRuntimeOutput property).
The fix here is to change the TargetFramework to either some version of net* or netcoreapp* depending on what framework you want to run the tests on.


Q:

Service class and logging design Scala with Futures

I have a service class that gets some data from a database (for context, I'm using Play! Framework). Here's an example method:
  def getAccessToken(id: BSONObjectID): Future[Option[String]] = {
    userDAO.find(id).map {
      case Some(user) =>
        user.settings flatMap (_.accessToken)
      case _ => None
    }
  }

I'm trying to improve the error handling (new to Scala) on this thing as there are a couple things that can go wrong:

User might not be found
User might be found but accessToken might not be set (accessToken is an Option[String])

As it stands right now, I can't differentiate between the two. My natural inclination to fix this is to use \/ from Scalaz and have the return type be Future[ErrorType \/ String] and this seems like a reasonable approach. In my controller method, I can for comprehension a bunch of different service methods like this by lifting into a wrapper monad.
But I have the following questions:

Should my ErrorType extend Exception, or should I just use the sealed trait style and just extend from that. I've heard that it is not good practice to use exceptions in Scala, so I'm not sure what the right approach is.
How can I handle logging without polluting the controller class with excessive log statements? If a controller class calls a bunch of these service methods, the controller will have to handle several different ErrorTypes in the for comprehension. Assuming I'm lifting all the monads to a wrapper monad with ?|, I want to avoid this:
accessToken <- service.getAccessToken(id) ?| { error => error match { case Error1 =>
               logger.error(
                 "Unable to find access token for user: " + id
                   .toString())
               InternalServerError(
                 ApiResponse("internal_server_error",
                             "Unable to get token."))
               case Error2 => ...
             }

Thanks!

A:

I think Future[ErrorType / String] is a bit overkill as Future[T] already can hold either an object of type T or an Exception derived one (see Future.successful(...)/ Future.failed(...))

Should my ErrorType extend Exception, or should I just use the sealed trait style and just extend from that. I've heard that it is not good practice to use exceptions in Scala, so I'm not sure what the right approach is.

I would recommend to use a class (or a set of classes, one per particular error type), say YourAppException derived from Exception, as you need to handle low level exceptions one way or another anyway.
I agree that throwing/catching exceptions is not going very well with functional code and it is better to use Try[T] or Future[T] to return errors in a more explicit way instead. On the other hand there is nothing wrong with using an Exception derived class to hold some error info. It is often useful to wrap the original non-application (say IO) exception in an application one and keep a reference to the initial one in Exception's 'cause' for troubleshooting. It gives an opportunity to provide a more context specific error message.

How can I handle logging without polluting the controller class with excessive log statements?

Consider encapsulating error messages in Exception derived case classes, representing application errors so you can access the error messsages uniformly using exception.getMessage. It is easy to add some method to YourAppException to construct ApiResponse as well.
def getAccessToken(id: BSONObjectID): Future[String] = {
    userDAO.find(id).flatMap {
      case Some(user) =>
        val optToken = user.settings.flatMap (_.accessToken)
        optToken.map(Future.successful).getOrElse(Future.failed(AccessTokenIsInvalid(user)))
      case _ => Future.failed(UserNotFoundError(user))
    }
  }

case class AccessTokenIsInvalid(user: String)
  extends YourAppException(s"Access token is invalid for user $user") {
}

accessToken <- service.getAccessToken(id) ?| { error =>
           logger.error(error.getMessage)
           InternalServerError(
             ApiResponse("internal_server_error", error.getMessage))
         }


Q:

Formula field in Opportunity to populate Opportunity Line Items

I have given a requirement of populating the Opportunity Line Items in a formula field in Opportunity Object. But i find it unable to write the formula for this as Opportunity Line Items And Opportunity shares a LookUp Relationship ...
Is there anything i am missing here. Kindly suggest any approach.

A:

This cannot be achieved by formula.
Through formula, we can only traverse from child to Parent. Reverse is not possible.
Salesforce maintains special kind of relationship for Account-Contact and Opportunity-OpportunityLineItems.
Though those relationships are defined as lookup but behave as Master-Detail. That's why they are special.
You could create a field and write a trigger to populate the field.


Q:

Make a sad unicorn happy!

I am here to propose that a % of all unicoin's earned for the rest of the day count towards a donation to "Make a sad unicorn happy!" the group prevents any and all unhappy unicorns from becoming specialty in several different restaurants around the world where people specifically seek for unicorns as well as other cruelties such as skinning and others.
I've been able to see first hand what kind of cruelty they do such as:

Unicorns on a stick

Canned unicorn meat

unicorn pet disguise
And several other cruelties.
I hope StackOverflow will join the cause and if possible add a donation counter below the unicoin's widget...
If you support this act, post an answer with what sort of cruelty against unicorns have you seen!

A:

I'm very sad that my spell checker doesn't recognize the word "Unicoin".


Q:

Url redirection issue with redirect 301

I am trying to redirect url using this condition
RewriteCond %{HTTP_HOST} ^www.example.com/xyz/Pianos-212--0$
RewriteRule ^(.*)$ http://www.example.com/xyz/Pianos-212/ [R=301,L]

the output i get is this
www.example.com/xyz/Pianos-212/?getCategory=$1&getBrand=$2

I need output URL to look like this
http://www.example.com/xyz/Pianos-212/

I am sure there is one line written above my condition that looks like this
RewriteRule ".*-([0-9]+)-.*-([0-9]+)" category.php?getCategory=$1&getBrand=$2 [L]

It is automatically appending query string after rewritten url

A:

Try adding a ? to the end of your RewriteRule:
RewriteRule ^(.*)$ http://www.example.com/xyz/Pianos-212? [R=301,L]

See this answer for more information:
htaccess 301 redirect - Remove query string (QSA)


Q:

Google JSON/Ajax API - how do you get the next page of results?

According to : http://code.google.com/apis/ajaxsearch/documentation/#fonje
I get back a cursor result, but stupidly, the moreResultsUrl returns a URL NOT to the JSON service but to the main site - how do instead fetch the next page of results into JSON?

A:

Well, that's because moreResultsUrl is pointing to http://www.google.com/search instead of http://ajax.googleapis.com/ajax/services/search/web.
What you need are just the parameters of the moreResultUrl which you can pass to http://ajax.googleapis.com/ajax/services/search/web for the JSON result.
For example:
http://www.google.com/search?v=1.0&q=Luca
is translated in JSON with
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Luca
Google is just showing you their RESTful api, it's up to you to use the pages JSON value with whatever interface you want.


Q:

reverse returning an empty string in get_absolute_url

I am trying to use reverse for get_absolute_url in one of my models. However, it's returning blank string.
url.py
url(
    regex=r'^$',
    view=SocietyView.as_view(),
    name='society',
),
url(
    regex=r'^(?P<tagname>[\w ]+)/?$',
    view=SocietyView.as_view(),
    name='society_with_tag',
),

model.py
class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)
    posts = models.ManyToManyField(Post, related_name='tags', null=True, blank=True)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return reverse("society_with_tag", kwargs={"tagname": self.name})

template.html

    {{ tag.name }}

result.html

    tag

A:

I have no idea why but removing ',' in the end solved this problem.
Both catherine and caio gave me great answers but since I am not using 1.5, that wasn't it.
I changed
def get_absolute_url(self):
    return reverse("society_with_tag", args=[self.name,])

into
def get_absolute_url(self):
    return reverse("society_with_tag", args=[self.name])


Q:

adding a node in Multi Level Doubly link list in c

I am creating a multilevel doubly link list, I am performing the adding nodes operation in it.  I'm confused because according to my logic code mentioned below it should print the value, but it is not printing.  The output is not wrong but maybe I'm doing something wrong which could affect while flatten that list.
I have 3 levels of this list. addNode function will add at the very first level, where as addChild function will add a node anywhere in 2nd or 3rd level.
code is:
Student* StudentList::addNode(int num)
{
    Student* node = new Student(num);
    if(head == 0) {
       head = node;
       tail = node;
    } else {
       node->prev = tail;
       tail->next = node;
       tail = tail->next;
    }

    return node;
}

add child:
Student* StudentList::addChild(Student* node1, int num)
{
    Student* node = head;
    Student* temp;
    Student* temp1;

    // traversing the list to find exact location
    while(node != 0)
    {
        if(node->num == node1->num) {
            break;
        } else {
            temp = node->child;
            while(temp)
            {
                if(temp->num == node1->num) {
                    node = temp;
                    break;
                } else {
                    temp1 = temp->child;
                    while(temp1)
                    {
                        if(temp1->num == node1->num) {
                            node = temp1;
                            break;
                        } else {
                            temp1 = temp1->next;
                        }
                    }
                    temp = temp->next;
                }
            }
            node = node->next;
        }
    }

    Student* newChild = new Student(num);
    Student* curr = node->child;
    if(curr == 0)
    {
        node->child = newChild;
    } else {
        while(curr->next)
        {
            curr = curr->next;
        }
        newChild->prev = curr;
        curr->next = newChild;
    }
    return node1;
}

Main Method code is:
StudentList* sl = new StudentList();
Student* newNode;
Student* newNode1;

newNode = sl->addNode(1);
    newNode1 = sl->addChild(newNode,11);
        sl->addChild(newNode1, 111);
        sl->addChild(newNode1, 112);
    newNode1 = sl->addChild(newNode,12);
newNode = sl->addNode(2);
    newNode1 = sl->addChild(newNode,21);
    newNode1 = sl->addChild(newNode,22);
        sl->addChild(newNode1, 221);
        sl->addChild(newNode1, 222);
        sl->addChild(newNode1, 223);
newNode = sl->addNode(3);
newNode = sl->addNode(4);
    newNode1 = sl->addChild(newNode,41);
        sl->addChild(newNode1, 411);

sl->printList();

and my print list code is:
void StudentList::printList(){
Student* curr = head;
while(curr){
    cout<< *curr <<endl;
    if(curr->child){
        Student* newCurr = curr->child;
        while(newCurr){
            cout<< "*{"<<newCurr->num <<"}"<<endl;
            if(newCurr->child){
                Student* newCurr2 = newCurr->child;
                while(newCurr2){
                        //according to my login this 3rd level childs num(id) value
                        //should be printed used only for 2nd level according to my
                        //logic.. where is the problem am i doing wrong any thing?
                        cout<< "**{"<<newCurr2->num <<"}"<<endl;
                        newCurr2 = newCurr2->next;
                }
            }
            newCurr = newCurr->next;
        }
    }
    curr = curr->next;
}

}
Kindly help me in this, thanks in advance for everyone.

A:

From the output you've put in your comment it looks like nothing is being added at the second level. Where you're expecting nodes to be added at the second level, they are being added to the first.
I think the problem is at the bottom of the add child function:
Student* StudentList::addChild(Student* node1, int num)
{
    // rest of function. node1 is never modified
    return node1;
}

You are always returning the node input to that function. I think in your following code
newNode = sl->addNode(1);
    newNode1 = sl->addChild(newNode,11);
        sl->addChild(newNode1, 111);
        sl->addChild(newNode1, 112);

That you will find that newNode1 == nodeNode and not the child node as I think you are expecting. Probably the add child function should be returning newChild


Q:

Amortized Analysis: Find the Rate of Travel

A biker can travel at 24kms per hour with the flow of the wind, but only 12kms per hour against the wind. Assuming the biker starts and finishes at the same point.
What is the rider's amortized rate of travel?
I do not understand how the answer is arrived at, I have read my lecture notes but it is a little confusing.
Thanks

A:

I am assuming the biker goes from point A to point B, and then back from point B to point A, and from A-B he is going 24km/hr and from B-A he is going 12km/hr.
Amortized is a fancy term that here essentially means average, so we want to find the average speed that the biker is traveling.
The actual distance that the person travels is not relevant because the distance from A to B is equivalent to the distance from B to A.  For simplicity of the Math, lets say that the distance is 24 kilometers.
We can then say that at a rate of 24km/hr it would take 1 hour to get from A to B.
We can also say that at a rate of 12hm/hr it would take 2 hours to get from B to A.
This means that in total it takes 3 hours to get from A to B back to A.  In this time he has gone twice the distance (which we decided was 24).  That means in total he traveled 48km.
If it took 3 hours to go 48km, that is (48/3)km/hr or just 16km/hr for the average (amortized) rate of speed.
You can see that the distance we decide upon is indeed irrelevant if you plug in x for the distance, and carry it through.


Q:

How to index a std_logic_vector by enumeration

I have a std_logic_vector like this:
cntrl_signals:out std_logic_vector(4 downto 0);

One way to have indexes to this vector would be to explicitly define a constant for each.
constant CLK_SIG:integer := 0;
constant EN_SIG:integer := 1;
constant FOO_SIG:integer := 2;
constant BAR_SIG:integer := 3;
constant BAZ_SIG:integer := 4;

The idea is to use these to index the vector.
cntrl_signals <= (CLK_SIG=>1,EN_SIG=>1,others=>0);

My question is if there a nice shorthand way of declaring the indexes (like an enum in C)?

A:

Well you could use enumerations, the best way would be to declare your own vector of std_logic, indexed by the enumeration instead of by integer.
But probably better would be a record instead of a vector :
type Control_Signals is record
   Clk : std_logic,
   En  : std_logic,
   Foo : std_logic,
   Bar : std_logic,
   Baz : std_logic
end record;

EDIT for more information, following comment:
Unimaginative use of std_logic_vector (and VHDL's type system in general) is holding VHDL back...
If this is a top level entity, then std_logic_vector ports allow you to substitute a post-synthesis netlist for your synthesisable design in the top level testbench. Or you may have to comply with antiquated coding style guidelines that insist on std_logic_vector ports.
But in any other circumstance I would declare the record in a package, use that package throughout the design, and make the ports of the record type. The package should include functions to_slv and to_control_sigs for the (rare, if you get it right) occasions when you actually need std_logic_vectors.
The same applies with enumerations:
type Controls is (Clk, En, Foo, Bar, Baz);
type Control_Signals is array(Controls) of std_logic;
My_Bus_Ctrl : Control_Signals := (Clk => '1', En => '1', others => '0');
My_External_SLV_Port <= std_logic_vector(My_Bus_Ctrl);

And of course, enumerations are a bit more powerful than in C; as well as using them as array index types, you can loop over them. Which keeps your loops in line whenever you update the enumeration!
Records or arrays indexed by enumerations both work; I prefer the record as a bit cleaner and more in line with object oriented practice.
In either case it becomes FAR more useful if you use it for entity ports. Declare one record (or array!) for outgoing bus signals (including address and data) and another for incoming signals, because you can't mix directions in a single port... (There are no bidirectional signals in an FPGA these days, so there is no need for a third port)
Now your design is protected against bus structure changes; changing the address width or adding an interrupt signal only changes the record declaration and any actual users; there is no need to add the new signal throughout the hierarchy...


Q:

Can't extract mp3 audio from video with ffmpeg

My input is a .mp4 video file.
Try #1
ffmpeg -i pipe:0 -y -map a media/73.mp3

Error:
ffmpeg version 3.3.3 Copyright (c) 2000-2017 the FFmpeg developers
  built with Apple LLVM version 8.1.0 (clang-802.0.42)
  configuration: --prefix=/usr/local/Cellar/ffmpeg/3.3.3 --enable-shared --enable-pthreads --enable-gpl --enable-version3 --enable-hardcoded-tables --enable-avresample --cc=clang --host-cflags= --host-ldflags= --enable-libmp3lame --enable-libx264 --enable-libxvid --enable-opencl --enable-videotoolbox --disable-lzma --enable-vda
  libavutil      55. 58.100 / 55. 58.100
  libavcodec     57. 89.100 / 57. 89.100
  libavformat    57. 71.100 / 57. 71.100
  libavdevice    57.  6.100 / 57.  6.100
  libavfilter     6. 82.100 /  6. 82.100
  libavresample   3.  5.  0 /  3.  5.  0
  libswscale      4.  6.100 /  4.  6.100
  libswresample   2.  7.100 /  2.  7.100
  libpostproc    54.  5.100 / 54.  5.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f977d800000] stream 1, offset 0xa8: partial file
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f977d800000] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none(smpte170m/smpte170m/bt709), 320x176, 300 kb/s): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'pipe:0':
  Metadata:
major_brand     : mp42
minor_version   : 0
compatible_brands: mp42isomavc1
creation_time   : 2012-03-13T08:58:06.000000Z
encoder         : HandBrake 0.9.6 2012022800
  Duration: 00:00:10.03, bitrate: N/A
Stream #0:0(und): Video: h264 (avc1 / 0x31637661), none(smpte170m/smpte170m/bt709), 320x176, 300 kb/s, 25 fps, 25 tbr, 90k tbn, 180k tbc (default)
Metadata:
creation_time   : 2012-03-13T08:58:06.000000Z
  encoder         : JVT/AVC Coding
Stream #0:1(und): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 160 kb/s (default)
Metadata:
  creation_time   : 2012-03-13T08:58:06.000000Z
Stream #0:2(und): Audio: aac (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 160 kb/s
Metadata:
  creation_time   : 2012-03-13T08:58:06.000000Z
Stream #0:3(und): Subtitle: mov_text (text / 0x74786574), 0 kb/s
Metadata:
  creation_time   : 2012-03-13T08:58:06.000000Z
Stream mapping:
  Stream #0:1 -> #0:0 (aac (native) -> mp3 (libmp3lame))
  Stream #0:2 -> #0:1 (aac (native) -> mp3 (libmp3lame))
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x7f977d800000] stream 1, offset 0xa8: partial file
pipe:0: Invalid data found when processing input
Finishing stream 0:0 without any data written to it.
Finishing stream 0:1 without any data written to it.
[mp3 @ 0x7f977b846800] Invalid audio stream. Exactly one MP3 audio stream is required.
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
Error initializing output stream 0:1 --
Conversion failed!

Try #2
ffmpeg -i pipe:0 -y -vn -acodec copy media/72.mp3

Error:
[...]
[mp3 @ 0x7febed835200] Invalid audio stream. Exactly one MP3 audio stream is required.
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument

Try #3
ffmpeg -i pipe:0 -y -codec:a libmp3lame -qscale:a 2 media/74.mp3

No error with ffmpeg, but the file is invalid (it's size is 334 bytes)

Try #4
ffmpeg -i pipe:0 -y -vn -acodec mp3 media/78.mp3

No error with ffmpeg, but the file is invalid (it's size is 334 bytes)

Try #5
ffmpeg -f mp4 -i pipe:0 -y media/80.mp3

No error with ffmpeg, but the file is invalid (it's size is 334 bytes)

What am I doing wrong? This seems like a fairly easy thing to do...

A:

Try this for extract .mp3:
ffmpeg -i video.mp4 -map 0:a -acodec libmp3lame out.mp3

And maybe this useful for extract .m4a:
ffmpeg -i video.mp4 -map 0:a -c copy out.m4a

A:

FFmpeg can't update metadata in WAVE files when output is written over a non-seekable protocol like a pipe. Quicktime seems to rely on metadata to determine file validity. You have to write to file or some other seekable protocol.

Please refer to this question.


Q:

How can I check if something in html is set to false or true using beautifulsoup?

So I have a html file and I wanna check some values in it.
For example: data-online="false", data-channel="123breakmefree"
So I wanna check if 'data-online' is set to true or false and what channel is marked in data-channel. And if channel is something else than '123breakmefree'.
Thanks!
P.S: English is not my main language so I could not find anything on that by googling.

A:

This code shows how to load a html string, get a tag and then the attributes:
from bs4 import BeautifulSoup

html = '
test text
'

s = BeautifulSoup(html)
tag = s.find(id='my-tag')

print tag.attrs
print tag['data-online']
print tag['data-channel']


Q:

How to deploy angular universal app in azureDevOps app service

I'm facing a problem deploying an angular universal app in azure web service I followed this step https://stackoverflow.com/a/53616516/10979521 but a got an error says
##[error]Error: Publish using webdeploy options are supported only when using Windows agent.

I guess the issue occurs in creating an app service, in my app service settings
    (
           *publish  (code)
           *runtime stack (.NET Core 2.2)
            *Operating System (Windows)
    )
# Node.js with Angular
# Build a Node.js project that uses Angular.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '10.x'
  displayName: 'Install Node.js'

- script: |
    npm install -g @angular/cli
    npm install
    npm run build:ssr
  displayName: 'build the project'

- task: CopyFiles@2
  displayName: 'Copy dist files to staging'
  inputs:
    SourceFolder: '$(Build.SourcesDirectory)/dist'

    TargetFolder: '$(Build.ArtifactStagingDirectory)/app/dist'

- task: CopyFiles@2
  displayName: 'Copy server.js to the root'
  inputs:
    SourceFolder: '$(Build.ArtifactStagingDirectory)/app/dist'

    Contents: server.js

    TargetFolder: '$(Build.ArtifactStagingDirectory)/app'

- task: DeleteFiles@1
  displayName: 'Delete the dist/server.js'
  inputs:
    SourceFolder: '$(Build.ArtifactStagingDirectory)/app/dist'

    Contents: server.js

- task: AzureRmWebAppDeployment@3
  displayName: 'Azure App Service Deploy: website'
  inputs:
    azureSubscription: 'my subscription'
    WebAppName: 'my website'
    Package: '$(Build.ArtifactStagingDirectory)/app'
    GenerateWebConfig: true
    WebConfigParameters: '-Handler iisnode -NodeStartFile server.js -appType node'
    UseWebDeploy: true
    RemoveAdditionalFilesFlag: true

A:

Edit 2 (9/3/2020)
Microsoft is moving away from release pipelines.
"Classic Release Pipelines"
https://docs.microsoft.com/en-us/azure/devops/pipelines/release/?view=azure-devops
New "Pipelines"
https://docs.microsoft.com/en-us/azure/devops/pipelines/create-first-pipeline?view=azure-devops&tabs=java%2Cyaml%2Cbrowser%2Ctfs-2018-2
Edit:
I realized after I typed this up that maybe your problem is you have "UseWebDeploy: true" and maybe you can fix your problem by setting this to false.  Below is a screenshot taken from the same task setup in a release pipeline.

I still think your best option is to remove the deploy task from your build pipeline as outlined below since build pipelines are not meant to be used in this way.  But that is up to you.
Original Answer:
Remove this part from your build pipeline:
- task: AzureRmWebAppDeployment@3
  displayName: 'Azure App Service Deploy: website'
  inputs:
    azureSubscription: 'my subscription'
    WebAppName: 'my website'
    Package: '$(Build.ArtifactStagingDirectory)/app'
    GenerateWebConfig: true
    WebConfigParameters: '-Handler iisnode -NodeStartFile server.js -appType node'
    UseWebDeploy: true
    RemoveAdditionalFilesFlag: true

Add a publish step to the end of you build.yml file.  This will allow your release pipeline to pick up the artifacts from your build.
- task: PublishBuildArtifacts@1

Setup a release pipeline to deploy your build.

Create a new pipeline
Add the artifact from your build

Then add a stage (ie Dev, QA, Production)
Select "empty job"
Edit the stage and add tasks
Add the Azure App Service task

Update the version number on the Azure App Service Deploy to version 3 (the same one you are using in your yaml - AzureRmWebAppDeployment@3).
Fill in the values in the task the same way you have it in your yaml.

The default value for the "Package or folder" option probably isn't correct.  You can use the 3 dots on the right to navigate and select the correct folder.  If you click this and see nothing then this is most likely because you haven't kicked off a build yet with the above "PublishBuildArtifact@1" change.

Keep working your way down and expanding the options to find your other configuration settings.

If you are having trouble with anything you can verify the task is setup properly by scrolling to the top of the task and clicking "View YAML".  Then you can compare to your original yaml.

Hopefully this helps.


Q:

Call a jQuery function when a button is being clicked

I'm trying to set jQuery a function on its own, and call the function when a click event triggers. Here's the code I've managed to come up with:
HTML:
<input type="text" class="form-control email_input" name='email' id="reserve_email_1" placeholder="Email">
                <span class='input-group-btn'>

                  <button type="submit" id="subscribe_1" class="btn btn-success subscribe_button">Send now</button>

</span>

JS:
$(document).ready(function(){
$('.subscribe_button').click(function(){
$.fn.Subscribe();
 });

 $.fn.Subscribe = function(){
  var email = $(this).parent().siblings('.email_input').val();
  alert(email);
}

});

But no matter what values I have in the email input, it would not pop up in the alert. I tested and don't think it's the wrong traversing order, but rather the first function failed to call the 2nd function. Any advice on why it would happen?
Best,

A:

Subscribe is a plugin method, so you need to invoke it like a jQuery plugin like(so that the method will get proper context value for this)
$('.subscribe_button').click(function () {
    $(this).Subscribe();
});

Demo: Fiddle


Q:

Help understanding unipolar transfer function

There is a question I am stuck on using the following formula for the unipolar transfer function:
f(net)=     1
         __________
               -net
         1 + e

The example has the following:
out =        1
        ____________  = 0.977
               -3.75
        1 + e

How do we arrive at 0.977?
What is e?

A:

e = 2.71828... is the base of natural logarithms. It's a mathematical constant that comes up in many different equations, similar to π. You will see it all the time when doing exponents and logarithms.
Plug it into your equation and you get 0.977.

A:

While factually correct the other responses merely provide the value of e and confirm the underlying computation.  This type of sigmoid functions is so ubiquitous to neural networks that some additional insight may be welcome.
Essentially the exponential function (e to the x power),  has a very characteristic curve:

Mostly flat at zero (very slightly above zero, actually),  from - infinity to about  -2
incrementally sharp turn towards the vertical, between about -2 and +4
quasi "vertical", with values in excess of 150 and increasingly huge, from +5 to infinity

As a result exponential curves are very useful for producing "S-shaped" functions; BTW, "S" is Sigma in Greek which supplied the etymology for "sigmoid". Such functions are often patterned on the formula shown in the question:
 1/(1 + e^-x)

where x is the variable.  Typically such functions also include constants aimed at stretching the range (the input zone where changes in x are significant) and/or at modifying the curve in this middle zone.
The result of such functions is that up to a particular value of the input, the function is quasi constant, then, for a particular range of inputs, the function provides a increasing output, and finally past the upper value of the range, the function is quasi constant.  Also looking in more details, such Sigmoids have a point of inflection which correspond to a reversing of the rate of change of the ouptut and which also marks an area of the curve, on either side, where the changes are the slowest, relatively.
In turn, such S-shaped curves (1) are very useful to normalize the output of neural network neurons, or more generally, to normalize various numeric values during processes of various nature.  Intuitively these correspond to a "sweet spot" or a "sweet range" of the underlying neuron or device.
(1) Or also, possibly,  "step-down" shaped curves, i.e. curves with a mostly constant high value, a decreasing value within the mid-range, and a low mostly constant value thereafter.


Q:

Oracle integer to number conversion

According to the Oracle documentation, creating a table with a column of ANSI type INT, Oracle will convert it to NUMBER(38).  According to the same document, NUMBER(38) is supposed to be a NUMBER with a precision of 38 and a scale of 0. But in practice, I am seeing a NUMBER with data_precision set to NULL and a data_length set to 22.
SQL> create table ltheisen.silly ( id int );

Table created.

SQL> select substr(data_type,1,10), data_length, data_scale, data_precision from
 all_tab_columns where owner='LTHEISEN' and table_name='SILLY' and column_name='
ID';

SUBSTR(DATA_TYPE,1,10)                   DATA_LENGTH DATA_SCALE DATA_PRECISION
---------------------------------------- ----------- ---------- --------------
NUMBER                                            22          0

What gives?
Also, I am trying to do a generic conversion from Oracle to ANSI.  Is there any way to determine from the metadata that the NUMBER was created as, or fits into an INT?
Lastly, I tried creating with BINARY_INTEGER which appears in the documentation, but the create statement fails:
SQL> create table ltheisen.silly ( id binary_integer );
create table ltheisen.silly ( id binary_integer )
                                 *
ERROR at line 1:
ORA-00902: invalid datatype

What am I missing?
-------------------- UPDATE -----------------------------
Reading a little deeper gives this gem:

Specify a floating-point number using the following form:
NUMBER
The absence of precision and scale designators specifies the maximum range and precision
for an Oracle number.

So since the datatype is NUMBER and there is no precision specified, we can assume it is maximum precision?

A:

A DATA_LENGTH of 22 is just the largest number of bytes it can take to store the largest possible number (Oracle uses 2 digits per byte). A NULL DATA_PRECISION implies the maximum of 38.
You can verify this with DBMS_METADATA:
SQL>  create table sotmp ( a int );

Table created.

SQL> select dbms_metadata.get_ddl('TABLE','SOTMP')
  2  from dual;

DBMS_METADATA.GET_DDL('TABLE','SOTMP')
--------------------------------------------------------------------------------

  CREATE TABLE "PHIL"."SOTMP"
   (    "A" NUMBER(*,0)
   ) SEGMENT CREATION DEFER

SQL>

(The "*" in the above output denotes the maximum precision).
BINARY_INTEGER is not a data type that can be used in table columns. It can only be used as a PL/SQL variable datatype.


Q:

Using Visual Studio with a screen reader without paying for an expensive edition

I'm a totally blind programmer who would like to learn .net.
It appears that the Visual Studio express editions are not accessible since the scripts that come with Jaws for Windows, the screen reading software I use, requires the VS object model to make Visual Studio accessible. This is not available in the express editions, so the scripts may partially work or not work at all.
None of the options mentioned in this question apply to me and I don't want to spend $500 or more to buy Visual Studio professional when I may never use it for a job.
If I take the time to try out the express versions and run into issues is there any way to contact Microsoft without my questions/feedback being lost in a black hole?

A:

You can get a 90 day free trial of Visual Studio at http://www.microsoft.com/visualstudio/ that should enable you to give it a darn good try. If you like it, and you decide you will go into .NET development, you will probably qualify for BizSpark if you decide to make a product you will sell. I agree that if you only intend to use it while working for a large company, you won't qualify, but then your employer will provide it, right?
Beyond that practical information, some general encouragement and suggestions. There was a 2004 video on Channel 9 about an intern who used a screen reader and Braille keyboard to code. It's at http://channel9.msdn.com/Blogs/TheChannel9Team/Kenneth-Spector-Coding-without-seeing-the-screen and while I realize you may not be able to see it, others who use this question later might. In the comments to that video, Sara Ford identified herself as the "go to" person for accessibility at Microsoft and encouraged people to contact her. Sara has since left Microsoft, but I think it's a good bet there is still such a person. I've had remarkable luck calling the main switchboard and asking for "the person who handles" whatever I want to talk about; you could try doing the same thing. That could lead to a conversation about how well Express works with Jaws.
There is an entire Developer Accessibility area on MSDN http://msdn.microsoft.com/en-us/windows/bb735024.aspx although from a quick read it seems to be more about helping developers to write apps that are accessible. However it has a TON of links including to forums and blogs, so perhaps one of them will be helpful. I think you'll find Microsoft will be delighted to help you succeed at this endeavour.

A:

Visual Studio community edition appears to provide access to the VS object model. I was able to create a project and do basic code editing with no issues. I've just started but it looks like this solves my issue.


Q:

Does UPDATE happen column by column in SQL Server

I have following query -
 UPDATE THINGS

SET Col 1 = CASE when 'A' then 'APPLE'
                 when 'B' then 'BALL'
                 when 'C' then 'CARROT'
                 else NULL
                 end,
    Col 2 = Case Col 1 when 'APPLE' then 'FRUIT'
                       when 'BALL'  then 'TOY'
                       when 'CARROT' then 'SALAD'
             else NULL
             end

My question is will the update happen on column by column basis so that I can get updated values in my Col 2 successfully? If it is not possible by above query, is there any other way to update it within a single query? I cannot write two separate queries.

A:

You can use this approach by using variable to store data and then use it foe next column.
DECLARE @val VARCHAR(20) -- type of Col1
UPDATE THINGS
SET @val = [Col 1] = CASE WHEN 'A' THEN 'APPLE'
                          WHEN 'B' THEN 'BALL'
                          WHEN 'C' THEN 'CARROT'
                     END,
       [Col 2] = CASE @val WHEN 'APPLE'  THEN 'FRUIT'
                           WHEN 'BALL'   THEN 'TOY'
                           WHEN 'CARROT' THEN 'SALAD'
                 END


Q:

Is it possible to use spread on multiple columns in tidyr similar to dcast?

I have the following dummy data:
library(dplyr)
library(tidyr)
library(reshape2)
dt <- expand.grid(Year = 1990:2014, Product=LETTERS[1:8], Country = paste0(LETTERS, "I")) %>%   select(Product, Country, Year)
dt$value <- rnorm(nrow(dt))

I pick two product-country combinations
sdt <- dt %>% filter((Product == "A" & Country == "AI") | (Product == "B" & Country =="EI"))

and I want to see the values side by side for each combination. I can do this with dcast:
sdt %>% dcast(Year ~ Product + Country)

Is it possible to do this with spread from the package tidyr?

A:

One option would be to create a new 'Prod_Count' by joining the 'Product' and 'Country' columns by paste, remove those columns with the select and reshape from 'long' to 'wide' using spread from tidyr.
 library(dplyr)
 library(tidyr)
 sdt %>%
 mutate(Prod_Count=paste(Product, Country, sep="_")) %>%
 select(-Product, -Country)%>%
 spread(Prod_Count, value)%>%
 head(2)
 #  Year      A_AI       B_EI
 #1 1990 0.7878674  0.2486044
 #2 1991 0.2343285 -1.1694878

Or we can avoid a couple of steps by using unite from tidyr (from @beetroot's comment) and reshape as before.
 sdt%>%
 unite(Prod_Count, Product,Country) %>%
 spread(Prod_Count, value)%>%
 head(2)
 #   Year      A_AI       B_EI
 # 1 1990 0.7878674  0.2486044
 # 2 1991 0.2343285 -1.1694878

A:

With the new function pivot_wider() introduced in tidyr version 1.0.0, this can be accomplished with one function call.
pivot_wider() (counterpart: pivot_longer()) works similar to spread().
However, it offers additional functionality such as using multiple key/name columns (and/or multiple value columns).
To this end, the argument names_from—that indicates from which column(s) the names of the new variables are taken—may take more than one column name (here Product and Country).
library("tidyr")

sdt %>%
    pivot_wider(id_cols = Year,
                names_from = c(Product, Country)) %>%
    head(2)
#> # A tibble: 2 x 3
#>     Year   A_AI    B_EI
#>    <int>  <dbl>   <dbl>
#>  1  1990 -2.08  -0.113
#>  2  1991 -1.02  -0.0546

See also: https://tidyr.tidyverse.org/articles/pivot.html


Q:

Determining sunrise and sunset times based on azimuth and elevation

If I observe the sun and measure the local azimuth and elevation, and I also have my latitude, can I calculate the local sunrise and local sunset times? If so, how would I calculate it?
Further, can the same calculations be used for the moonrise and moonset?

A:

$
\cos ^{-1}\left(-\frac{\tan (\lambda ) (\cos (\lambda ) \cos (\phi ) \cos
(Z)+\sin (\lambda ) \sin (Z))}{\sqrt{(\cos (\lambda ) \sin (Z)-\sin (\lambda)
\cos (\phi ) \cos (Z))^2+\sin ^2(\phi ) \cos ^2(Z)}}\right)-\tan^{-1}
(\cos (\lambda ) \sin (Z)-\sin (\lambda ) \cos (\phi ) \cos (Z),\sin
(\phi ) (-\cos (Z)))
$
is the amount of time from now (see important notes below) a celestial object will set, where:

$\phi$ is the azimuth of the object
$Z$ is the altitude of the object above the horizon
$\lambda$ is the latitude of the observer

Note the two-argument form of arctangent is required for accuracy: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Two-argument_variant_of_arctangent
Important notes (MUST READ!):

The result is in radians. To convert to sidereal hours, multiple by $\frac{12}{\pi }$
If the object has a fixed right ascension and declination, divide sidereal hours by 1.002737909350795 to get clock hours.
For the Sun (which doesn't have fixed right ascension/declination), do NOT divide as above. By not dividing, you compensate for the Sun's change in right ascension.
For the Moon, see "The Moon" section below.
The time computed above is for geometric midpoint setting. In reality, refraction near the horizon means the object will set later. Additionally, for objects that have an angular diameter (eg, the Sun), setting usually means when the top edge disappears over the horizon, which will make the set time even later. Accounting for both effects should be possible, but might require numerical methods instead of a closed form formula as above.
If the quantity inside the arccosine is greater than 1, the object is always in the sky and never sets or rises.
If the quantity inside the arccosine is less than -1, the object is never in the sky and thus also never sets or rises.
I did only minimal testing. As always, do not rely on my answers for anything important.

The Moon:

The Moon's right ascension and declination change rapidly, so this calculation does not work well for the moon.
You could compensate for the change in right ascension (and thus hour angle) by approximating the increase as 24 hours every 27.32158 days (its sidereal period) and do an iterative calculation.
An even better compensation for the change in right ascension would be to approximate the moon's movement in ecliptic longitude (which is more constant than its movement its right ascension) as 360 degrees per 27.32158 days and then project the ecliptic longitude back to right ascension, and then iterate.
Compensating for the moon's change in declination is more difficult. The moon's ecliptic latitude (which can be converted to declination) varies sinusoidally, but the equation $\sin (x)=a$ normally has two solutions. Unless you know whether the moon's ecliptic latitude is increasing or decreasing (ie, whether it's between ascending and descending nodes or vice versa), you won't know the direction of declination change.

Less important notes (optional):

See Need Simple equation for Rise, Transit, and Set time for more general equations on when an object rises/sets/etc.
Calculations for this answer at: https://github.com/barrycarter/bcapps/blob/master/STACK/bc-object-riset-from-az-elt.m
Related calculations: https://github.com/barrycarter/bcapps/blob/master/STACK/bc-rst.m
Mathematica was unable to find a simpler form for the "time to set" above, though I sense a simpler form does exist (I could be wrong).
If you know the Sun's declination (which you can get from its azimuth and elevation as above), you can almost determine the date. However, the sun reaches a given declination twice a year (example: it reaches 0 degrees declination on both equinoxes, by definition), so you can only know it's one of two days.

Solution notes:
I learned quite a bit answering this question, and thought it was only solvable numerically until I figured out the shortcut:

To convert from the azimuth/elevation sphere to the hour angle/declination sphere, you just rotate around the y axis by $\frac{\pi }{2}-\lambda$ (90 degrees minus the latitude) and then rotate $pi$ (180 degrees) around the z axis.
Once you have the declination, computing the hour angle when an object sets is easy.
You then subtract the setting time from the current hour angle to get the answer.

TODO: I was hoping to add some graphs/visualizations to this answer but couldn't quite get things working.


Q:

Using razor views with jQuery validation with angularJS

I'm using AngularJS in my MVC application and trying to use the best of both worlds. I really like how you can in MVC set up your validation logic in your viewmodels and generate client side validation with jQuery validation in your razor views with little effort. I use AngularJS to get the SPA behavior with routing etc, but when I create a razor view that I use to inject into a page with:

then the jQuery validation stops working, even though the script files is references on the page where the view is injected. See below for my razor view:
@model BandViewModel

    <form name="startBandForm">
        @Html.ValidationSummary(true)

        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name, new { data_ng_model = "band.Name" })
        @Html.ValidationMessageFor(m => m.Name)

        <input data-ng-disabled="startBandForm.$invalid" type="submit" data-ng-click="createBand(band)" value="Create"/>
    </form>

A:

First of all, IMO using Razor to render your templates is fraught with peril, at best. Generally you want to use static HTML for your page and directive templates, and then retrieve and post data as AJAX to your API. The ASP.NET web API is really good at this, actually. If your underlying model has validation, then bad web API calls will throw an exception, which you can catch in your $http or $resource handler and show to the user. Mixing standard HTTP form posts with AngularJS will be... difficult.
To achieve what you want, I think someone (not me) would have to write the AngularJS equivalent to jQuery Unobtrusive Validation library, which itself is using the jQuery Validate plugin. Not trivial. I personally don't see drop-in Angular validation happening soon, especially since it has more to do with markup and less to do with a JS configuration object.
Possibly you could re-initialize the validation when the view has finished loading using the $viewContentLoaded event. But please don't.

A:

It pains me that everywhere I've looked we get the same replies: "HTML should just be a template". Perhaps, but I'm just not ready to delegate everything to JavaScript
Instead of using the anonymous object for passing the HTML attributes, try using the Dictionary
@Html.TextBoxFor(m => m.Name, new Dictionary<string, object>(){{ "data_ng_model",  "band.Name" }})

Make sure is
Dictionary<string, object>

And not
Dictionary<string, string>

Otherwise the constructor will confuse it for
object HtmlAttribute

Not as pretty though... but it works for the most part.
Lastly, take in mind that if you include AngularJS after jQuery, then it will use jQuery for selectors.

A:

To anyone still looking for a solution to this problem , there is a simple way to make it work.
    var currForm = $("#myForm");
currForm.removeData("validator");
currForm.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(currForm);
currForm.validate();

You could put this code in $viewContentLoaded or other places which are relevant in your code.
While I understand some of the views here which discourage MVC views being used as a templates for your Angular code. My reason being its not  not a natural way of doing things in angular and hence there are chances that you will run into issues like this one. But if you benefit from using MVC views as templates its not a path to hell. IT works and can benefit you as well. I have 2 use cases in my project where using MVC views make a lot of sense.

My project actually has a requirement where a client can turn of the required validation on certain field ,  for this I use the MVC custom data annotation validator which allows me to add or remove the data annotation at the time of rendering the view using a single class , if you were to build the same flexibility in angular , you would have to write a lot more code. So MVC views work great here for me as Custom Data Annotations are triggerd by the DisplayFor and EditorFor helpers
We are heavily invested in Internationalization and while angular is great at other stuff  internationalization is not its strong suite ( at the time of writing this atleast )I still feel the internationalization support in MVC with .RESX works great and has been here long . This again uses the data annotation power of the DisplayAttribute.

TLDR : MVC views as templates may give you a few unexpected problems but are worth it if you are really using the full power of the data annotation pipeline created by Microsoft.
Hopefully someone comes up with a Angular HTML Helpers library in the future this would be much simpler.


Q:

Calibrate against multi-dimensional population totals using the survey package?

Is there a way to calibrate against multidimensional control totals using the survey package? I have been able to estimate poststratification weights, but now I'm stuck with the calibration. (I have a clustered design and need the weights to stay the same within each cluster.) Do I have to recode all combinations into a new attribute?
> df <- data.frame(id=c(1,1,1,2,2,3,4,5,5),
+                  h=factor(c(1,1,1,0,0,1,0,1,1)),
+                  p=factor(c(1,0,1,0,1,0,0,0,1)))
>
> df
  id h p
1  1 1 1
2  1 1 0
3  1 1 1
4  2 0 0
5  2 0 1
6  3 1 0
7  4 0 0
8  5 1 0
9  5 1 1
> des <- svydesign(id=~id, data=df)
Warning message:
In svydesign.default(id = ~id, data = df) :
  No weights or probabilities supplied, assuming equal probability
> pop <- xtabs(Freq~., data.frame(h=factor(c(0, 1, 0, 1)),
+                                 p=factor(c(0, 0, 1, 1)),
+                                 Freq=c(40, 35, 25, 10)))
> pop
   p
h    0  1
  0 40 25
  1 35 10
>
> ps <- postStratify(des, strata=~h*p, population=pop)
> weights(ps)
[1]  3.333333 11.666667  3.333333 20.000000 25.000000
[6]  11.666667 20.000000 11.666667  3.333333

The documentation and Lumley's "survey book" both don't show how to do this and if it's possible at all.

A:

The documentation contains a small hint on how the names of the population vector for calibrate() should be formed: They are compared with the results of model.matrix(). The question remains how to derive a proper population vector from a table of totals like the one passed to postStratify().
I use a special call to model.matrix() to convert a totals table to a population vector. The main idea is to compute a model.matrix() from the totals table plus a Freq column, to scale the matrix contents by the Freq column and then to sum up column-wise. This results exactly in the population vector. Please see the complete example below for details.
> library(survey)

Attaching package: ‘survey’

The following object(s) are masked from ‘package:graphics’:

    dotchart

> df <- data.frame(id=c(1,1,1,2,2,3,4,5,5,6,6,6,7,7,7)
+                  , h=factor(c(1,1,1,0,0,1,0,1,1,0,0,0,0,0,0))
+                  , p=factor(c(1,0,1,0,1,0,0,0,1,1,0,1,1,0,0))
+                  , q=factor(c(0,0,1,1,1,0,1,1,1,0,0,1,1,1,0))
+                  )
> df$hp <- do.call(interaction, df[, c('h', 'p')])
    > df$hq <- do.call(interaction, df[, c('h', 'q')])
> df$pq <- do.call(interaction, df[, c('p', 'q')])
    > df$hpq <- do.call(interaction, df[, c('h', 'p', 'q')])
> df
   id h p q  hp  hq  pq   hpq
1   1 1 1 0 1.1 1.0 1.0 1.1.0
2   1 1 0 0 1.0 1.0 0.0 1.0.0
3   1 1 1 1 1.1 1.1 1.1 1.1.1
4   2 0 0 1 0.0 0.1 0.1 0.0.1
5   2 0 1 1 0.1 0.1 1.1 0.1.1
6   3 1 0 0 1.0 1.0 0.0 1.0.0
7   4 0 0 1 0.0 0.1 0.1 0.0.1
8   5 1 0 1 1.0 1.1 0.1 1.0.1
9   5 1 1 1 1.1 1.1 1.1 1.1.1
10  6 0 1 0 0.1 0.0 1.0 0.1.0
11  6 0 0 0 0.0 0.0 0.0 0.0.0
12  6 0 1 1 0.1 0.1 1.1 0.1.1
13  7 0 1 1 0.1 0.1 1.1 0.1.1
14  7 0 0 1 0.0 0.1 0.1 0.0.1
15  7 0 0 0 0.0 0.0 0.0 0.0.0
>
> des <- svydesign(id=~id, data=df)
Warning message:
In svydesign.default(id = ~id, data = df) :
  No weights or probabilities supplied, assuming equal probability
>
> pop <- data.frame(h=factor(c(0, 1, 0, 1, 0, 1, 0, 1)),
+                   p=factor(c(0, 0, 1, 1, 0, 0, 1, 1)),
+                   q=factor(c(0, 0, 0, 0, 1, 1, 1, 1)),
+                   Freq=c(40, 35, 25, 35, 45, 30, 30, 30))
> pop$hp <- do.call(interaction, pop[, c('h', 'p')])
    > pop$hq <- do.call(interaction, pop[, c('h', 'q')])
> pop$pq <- do.call(interaction, pop[, c('p', 'q')])
    > pop$hpq <- do.call(interaction, pop[, c('h', 'p', 'q')])
> pop
  h p q Freq  hp  hq  pq   hpq
1 0 0 0   40 0.0 0.0 0.0 0.0.0
2 1 0 0   35 1.0 1.0 0.0 1.0.0
3 0 1 0   25 0.1 0.0 1.0 0.1.0
4 1 1 0   35 1.1 1.0 1.0 1.1.0
5 0 0 1   45 0.0 0.1 0.1 0.0.1
6 1 0 1   30 1.0 1.1 0.1 1.0.1
7 0 1 1   30 0.1 0.1 1.1 0.1.1
8 1 1 1   30 1.1 1.1 1.1 1.1.1
>
> #fm <- '~hp+hq+pq'
> fm <- '~h:p+h:q+p:q'
> # Both options above seem to produce the same results
>
> (mm <- as.data.frame(model.matrix(as.formula(paste0(fm, '+Freq')), pop)))
  (Intercept) Freq h0:p0 h1:p0 h0:p1 h1:p1 h0:q1 h1:q1 p1:q1
1           1   40     1     0     0     0     0     0     0
2           1   35     0     1     0     0     0     0     0
3           1   25     0     0     1     0     0     0     0
4           1   35     0     0     0     1     0     0     0
5           1   45     1     0     0     0     1     0     0
6           1   30     0     1     0     0     0     1     0
7           1   30     0     0     1     0     1     0     1
8           1   30     0     0     0     1     0     1     1
> mm <- mm * mm$Freq
    > mm$Freq <- NULL
> (pop <- unlist(lapply(mm, sum)))
(Intercept)       h0:p0       h1:p0       h0:p1       h1:p1       h0:q1
        270          85          65          55          65          75
      h1:q1       p1:q1
         60          60
>
> cal <- NULL
> cal <- calibrate(des, formula=as.formula(fm), population=pop,
+                  calfun="raking")
Loading required package: MASS
> weights(cal)
        1         2         3         4         5         6         7         8
31.902369 19.048815 16.548815 16.032544  8.967456 19.048815 16.032544 26.902369
        9        10        11        12        13        14        15
16.548815 28.097631 18.451185  8.967456  8.967456 16.032544 18.451185
attr(,"eta")
           [,1]
[1,]  2.5320998
[2,]  0.3830288
[3,]  0.4149051
[4,]  0.8035854
[5,]  0.9305805
[6,] -0.1405080
[7,]  0.3452095
[8,] -1.0015752
> svytotal(~h, cal)
   total SE
h0   140  0
h1   130  0
> svytotal(~p, cal)
   total SE
p0   150  0
p1   120  0
> svytotal(~q, cal)
   total SE
q0   135  0
q1   135  0
> svytotal(~hp, cal)
      total SE
hp0.0    85  0
hp1.0    65  0
hp0.1    55  0
hp1.1    65  0
> svytotal(~hq, cal)
      total SE
hq0.0    65  0
hq1.0    70  0
hq0.1    75  0
hq1.1    60  0
> svytotal(~pq, cal)
      total SE
pq0.0    75  0
pq1.0    60  0
pq0.1    75  0
pq1.1    60  0
> svytotal(~hpq, cal)
          total     SE
hpq0.0.0 36.902 6.4914
hpq1.0.0 38.098 6.4914
hpq0.1.0 28.098 6.4914
hpq1.1.0 31.902 6.4914
hpq0.0.1 48.098 6.4914
hpq1.0.1 26.902 6.4914
hpq0.1.1 26.902 6.4914
hpq1.1.1 33.098 6.4914

(Just for the record: The R function interaction() recodes all combinations of given factors into one single factor.)


Q:

Angular2 components fail to communicate via observable in a service

I'm trying to make components send messages via a shared service, like in a cookbook's "Parent and children communicate via a service" recipe. I have a Sender component that calls a service's method, in which an event is fired. And there's a Receiver component, which's just listens to events.
The problem is the Receiver doesn't get an event. Here's the code:
import {bootstrap} from 'angular2/platform/browser'
import {Injectable, Component} from 'angular2/core';

import 'rxjs/Rx';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class TestService {
    private _subject = new Subject<any>();
    event$ = this._subject.asObservable();

    doFoo() {
        console.log('Doing foo hard...')
        this._subject.next('hey');
    }
}

@Component({
    selector: 'receiver-component',
    template: 'Value is {{ value }}',
    providers: [
        TestService
    ],
})
export class ReceiverComponent {
    private value: number = 'nope';

    constructor(private service: TestService) {
        this.service.event$.subscribe(data => this.value = data)
    }
}

@Component({
    selector: 'sender-component',
    template: '<button (click)="fireEvent()">Click me</button>',
    providers: [
        TestService
    ],
})
export class SenderComponent {
    constructor (private service: TestService) {}

    fireEvent() {
        this.service.doFoo()
    }
}

bootstrap(SenderComponent);
bootstrap(ReceiverComponent);

When I click the button, I see the debug message from TestService.doFoo(), so it gets executed. But the event message just doesn't get passed. Why?
Update: I'm using angular2@2.0.0-beta.7 and rxjs@5.0.0-beta.2.

A:

This it isn't a shared service. Each component gets it's own instance.
If you add the service to the providers list of the component, each component will get a new instance.
If you run bootstrap() twice, you create two distinct Angular applications which don't share anything. See the last lines of the code how to establish the connection anyway:
import {bootstrap} from 'angular2/platform/browser'
import {Injectable, Component, provide} from 'angular2/core';

import 'rxjs/Rx';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class TestService {
    private _subject = new Subject<any>();
    event$ = this._subject.asObservable();

    doFoo() {
        console.log('Doing foo hard...')
        this._subject.next('hey');
    }
}

@Component({
    selector: 'receiver-component',
    template: 'Value is {{ value }}',
//    providers: [
//        TestService
//    ],
})
export class ReceiverComponent {
    private value: number = 'nope';

    constructor(private service: TestService) {
        this.service.event$.subscribe(data => this.value = data)
    }
}

@Component({
    selector: 'sender-component',
    template: '<button (click)="fireEvent()">Click me</button>',
//    providers: [
//        TestService
//    ],
})
export class SenderComponent {
    constructor (private service: TestService) {}

    fireEvent() {
        this.service.doFoo()
    }
}

sharedService = new TestService();
bootstrap(SenderComponent, [provide(TestService, {useValue: sharedService})]);
bootstrap(ReceiverComponent, [provide(TestService, {useValue: sharedService})]);


Q:

Proving a simple assertion in Propositional Logic

I have to prove some Propositional Logic assertions.
Given this one: $\alpha \models \beta \Leftrightarrow (\alpha \Rightarrow \beta)$ is valid
Where $\models$ is entailment
The answer is: $\alpha \Rightarrow \beta$ holds in those models where $\beta$ holds or where $\neg\alpha$ holds. This is precisely the case if $\alpha \Rightarrow \beta$ is valid.
I don't understand this answer. Could someone clarify it for me. I don't know what holds means in this context. English is not my first language.
I know that a sentence to be valid needs to be True in all models. Also that $\alpha \models \beta \Leftrightarrow$ in every model in which $\alpha$ is true, $\beta$ is also true.
Thanks

A:

You can think of the phrase "[insert something here] holds" as "[that same something] is [insert property here]". More concretely, "holds" in this context is a sort of expression that refers to some thing "holding true" or always having the property of being true.
So, when we say $\alpha \Rightarrow \beta$ holds, we mean that $\alpha \Rightarrow \beta$ is in fact true.


Q:

Spring: How to use @RequestBody after reading inputStream

I'm having the issue described here but it's not clear to me how to address it.
The issue is that I have an AuthenticationProvider which has to read the body of the request. When my controller method wants to use that data via @RequestMapping, however, it's empty because the Provider has already read the inputStream.
Is there a way to obtain an inputReader from Request which supports mark/reset so my provider can simply roll the stream back to it's initial state after it does the authentication? It seems crazy that the default behavior of the filter is destructive modification of the request object.

A:

The Provider should be triggered only in specific cases, so it shouldn't affect your whole application. But if you need the body in the requests handled by the provider, then you still have a workaround:

implement a servlet Filter
wrap the request
in the wrapper cache the request body, and then override the getInputStream() method to return a ByteArrayInputStream with the cached request body. That way it can be read muiltiple times.

spring's AbstractRequestLoggingFilter does something similar and has an example wrapper, you can check it.


Q:

Mysterious behaviour of php

Below code works as expected. It adds 3 entries to the table 'keywords'.
<?php
include "config.php";
try{
    // $conn = new PDO(DBINFO,USER,PASS);
    // $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)";
    // $stmt = $conn->prepare($sql);
    // $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR);
    // $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
    // $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR);
    // $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR);
    // $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
    // $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR);
    // $stmt->execute();

    for($i=0; $i<3; $i++){
        $conn2 = new PDO(DBINFO,USER,PASS);
        $sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)";
        $stmt2 = $conn2->prepare($sql2);
        $a = 'asdfds';
        $stmt2->bindParam(':keyword', $a,PDO::PARAM_STR);
        $stmt2->bindParam(':confidence', $a, PDO::PARAM_STR);
        $stmt2->execute();
    }
}
catch(PDOException $pe){
    die("Could not connect to the database :".$pe->getMessage());
}
?>

However, when I run the below code (where I uncommented the first part), the entries get added 6 times to the 'keywords' table.
<?php
include "config.php";
try{
    $conn = new PDO(DBINFO,USER,PASS);
    $sql = "INSERT INTO projects (title,duration, startyear, description, tags,email) VALUES (:title,:duration, :startyear, :description, :tags,:email)";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':title', $_POST['title'],PDO::PARAM_STR);
    $stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
    $stmt->bindParam(':duration', $_POST['duration'], PDO::PARAM_STR);
    $stmt->bindParam(':startyear', $_POST['startyear'], PDO::PARAM_STR);
    $stmt->bindParam(':description', $_POST['description'], PDO::PARAM_STR);
    $stmt->bindParam(':tags', $_POST['tags'], PDO::PARAM_STR);
    $stmt->execute();

    for($i=0; $i<3; $i++){
        $conn2 = new PDO(DBINFO,USER,PASS);
        $sql2 = "INSERT INTO keywords (keyword,confidence) VALUES (:keyword,:confidence)";
        $stmt2 = $conn2->prepare($sql2);
        $a = 'asdfds';
        $stmt2->bindParam(':keyword', $a,PDO::PARAM_STR);
        $stmt2->bindParam(':confidence', $a, PDO::PARAM_STR);
        $stmt2->execute();
    }
}
catch(PDOException $pe){
    die("Could not connect to the database :".$pe->getMessage());
}
?>

I can't understand this. Any help?

A:

Why do you create 4 different connections to the same server and schema in the first place?
The loop creates connections and closes them automatically when the references to statements and connections are overwritten.
But the original connection from before the loop will stay open and is reused for the statements. If you create a third connection without closing it before the loop you'll end up with 9 entries.
So delete the references to connection objects if they are no longer needed (this includes associated statements).
Or better yet reuse connections instead of creating a new connection for every statement.


Q:

FTP Error 500 Illegal Port Command - PORT command sending different IP than source of request

The problem I'm experiencing is that I'm getting a "500 Illegal PORT command" Response from an FTP server when attempting to upload a file programmatically.
This program is a small c# application that connects to an FTP site and copies files to the default directory. This program has been in production for several years and I am confident the code itself works just fine. I've also tested the application by connecting to my own FTP site using the same application and it works. Passive mode does not seem to be an option.
When attempting to connect to our partner's FTP site, the program runs as expected until the FTP put command is executed. I have noticed when running Wireshark that the source IP of my Request is different from the IP address the PORT command is sending. I have uploaded an image of a capture here (all sensitive information has been removed using my amazing photoshop skills):
.
I have contacted the owner of the FTP site where we are attempting to transfer the files and they have opened their firewall for our new Static IP address. I can connect to their site using FTP clients from machines on both of the LAN IP's, but those PORT commands are always sent using the same LAN IP as the source of the request. I have also tried using ftp.exe from the server where the program resides, and it is successful (but the PORT command uses the same IP as the source).
So I guess the big question is how can I control what IP address the PORT command uses? Or, if I can't control it, how is the IP address and PORT determined by the ftp program?

A:

It turns out the answer really has to do with the FTP library I was using. I thought for sure this wasn't a coding issue, but after I sniffed around how the library is creating the request, I think I have found the answer.
Here is the relevant section using ILSpy (I put space around the most important line):
private Socket CreateDataSocketActive()
{
    Socket socket = new Socket(2, 1, 6);
    IPHostEntry iPHostEntry = Dns.Resolve(Dns.GetHostName());

    IPEndPoint iPEndPoint = new IPEndPoint(iPHostEntry.get_AddressList()[0], 0);

    socket.Bind(iPEndPoint);
    socket.Listen(5);
    int port = ((IPEndPoint)socket.get_LocalEndPoint()).get_Port();
    IPAddress address = ((IPEndPoint)socket.get_LocalEndPoint()).get_Address();
    this.SetDataPort((IPEndPoint)socket.get_LocalEndPoint());
    return socket;
}

It looks like the library is creating the IP endpoint by simply grabbing the first address in the list of available IP addresses. For most solutions, that is probably acceptable, but because I have multiple NICs on my server, it doesn't work for me.
I know by using FTP.exe that the server will accept connections from both of my LAN IP subnets so long as the PORT command issued is issued using the same LAN IP address as the source of the request.
I'm guessing there's some kind of validation done by the FTP server that compares the two addresses to verify they're the same. Otherwise, I could theoretically transfer a file to some other device on a completely different network once I logged into the FTP site.
Now I've just got to figure out a workaround, but that should just be a matter of finding a new library or rolling my own. If it helps anyone else who might have had the same issue, the library I was using was com.enterprisedt.net.ftp.


Q:

Should you worry about fake accounts/logins on a website?

I'm specifically thinking about the BugMeNot service, which provides user name and password combos to a good number of sites. Now, I realize that pay-for-content sites might be worried about this (and I would suspect that most watch for shared accounts), but how about other sites? Should administrators be on the lookout for these accounts? Should web developers do anything differently to take them into account (and perhaps prevent their use)?

A:

I think it depends on the aim of your site. If usage analytics are all-important, then this is something you'd have to watch out for. If advertising is your only revenue stream, then does it really matter which username someone uses?
Probably the best way to discourage use of bugmenot accounts is to make it worthwhile to have an actual account. E.g.: No one would use that here, since we all want rep and a profile, or if you're sending out useful emails, people want to receive them.

A:

Ask yourself the question "Why do we require users to register to access my site?"  Once you have business reason for this requirement, then you can try to work out what the effect of having some part of that bypassed by suspect account information.
Work on the basis that at least 10 to 15 percent of account information will be rubbish - and if people using the site can't see any benefit to them personally for registering, and if the registration process is even remotely tedious or an imposition, then accept that you will be either driving more potential visitors away, or increasing your "crap to useful information" ratio.

A:

Not make registration mandatory to read something? i.e. Ask people to register when you are providing some functionality for them that 'saves' some settings, data, etc. I would imagine site like stackoverflow gets less fake registrations (reading questions doesn't require an account) than say New York Times, where you need to have an account to read articles.
If that is not upto your control, you may consider removing dormant accounts. i.e. Removing accounts after a certain amount of inactivity.


Q:

CQ5, dynamically set 'defaultValue' in component's dialog using extjs?

I have a selection box in my component's dialog, with four options:

off
default
addon
overwrite

In the dialog, I want dynamically set the defaultValue property to 'off' or 'default' based on whether the URL path contains a certain characters or not.  Is this possible?
Here is the dialog.xml snippet with my attempted listener to do this:
<extra_meta_description_tag_mode
    jcr:primaryType="cq:Widget"
    defaultValue=""
    fieldLabel="SEO Description Usage"
    name="./extraMetaDescriptionTagMode"
    type="select"
    xtype="selection">
        <listeners
            jcr:primaryType="nt:unstructured"
            defaultValue="function(url) {
                url.contain("en_gb/news") ? return "default" : return "off";
            }"/>
        <options jcr:primaryType="cq:WidgetCollection">
            <off
                jcr:primaryType="nt:unstructured"
                text="Off"
                value="off"/>
            <default
                jcr:primaryType="nt:unstructured"
                text="Append pre-set text"
                value="default"/>
            <addon
                jcr:primaryType="nt:unstructured"
                text="Append input text"
                value="addon"/>
            <over_write
                jcr:primaryType="nt:unstructured"
                text="Overwrite"
                value="overwrite"/>
        </options>
</extra_meta_description_tag_mode>

A:

The listener can only have values of events, defaultValue is not one. You can use the loadContent event,which is fired when the dialog loads. CQ.WCM.getPagePath() will give the current page path:
<listeners
    jcr:primaryType="nt:unstructured"
    loadcontent="function(selection,record,path) {
        var currentPath = CQ.WCM.getPagePath();
        if(currentPath.indexOf('en_gb/news')!=-1)
        {
            selection.setValue('default');
        } else {
            selection.setValue('off');
        }"/>

This will reset the value every time the dialog loads, so you will have add conditions to prevent it if the users have overridden the default value.