Q:

include of this file does not work

When I try to include this file in any of my other pages it doesn't work. Any ideas why? file structure:
index.php
       (FOLDER - core)      init.php
       (FOLDER - functions) sanitise.php
       (FOLDER - browse)    blog.php , ecommerce.php...
       (FOLDER - includes)  header.php

The problem I'm having is when I try to include core/init.php in any of my files. Do you spot any mistakes that I've missed or anything?
Maybe its possible to include core/init.php in my includes/header.php file so that when I call includes/header.php in lets say browse/blog.php, core/init.php gets included too. I want init.php to be included in all my web pages.
Init.php code:
    <?php
session_start();

$GLOBALS['config'] = array(
    'mysql' => array(
        'host' => 'localhost',
        'username' => 'root',
        'password' => 'root',
        'db' => 'webAwwards'
    ),
    'remember' => array(
        'cookie_name' => 'hash',
        'cookie_expire' => 604800
    ),
    'session' => array(
        'session_name' => 'user'

    )
);

spl_autoload_register(function($class) {
        require_once 'classes/' . $class . '.php';
    });

require_once '/functions/sanitise.php';

?>

My header.php file code:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Web Awwards | Web Gallery | Submit your site</title>
    <meta name="description" content="">
    <meta name="author" content="">

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="stylesheet" type="text/css" href="../css/base.css">
    <link rel="stylesheet" type="text/css" href="../css/skeleton.css">
    <link rel="stylesheet" type="text/css" href="../css/layout.css">
    <link rel="stylesheet" type="text/css" href="../css/styles.css">
    <link rel="stylesheet" type="text/css" href="../css/menu.css">
    <link rel="stylesheet" type="text/css" href="../css/submission.css">

    <link rel="shortcut icon" href="images/favicon.ico">
    <link rel="apple-touch-icon" href="images/apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">

WebAwwards

Home

Browse

Blog

E-Commerce

Corporate

Portfolio

Minimalist

Other

Register/ Login

Submit Your Site

browse/blog.php code:
<?php
    require_once('../core/init.php');
    require ('../includes/header.php');
?>

 Web Name

 Designed By: Tautvydas Slegaitis

    <h7> Designers url </h7>

 Vote for my site

         Love it
         Nope, Not for me

File does not execute and error is displayed all the time.

Warning: require_once(../core/init.php): failed to open stream: No such file or directory in - on line 2 Fatal error: require_once(): Failed opening required '../core/init.php' (include_path='.:') in - on line 2 "

A:

You are including sanitise.php in wrong way.
/functions/sanitise.php will search for functions folder in root directory.
You should call it as ../functions/sanitise.php.


Q:

get clicked item from listview

I've got a problem. Before modification in my XML file, my listview was able to work perfectly. But now, after some modifications in xml, its not working properly.
My listview is custom. So, i've created separate xml to render every single row in the listview.
My single row.xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:id="@+id/relativeLayoutSingleRowManageAddictions"
    android:layout_height="40dp"
    android:background="@drawable/box_midbg" >

    <TextView
        android:id="@+id/textViewSingleRowManageAddictions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="17dp"
        android:text="TextView"
        android:textSize="20dp"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/imageViewSingleRowManageAddictions"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="18dp"
        android:src="@drawable/listing_arrow" />

</RelativeLayout>

My main.xml code where listview resides:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_bg_edited" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        style="@style/top_bar_style" >

        <ImageView
            android:id="@+id/imageViewMAnageAddictionsBack"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:src="@drawable/back_arrow"
            android:clickable="true" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/header_style"
            android:text="Manage Addictions" />

        <ImageView
            android:id="@+id/imageViewManageAddictionsAdd"
            android:layout_width="25dp"
            android:layout_height="20dp"
            android:layout_marginRight="3dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/plus_nav"
            android:clickable="true" />

    </RelativeLayout>

    <ListView
        android:id="@+id/listViewManageAddictions"
        android:layout_width="290dp"
        android:layout_height="fill_parent"
        android:layout_below="@+id/relativeLayout1"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginTop="12dp"
        android:divider="@android:color/transparent"
        android:dividerHeight="2dp" />

</RelativeLayout>

And my java code for it:
package com.addictioncounterapp;

import java.util.ArrayList;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ManageAddictionList extends Activity {
  ImageView iv_manage_addictions_back, iv_manage_addictions_add;
  ListView listview;
  ArrayList < String > arraylist_manage_addiction;
  ArrayAdapter < String > arrayadapter_manage_addiction;
  SQLiteDatabase database;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manage_addiction_list);

    loaddatabase();

    iv_manage_addictions_back = (ImageView) findViewById(R.id.imageViewMAnageAddictionsBack);
    iv_manage_addictions_back.setClickable(true);
    iv_manage_addictions_back.setOnClickListener(new OnClickListener() {@Override
      public void onClick(View v) {
        startActivity(new Intent(ManageAddictionList.this, Settings.class));
      }
    });

    iv_manage_addictions_add = (ImageView) findViewById(R.id.imageViewManageAddictionsAdd);
    iv_manage_addictions_add.setClickable(true);
    iv_manage_addictions_add.setOnClickListener(new OnClickListener() {@Override
      public void onClick(View v) {
        Intent intent = new Intent(ManageAddictionList.this, MainActivity.class);
        intent.putExtra("name", "");
        intent.putExtra("unit", "");
        intent.putExtra("attribute", "");
        intent.putExtra("limit", "");
        intent.putExtra("operation", "Add Addiction");
        startActivity(intent);
      }
    });

    arraylist_manage_addiction = new ArrayList < String > ();
    manageList();
    listview = (ListView) findViewById(R.id.listViewManageAddictions);

    if (arraylist_manage_addiction.isEmpty()) Toast.makeText(getBaseContext(), "No Addictions found to manage. Click on 'add' button to create new Addiction.", Toast.LENGTH_SHORT)
      .show();
    else listview.setAdapter(arrayadapter_manage_addiction);

    listview.setOnItemClickListener(new OnItemClickListener() {@Override
      public void onItemClick(AdapterView <? > arg0, View arg1, int arg2, long arg3) {
        String name = null, attribute = null, unit = null, limit = null;

        View parentView = (View) arg0.getParent();
        name = ((TextView) parentView.findViewById(R.id.textViewSingleRowManageAddictions))
          .getText() + "";

        Toast.makeText(getBaseContext(), name, Toast.LENGTH_SHORT)
          .show();

        int cat_id = 0;

        //--------Fetching cat_id through name from the list--------

        Cursor cursor;

        cursor = database.query("category", new String[] {
          "cat_id"
        }, new String("cat_name=?"), new String[] {
          name
        }, null, null, null);

        if (cursor.getCount() > 0) {
          while (cursor.moveToNext())
          cat_id = cursor.getInt(0);
          cursor.close();
        }

        //--------Fetching unit, attribute, limit through cat_id from the list--------

        cursor = database.query("category_attribute", new String[] {
          "cat_attribute_name", "cat_attribute_unit", "cat_limit"
        }, new String("cat_id=?"), new String[] {
          cat_id + ""
        }, null, null, null);

        if (cursor.getCount() > 0) {
          while (cursor.moveToNext()) {
            attribute = cursor.getString(0);
            unit = cursor.getString(1);
            limit = cursor.getString(2);
          }
          cursor.close();
        }

        Intent intent = new Intent(ManageAddictionList.this, MainActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("unit", unit);
        intent.putExtra("attribute", attribute);
        intent.putExtra("limit", limit);
        intent.putExtra("cat_id", cat_id);
        intent.putExtra("operation", "Edit Addiction");
        startActivity(intent);
      }
    });
  }

  private void loaddatabase() {
    database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READONLY, null);
  }

  private void manageList() {
    String[] columns = {
      "cat_name"
    };
    Cursor cursor;

    cursor = database.query("category", columns, null, null, null, null, null);

    if (cursor.getCount() > 0) {
      while (cursor.moveToNext())
      arraylist_manage_addiction.add(cursor.getString(0));
      cursor.close();
    }

    arrayadapter_manage_addiction = new ArrayAdapter < String > (this, R.layout.single_row_manage_addictions, R.id.textViewSingleRowManageAddictions, arraylist_manage_addiction);
  }
}

The main bug behind this is that, when I get the name using this:
View parentView = (View) arg0.getParent();
name = ((TextView) parentView.findViewById(R.id.textViewSingleRowManageAddictions)).getText()+"";

the listview of any record, it gives the name of first record only.
For example, if my first row has textview named "Gaming", when i click on any row, (for debugging purpose, i used Toast.makeText(...)) it Toasts "Gaming" as the name for every record in the listview, though every record in the listview is unique. Please help me out with this.

A:

lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // selected item
        String selected = ((TextView) view.findViewById(R.id.your_textView_item_id)).getText().toString();

        Toast toast = Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT);
        toast.show();
    }
});

A:

listView = (ListView)view.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String selected = ((TextView) view.findViewById(R.id.complaint)).getText().toString();
        Toast.makeText(context,selected,Toast.LENGTH_LONG).show();
    }
});


Q:

An unexpected error occurred during response processing (Name: ECN) WP7

I'm developing an app on WP7 and decided to add a Microsoft Advertisement to my application.
I added the control and setup the width/height, inserted my app id and ad unit id and published it to my phone. However I keep getting the following error:

An unexpected error occurred during response processing (Name: ECN)

I don't receive this error when use I "test_client" for app id and "Image300_50" for ad unit id.
Does anyone have any clues as to what the reason for this error may be?

A:

I found this official statement from Microsoft about that error, and it appears to be that there aren't any ads to match your app.

This error is only visible to app developers that are debugging the
  use of the Microsoft Ad Control in a development environment.  As of
  February 24, 2011, this scenario will now return the error “No ad
  available”.  In production the ad control would simply not display an
  ad if there is an error or if there is no ad to display.  There is no
  user facing impact.  Please reference the Monetization Best Practices
  document (attached) to review the best practices you can incorporate
  to ensure you are maximizing the possibility of Advertisers desiring
  to reach your application audience.

I also found that when I was getting the error, I was using the wrong width and height for the control, and fixing that got the ads to appear.


Q:

C# WPF Screenshot Application -- Handling Drawing on a Canvas Though Mouse Events

I'm working on making a screenshot program in WPF. What I don't understand is how I should mouse events. All of my mouse events are handled in the code-behind, which works great, but I want to convert my project to MVVM-style. Here is all of my ScreenshotTab code, which is the usercontrol which hosts the screenshot (it's actually designed to be placed into a tabcontrol tabitem):
public partial class ScreenshotTab : UserControl
{
    public ScreenshotTab()
    {
        InitializeComponent();
    }

    public ScreenshotTab(BitmapImage screenshot, Window window)
    {
        InitializeComponent();
        imgControl.Source = screenshot;
        imgControl.MaxWidth = screenshot.Width;
        imgControl.MaxHeight = screenshot.Height;
        canvas.Height = screenshot.Height;
        canvas.MinHeight = screenshot.Height;
        canvas.MaxHeight = screenshot.Height;
        canvas.Width = screenshot.Width;
        canvas.MinWidth = screenshot.Width;
        canvas.MaxWidth = screenshot.Width;
        mainWindow = window as MainWindow;
    }

    public bool isSaved
    {
        get;
        set;
    }

    public BitmapImage Screenshot
    {
        get
        {
            if (imgControl.Source is BitmapImage)
            {
                return imgControl.Source as BitmapImage;
            }
            else
            {
                return null;
            }
        }
    }

    // Listed in the order they are needed in the logic flow inside the event handlers.
    private MainWindow mainWindow;
    private Ellipse circle;
    private Polyline polyLine;
    private Point startPoint;
    private Point endPoint;
    private Line line;
    private Rectangle rectangle;
    private Point topLeft;
    // I probably don't need a bool.
    private bool isDrawing;

    private void imgControl_MouseDown(object sender, MouseButtonEventArgs e)
    {
        // MessageBox.Show("Mouse down event is working...");
        // MessageBox.Show("mainwindow.toolselected = " + mainWindow.toolSelected.ToString());
        // Sets the starting point of the line, which doesn't change
        // as the user moves their mouse.

        // Turns on a flag that represents that we are drawing when on.
        isDrawing = true;

        switch (mainWindow.toolSelected)
        {
            case DrawingTool.FreeDraw:
                polyLine = new Polyline();
                SetStrokeProperties(polyLine);
                polyLine.Points.Add(e.GetPosition(canvas));
                canvas.Children.Add(polyLine);
                break;
            case DrawingTool.Line:
                line = new Line();
                SetStrokeProperties(line);
                line.X1 = e.GetPosition(canvas).X;
                line.Y1 = e.GetPosition(canvas).Y;
                line.X2 = e.GetPosition(canvas).X;
                line.Y2 = e.GetPosition(canvas).Y;
                canvas.Children.Add(line);
                break;
            case DrawingTool.Rectangle:
                rectangle = new Rectangle();
                SetStrokeProperties(rectangle);
                startPoint = e.GetPosition(this);
                endPoint = e.GetPosition(this);
                Canvas.SetLeft(rectangle, startPoint.X);
                Canvas.SetTop(rectangle, startPoint.X);
                canvas.Children.Add(rectangle);
                break;
            case DrawingTool.Circle:
                circle = new Ellipse();
                SetStrokeProperties(circle);
                startPoint = e.GetPosition(this);
                endPoint = e.GetPosition(this);
                Canvas.SetLeft(circle, startPoint.X);
                Canvas.SetTop(circle, startPoint.X);
                canvas.Children.Add(circle);
                break;
            case DrawingTool.Eraser:

                break;
            default:
                break;
        }
    }

    private void SetStrokeProperties(Shape shape)
    {
        shape.Stroke = new SolidColorBrush(mainWindow.color);
        shape.StrokeThickness = 3;
    }

    // This is our eraser event.
    // It simply removes the element from the object when the tool selected
    // is the eraser tool and we have the mouse down.
    private void OnMouseOver(object sender, MouseEventArgs e)
    {
        // MessageBox.Show("Yay, mouse over event called...");
        if (isDrawing && (mainWindow.toolSelected == DrawingTool.Eraser))
        {
            canvas.Children.Remove(sender as UIElement);
        }
    }

    private void imgControl_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDrawing)
        {
            switch (mainWindow.toolSelected)
            {
                case DrawingTool.FreeDraw:
                    polyLine.Points.Add(e.GetPosition(canvas));
                    break;
                case DrawingTool.Line:
                    line.X2 = e.GetPosition(canvas).X;
                    line.Y2 = e.GetPosition(canvas).Y;
                    break;
                case DrawingTool.Rectangle:
                    endPoint = e.GetPosition(this);
                    rectangle.Width = Math.Abs(endPoint.X - startPoint.X);
                    rectangle.Height = Math.Abs(endPoint.Y - startPoint.Y);
                    // down and to the right.
                    if ((endPoint.X >= startPoint.X) && (endPoint.Y >= startPoint.Y))
                    {
                        // In this case, the start point is the top left point of the rectangle.
                        topLeft.X = startPoint.X;
                        topLeft.Y = startPoint.Y;
                        Canvas.SetLeft(rectangle, topLeft.X);
                        Canvas.SetTop(rectangle, topLeft.Y);
                    }
                    // up and to the right.
                    else if ((endPoint.X >= startPoint.X) && (endPoint.Y <= startPoint.Y))
                    {
                        topLeft.X = endPoint.X - rectangle.Width;
                        topLeft.Y = endPoint.Y;
                        Canvas.SetLeft(rectangle, topLeft.X);
                        Canvas.SetTop(rectangle, topLeft.Y);
                    }
                    // up and to the left...
                    else if ((endPoint.X <= startPoint.X) && (endPoint.Y <= startPoint.Y))
                    {
                        topLeft.X = endPoint.X;
                        topLeft.Y = endPoint.Y;
                        Canvas.SetLeft(rectangle, topLeft.X);
                        Canvas.SetTop(rectangle, topLeft.Y);
                    }
                    // down to the left...
                    else if ((endPoint.X <= startPoint.X) && (endPoint.Y >= startPoint.Y))
                    {
                        topLeft.X = startPoint.X - rectangle.Width;
                        topLeft.Y = endPoint.Y - rectangle.Height;
                        Canvas.SetLeft(rectangle, topLeft.X);
                        Canvas.SetTop(rectangle, topLeft.Y);
                    }
                    break;
                case DrawingTool.Circle:
                    endPoint = e.GetPosition(this);
                    circle.Width = Math.Abs(endPoint.X - startPoint.X);
                    circle.Height = Math.Abs(endPoint.Y - startPoint.Y);
                    // down and to the right.
                    if ((endPoint.X >= startPoint.X) && (endPoint.Y >= startPoint.Y))
                    {
                        // In this case, the start point is the top left point of the rectangle.
                        topLeft.X = startPoint.X;
                        topLeft.Y = startPoint.Y;
                        Canvas.SetLeft(circle, topLeft.X);
                        Canvas.SetTop(circle, topLeft.Y);
                    }
                    // up and to the right.
                    else if ((endPoint.X >= startPoint.X) && (endPoint.Y <= startPoint.Y))
                    {
                        topLeft.X = endPoint.X - circle.Width;
                        topLeft.Y = endPoint.Y;
                        Canvas.SetLeft(circle, topLeft.X);
                        Canvas.SetTop(circle, topLeft.Y);
                    }
                    // up and to the left...
                    else if ((endPoint.X <= startPoint.X) && (endPoint.Y <= startPoint.Y))
                    {
                        topLeft.X = endPoint.X;
                        topLeft.Y = endPoint.Y;
                        Canvas.SetLeft(circle, topLeft.X);
                        Canvas.SetTop(circle, topLeft.Y);
                    }
                    // down to the left...
                    else if ((endPoint.X <= startPoint.X) && (endPoint.Y >= startPoint.Y))
                    {
                        topLeft.X = startPoint.X - circle.Width;
                        topLeft.Y = endPoint.Y - circle.Height;
                        Canvas.SetLeft(circle, topLeft.X);
                        Canvas.SetTop(circle, topLeft.Y);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void imgControl_MouseUp(object sender, MouseButtonEventArgs e)
    {
        isSaved = false;
        switch (mainWindow.toolSelected)
        {
            case (DrawingTool.FreeDraw):
                polyLine.MouseEnter += OnMouseOver;
                break;
            case (DrawingTool.Line):
                line.MouseEnter += OnMouseOver;
                break;
            case (DrawingTool.Rectangle):
                rectangle.MouseEnter += OnMouseOver;
                break;
            case (DrawingTool.Circle):
                circle.MouseEnter += OnMouseOver;
                break;
        }
        isDrawing = false;
        // MessageBox.Show("Mouse up event fired...");
    }
}

Obviously, that is quite a mess of code to handle, especially if I decide to add more shapes to draw in the future. So how would I go about setting up this up in MVVM if I want the user to be able to draw different kinds of shapes? Thanks for taking the time to look over this.

A:

I handle this with an interface to a class that my view model can interact with:
public interface IMouseArgs
{
    Point Pos { get; }
    void Capture();
    void Release();
    bool Handled { get; set; }
    ... lots of other stuff
}

So basically whenever a mouse event or drag-n-drop operation occurs my view layer creates an object that implements this interface and passes it to the view model. If the view model decides to Capture or Release then mouse (e.g. a drag operation) then there are functions for it to request that. Similarly, it can set the Handled flag to indicate to the view that it is handling the mouse now (so that the view doesn't bubble the message up to parent controls in the view hierarchy.
As for the view, I use an interaction trigger to convert from the mouse events to the view model command handlers:
<SomeControl>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDown">
            <cmd:EventToCommand Command="{Binding MouseDownCommand}"
                PassEventArgsToCommand="True"
                EventArgsConverter="{StaticResource ClickConverter}"
                EventArgsConverterParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:SomeParentWindow}}"/>
        </i:EventTrigger>

Again, this is a simplified example, but shows the general idea. You could just do only the cmd:EventToCommand and PassEventArgsToCommand="True", but then your view model will receive the Windows data objects associated with the event (which isn't good SOC and means your view model is now forced to reference the Windows libraries). Specifying an EventArgsConverter, with optional EventArgsConverterParameter, means you can write a converter in the view to accept the event arg and convert it into something that implements IMouseArgs.
Sounds a bit complex, but it allows for very complex mouse interactions (drags, resizes, drag-n-drop etc) and is fully unit-testable, all while maintaining complete separation between your view model and view layers.


Q:

Implications of increasing MAX_NUM_COOKIES

Magento 2 allows 50 cookies per domain.
This limit is enforced by Magento\Framework\Stdlib\Cookie\PhpCookieManager::MAX_NUM_COOKIES.
What are the implications of increasing that value?
I've read how to change constants of class in Magento\Framwork? and the accepted answer states

... incompatibility with several more or less outdated browsers, depending on much you increase it.
  Especially IE 11 and lower have the 50 Cookie per domain limit and still a relevant market share.

But I don't exactly understand what would happen on IE11 and lower.
Does this mean that the website will not function properly or the cookies that come in from 50 upwards don't get set? Or anything else?
If I don't care how the website behaves on IE, is it safe to increase this number?

A:

Browser will just automaticlly discard older cookies.
Ref:
https://support.microsoft.com/en-us/help/941495/internet-explorer-increases-the-per-domain-cookie-limit-from-20-to-50


Q:

How to use the "classes" parameter of JavaCompiler.getTask()?

I'm trying to understand JavaCompiler.getTask(). I understand all the parameters except for the second to last one called classes. The Javadoc read:

class names (for annotation processing), null means no class names

but I don't understand what they mean. I found plenty of websites referring to JavaCompiler online, but none of them explain this parameter. Any ideas?

A:

I believe this can be used when you want to run annotation processors on binaries. The classes would be the types you want to process.
Demo code:
public class MyProcessor extends AbstractProcessor {

  public static @interface X { String value(); }

  @X("Hello") public static class Y {}

  @Override public boolean process(Set<? extends TypeElement> annotations,
      RoundEnvironment roundEnv) {
    for (Element element : roundEnv.getRootElements()) {
      X x = element.getAnnotation(X.class);
      if (x != null) System.out.println(x.value());
    }
    return true;
  }

  @Override public Set<String> getSupportedAnnotationTypes() {
    return new HashSet<String>(Arrays.asList(X.class.getCanonicalName()));
  }

  @Override public SourceVersion getSupportedSourceVersion() {
    return SourceVersion.RELEASE_6;
  }

  public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<String> classes = Arrays.asList(Y.class.getCanonicalName());
    List<String> options = Arrays.asList("-processor", MyProcessor.class
        .getCanonicalName());
    CompilationTask task = compiler.getTask(null, null, null, options, classes,
        null);
    task.call();
  }
}

The above code prints out "Hello".


Q:

C# Return true if string is different from any of the string in a list of strings using LINQ

How do I achieve the same result as code below using LINQ?
What it do is if a string is different from any of the string in a list of strings, it will return true.
public static bool MasterPlantDifferentFromDetailPlant(string mrNumber)
{
    string masterPlant = t_MT_MTInfo.GetMaterialRequestPlant(mrNumber);
    List<string> detailPlants = t_MT_MTItem.GetPlants(mrNumber);
    bool differentPlant = false;
    foreach (string plant in detailPlants)
    {
        if (string.Compare(masterPlant.Trim(), plant.Trim(), StringComparison.OrdinalIgnoreCase) != 0)
        {
            differentPlant = true;
            break;
        }
    }
    return differentPlant;
}

A:

detailPlants.Any(p => string.Compare(masterPlant.Trim(), p.Trim(), StringComparison.OrdinalIgnoreCase) != 0)


Q:

What does lisp "list" function/keyword do?

I've seen it in An Introduction to Programming in Emacs Elisp, section 4.4.1:
(interactive
  (list (read-buffer
    "Append to buffer: "
    (other-buffer (current-buffer) t))
    (region-beginning)
    (region-end)))

It's surprisingly hard to Google what "list" means in lisp, because every page is a hit. I'm guessing it just makes a list of its arguments, in which case, why is it better or clearer to use than just making a list "manually" with another set of parentheses?

A:

That's because you cannot just use "another set of parentheses" to make a list.
Here's an expression that creates a list containing the numbers 1, 2, 3, 4.
(list 1 2 3 4)

However, you cannot use (1 2 3 4) or even ((1 2 3 4)) to express that.


Q:

Harry Potter FanFiction ID - Harry meets Rowena Ravenclaw's familiar, has to wait for the rest of the founders familiars to find him

I'm looking for a certain Harry Potter fanfic that's been bugging me for months now. I can't remember a great deal, and what I can is so similar to so many other fanfics that Google is no help. I'll bullet point what I can remember below.

Harry meets Rowena Ravenclaw's familiar, which was either a female eagle or a raven. The familiar is the guardian of Rowena's hidden library and decided Harry's level of access to texts. The bird tells him that Godric's familiar (a lion that I am almost positive Harry can wear as a tattoo or item on his body) and Helga's (a huge female badger which I'm positive ended up being in the Room of Requirements the whole time living in a tree and revealed herself to help cure an illness) are aware of him and will make themselves known in time. There was some element of him being "chosen" by them.
Harry had already killed Slytherin’s familiar in the Chamber based on a conversation I remember him having with Ravenclaw’s familiar, so this story began post Chamber of Secrets (this may be wrong as Slytherin’s familiar might have been a different basilisk, not the one in the chamber).
Very loosely I recall that Harry may have stumbled onto some hidden space of Ravenclaw’s in the Castle which led him into initial contact with her familiar.
Dumbledore has been siphoning power from Hogwarts's wards. Harry follows him to a tower and confronts him during this act. I Roughly remember Dumbledore is removed from Hogwarts and returns with Ministry Aurors, etc.
Dumbledore practically destroyed the original wards around Hogwarts by using the instruments from his office to carve slices out of them essentially, but Slytherin had designed a secondary ward scheme which Harry activates. This makes me think there was a heartstone or Ward stone scene but it’s to fuzzy.
There is a tower that is for Harry as an heir to the founders or founders chosen whatever he's called. Dumbledore managed to find it at one point and shattered the guardian status of the founders familiar as I recall there’s a scene where Harry rebuilds this.
One particular scene involved Rowena's familiar discovering the diadem was a Horcrux and going absolutely batshit. I remember they used Magik with the K spelling fairly often.
I vaguely recall the familiars had some sort of shape shifting ability, or were something other than the animals whose forms they assumed as Rowena and Godric's familiars had a romantic past of sorts they were discussing telling Harry about in one scene. Also Ravenclaws familiar become the Transfiguration teacher after McGonagall become Headmistress and she had a human female form.
There is a close relationship between Harry and Severus but it's not slash and I can't remember if it's father/son, or simply professor/student. Based on another comment Harry and Draco begin some sort of relationship but I can’t recall the details e.g. Veela.

I know it's not a lot to go on but this has been tormenting me and I’ve wracked through about a hundred pages on FanFiction.net trying to find it. The title was something completely ubiquitous as I remember not expecting much based on it and being completely engrossed and thinking it should have a better name. It was a relatively lengthy fanfic, so at least 100k words but possibly much more and, it was incomplete on my last read. I am 97% certain this was on FF.net but I have read the odd story on Archive of Our Own, so it could be there.

A:

I found a fanfiction that fits some of the details mentioned here, but doesn't fit many of the others. I'm posting it as an answer in case you may have misremembered some details, or combined two (or more) stories. I will address your bullets one by one, noting where the details match and where they don't match. The story is The Dark Phoenix by Lordstar016.

Harry meets Rowena Ravenclaw's familiar, which was either a female
eagle or a raven. The familiar is the guardian of Rowena's hidden
library and decided Harry's level of access to texts. The bird tells
him that Godric's familiar (a lion that I am almost positive Harry
can wear as a tattoo or item on his body) and Helga's (a huge female
badger which I'm positive ended up being in the Room of Requirements
the whole time living in a tree and revealed herself to help cure an
illness) are aware of him and will make themselves known in time.
There was some element of him being "chosen" by them.
Harry does meet Ravenclaw's familiar, it is part raven and part eagle, and can loosely be considered the guardian of Ravenclaw's library:
Chapter 5

The trio entered the right hall and entered a HUGE library. Books were everywhere and many many scrolls and other items that held knowledge. It was bigger than the main library in the school.

Suddenly a large black bird flew down towards Harry. Harry got a good look at the bird.
It's wingspan was about the size of Gondor's body and its body was pretty thing. It was black with silver tints on its feathers. It was a female and had grey eyes and a sharp beak. It looked like a overgrown Raven but it had the talons of a eagle and the speed of a hawk. It looked majestic as hell and it landed right in front of him. He was only 1 inch smaller than it. The creature Harry knew was called a Birvan a large mixture of several speices of birds.

"You must be Rowena Ravenclaw's familiar am I right?" asked Harry.
The bird nodded.
"Yes your correct sire I am Ravana." the bird said.

"Of course this is The Study of Wisdom Rowena Ravenclaw's secret chamber." Ravana said.

However, there is no mention of the bird deciding Harry's level of access to texts. In fact, in the rest of the story Harry never even uses this library.
Gryffindor's familiar is also in the story, and while it is a griffin rather than a lion, it is described as a lion (my emphasis):
Chapter 5

Harry turned his head and by the main entrance to the room they were in was a giant beastly looking lion thing. It was a male and had long sharp teeth about the size of small swords and giant muscular legs and paws with long claws on the end of them. Its tail was thin but flexible looking and its mane was dark red. Its eyes were sky blue and its fur was golden. The only thing that didn't make it a over sized lion was the fact that it had some feathers on its back and legs a bit and had giant eagle wings. It was about 30 feet tall. Harry was up to its chin however its width was larger than him big time and it looked like it could swallow half of Harry in one gulp. Harry knew what this creature was. It was a Griffon and it looked like it was ready to kill.

"How... how can I understand you?" Harry asked.
"Because Young Harry he is Godric Gryffindor's familiar as I am Salazar Slytherin's familiar." Sarota hissed out.

Similarly, Hufflepuff's familiar is a "huge female badger":
Chapter 5

It looked like a oversized honey badger but yellow and black fur and large long body. It was a female and as shorter than Harry when walking on all fours but was 1 inch taller when standing on two legs.

"Hello you must be Helga Hufflepuff's familiar whats your name?" asked Harry.
"My name is Halen dear." she said in a kind tone.

However, it was not Ravenclaw's familiar that told Harry about Hufflepuff's and Gryffindor's familiars; rather it was Slytherin's familiar that showed Harry all the other ones. Additionally, there is no mention of Hufflepuff's familiar living in a tree in the Room of Requirement; instead it lives in Hufflepuff's secret chamber. Nor did Hufflepuff's familiar have anything to do with curing an illness. Also, Harry was not "chosen" by them; rather, he was the heir (of all of them):
Chapter 3

After a few minutes as piece of paper shot out. Sharptooth read it out loud.
"Harry James Potter"
Son of James Charles Potter = Deceased and Lily Potter nee Evans = Deceased
Born: July 31st 1980.
Grandson of Charles Alexander Potter = Deceased and Dora Alina Potter nee Black
Heir: Potter = Main Line = direct
Black = Chosen Heir = chosen
Peverell = Father's side = direct
Gryffindor = Father's side = direct
Slytherin = Mother's side = direct
Ravenclaw = Mother's side = direct
Hufflepuff = Father's side = distant
Gaunt = Conquest = conquest

Harry had already killed Slytherins familiar in the Chamber based on
a conversation I remember him having with Ravenclaw’s familiar, so
this story began post Chamber of Secrets (this may be wrong as
slytherin a familiar might have been a different basilisk not the one
in the chamber).
Harry hadn't actually killed Slytherin's familiar, but he (and everyone else) thought that he had. Slytherin's familiar was the basilisk in the Chamber of Secrets  (named Sarota)but it turned out that Harry had wounded it but it had survived:
Chapter 2

Harry turned to him. "Sarota can enter the chamber and leave as he pleases he was after all Salazar's familiar."

Chapter 2

The hall was in an uproar. "I thought you said he killed it!" screamed many students. While certain Slytherins and Ravenclaws remembered the name from before. "EVERY ONE PLEASE CALM DOWN!" yelled Harry. Everyone stopped to look at him. "Alright yes the Headmaster said I killed him and during 2d year I thought I did as I had stabbed him threw the head and I thought I hit his brain. However I merely knocked him unconscious and made him wounded. I went back in the middle of third year and found him and we made peace... kinda." Harry explained. The hall still was frightened about there being a 60 ft basilisk in the school but they continued to listen to Dumbledore.

In any case the story does begin "post Chamber of Secrets".
Very loosely I recall that Harry may have stumbled onto some hidden
space of Ravenclaw’s in the Castle which led him into initial contact
with her familiar.
As mentioned in response to the first bullet, Harry found Ravenclaw's familiar in a secret chamber that Ravenclaw had in the castle.
Dumbledore has been siphoning power from Hogwarts's wards. Harry
follows him to a tower and confronts him during this act. I Roughly
remember Dumbledore is removed from Hogwarts and returns with
Ministry Aurors, etc.
There is no mention of Dumbledore siphoning power from Hogwarts's ward, or any confrontation relating to this on a tower. However, in the story Dumbledore is not quite good, as it turns out he had been obstructing Harry's parents' will, enabling theft from Harry's vaults, placing magic blockers on Harry, and creating an illegal marriage contract between Harry and Ginny:
Chapter 4

"Molly, Ginevra and Ronald have been taking money from the Vault since 1980 up until this year. Also Molly has made a new account under the name of "Prewett" for herself which in turn means she steals even more money. Albus Dumbledore was the one who gave them the key to Mr. Potter's vault due to him being Mr. Potter's magical guardian and after reading the will of his parents had NO right to claim. Also Albus Dumbledore put so many blocks on Harry's magic that it was nearly all blocked. Then finally to top it all off he made a illegal marriage contract with Ginevra Weasley and Harry Potter." Sharptooth said in one go.

Because of these misdeeds, there was a discussion about removing him from his position, but that did not occur by the end of the story:
Chapter 7

"As for you Albus you better hope you got a pretty good lawyer for I think you might end up getting a lot of your positions taken away from you." said Sirius glaring at the man.

There is, however, mention of a confrontation on a tower involving unnamed people, one of whom may have been Dumbledore:
Chapter 4

Harry saw something in his mind. It was a vision. It showed a army charging at another army. A cloaked man battling two people on a tall tower.

However, this is never elaborated upon later in the story.
Dumbledore practically destroyed the original wards around Hogwarts
by using the instruments from his office to carve slices out of them
essentially, but Slytherin had designed a secondary ward scheme which
Harry activates. This makes me think there was a heartstone or Ward
stone scene but it’s to fuzzy.
There is nothing remotely resembling this in the story.
There is a tower that is for Harry as an heir to the founders or
founders chosen whatever he's called. Dumbledore managed to find it
at one point and shattered the guardian status of the founders
familiar as I recall there’s a scene where Harry rebuilds this.
As mentioned in response to the first bullet, Harry was indeed the heir to all the founders. But none of the other details of this bullet are present in the story. There is a network of secret chambers that Harry has access to as their heir, but it's not a tower and Dumbledore never found it or did anything to it.
One particular scene involved Rowena's familiar discovering the
diadem was a Horcrux and going absolutely batshit. I remember they
used Magik with the K spelling fairly often.
There is no mention of the diadem or Horcruxes, and I did not notice any instances of "Magik" with a K.
I vaguely recall the familiars had some sort of shape shifting
ability, or were something other than the animals whose forms they
assumed as Rowena and Godric's familiars had a romantic past of sorts
they were discussing telling Harry about in one scene. Also
Ravenclaws familiar become the Transfiguration teacher after
McGonagall become Headmistress and she had a human female form.
There is nothing of this in the story.
There is a close relationship between Harry and Severus but it's not
slash and I can't remember if it's father/son, or simply
professor/student. Based on another comment Harry and Draco begin
some sort of relationship but I can’t recall the details ie Veela
etc.
There is not much of a relationship described between Harry and Snape. There is one point where it might be implied that their relationship will become better, but that is never shown to actually happen:
Chapter 3

Severus Snape however was silent and white as a ghost. James Potter his life long enemy had tried to apologize even going as far as to begging for forgiveness. Severus felt like a child. He had let a grudge rule over his emotions about a boy. Lily's boy. He felt sick. So sick that he looked paler than usual. He felt his whole world crash down and he couldn't stop it. He let a single tear fall out of his eye.

There is also no particular relationship shown between Harry and Malfoy.
I know it's not a lot to go on but this has been tormenting me and
I’ve wracked through about a hundred pages on FanFiction.net trying
to find it. The title was something completely ubiquitous as I
remember not expecting much based on it and being completely
engrossed and thinking it should have a better name. It was a
relatively lengthy fanfic, so at least 100k words but possibly much
more and, it was incomplete on my last read. I am 97% certain this
was on FF.net but I have read the odd story on Archive of Our Own, so
it could be there.
The story is indeed on fanfiction.net. The title The Dark Phoenix is indeed pretty vague and does not really describe the story as it currently stands. It is ten chapters, if that's considered relatively lengthy, and indeed it appears to be incomplete.

All in all there are quite a few details that do not fit, but perhaps there is still a chance that this is the story you are looking for.

Found with searching Google for "ravenclaw's familiar" site:fanfiction.net and then reading through it to find corroborating details.


Q:

Appveyor cannot find test coverage

I have a small project (.netstandard 1.0 + net45) on github which I integrated with Appveyor.
I'm using xunit for unit tests and opencover for test coverage.
I cannot get Appveyor to commit test results, here is the output:

Committing...
  No results, this could be for a number of reasons. The most common reasons are:
      1) missing PDBs for the assemblies that match the filter please review the
      output file and refer to the Usage guide (Usage.rtf) about filters.
      2) the profiler may not be registered correctly, please refer to the Usage
      guide and the -register switch.

Here is my script:
- .\tools\OpenCover.4.6.519\tools\OpenCover.Console.exe \
  -target:"c:\Program Files\dotnet\dotnet.exe" \
  -targetargs:"test -f netcoreapp1.1 -c %CONFIGURATION% Giver.Tests/Giver.Tests.csproj" \
  -mergeoutput \
  -hideskipped:File \
  -output:opencoverCoverage.xml \
  -oldStyle \
  -filter:"+[Giver*]* -[Giver.*Tests*]*" \
  -searchdirs:Giver.Tests/bin/%CONFIGURATION%/netcoreapp1.1 \
  -register:user
DebugType is full for all projects.
I probably tried most of the combinations for OpenCover.Console arguments.
The same script works on my machine (after replacing %CONFIGURATION%).

A:

Yeah, it was totally my mistake.
If you change DebugType to Full using Project Properties page (Visual Studio), beware, it will add a condition like this:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

I am using Release configuration for Appveyor build, so this condition will not be met and portable .pdb will be generated (opencover only works with Full .pdb).
After deleting this condition, everything works fine.


Q:

How do I install Cheese 3.0?

After seeing an article on Cheese 3.0 and it's new effects some months back, it was going to be one of the major highlights of 11.04 to me.
Sadly, I find 3.0 is not in the repo; it has been released, just not soon enough before the freeze.
So how do I install Cheese 3.0 in Ubuntu 11.04?

A:

You need GNOME 3 to run Cheese 3.0 while Ubuntu 11.04 has GNOME 2.32. So, what to do?
Wait a few weeks until the GNOME3 PPA has been throughly tested and install GNOME3 alongside to Unity. Then, you can install Cheese 3.0.
Instructions at https://launchpad.net/~gnome3-team/+archive/gnome3
NOTE: Do not install the PPA yet. Currently the PPA is experimental, and there is no going back (removing GNOME3 to go back to Unity).


Q:

Access 2010 Popup Report always matches size of Report Design window

I have always been mystified by how Access popup forms and reports seem to size themselves arbitrarily.  Today, I discovered that the report I'm working on is actually sizing itself to match the visible design area of the report's design view.  Detail fields are in tabular layout.  Detail section is 0.2", report width is 3.5", and there is a small header and footer.  Popup = Yes; Modal = No; Auto Resize = No.
When I drag the left border of the property box to increase the size of the property box, and then open in report view, this actually makes the report narrower!  I know I can open in report view, resize the borders, and save.  But whenever I open in design view again, the report size resets to the size of the visible design area.
I am not looking for a workaround (I already know I can resize programmatically).  I want to know if there is a fix to the above behavior.  Shouldn't it initially set the width to the Width property?  And the height to the height of all rows plus header/footer height?  Please tell me the above behavior is not by design.

A:

Yes, that's by design, and why wouldn't it?
With Auto Resize = No, the size of the popup window will be the window size you saved in design view. What else could it be?
If you want the popup window size to adapt to the form/report width, set Auto Resize = Yes. That's the usual way to handle popups.
The height of popup continuous forms/reports will still be determined by the height you save in design view.
Thinking about it, you probably have "tabbed document windows" set in the Access Options for the current database. With this option, you don't really have much control over the window size in design view.
If you must have popups with Auto Resize = No, you probably should switch to "overlapping windows". (I don't know the exact option names since I have a German Access).


Q:

Coordinates scale not correct when drawing a polyline on an View

I want to draw a polyline on a view. I don't want to draw it on a MapView because I only want the polyline without any background.
I have the polyline coordinates and I also have its bounds (northeast and southwest coordinates).
The idea was to create a custom view and draw the path there. The problem I believe I'm having is with the scale. I can convert the LatLng coordinates to x and y coordinates but the polyline that is shown on the view is too small. The view is set with a 64dp width and height.
Here is what I'm doing:
public PolylineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    polylineSize = (int) context.getResources().getDimension(R.dimen.polyline_size);
    setupAttributes(attrs);
}

private void setupAttributes(AttributeSet attrs) {
    // Obtain a typed array of attributes
    TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.PolylineView, 0, 0);
    // Extract custom attributes into member variables
    try {
        polylineColor = a.getColor(R.styleable.PolylineView_polylineColor, Color.BLACK);

    } finally {
        // TypedArray objects are shared and must be recycled.
        a.recycle();
    }

    polyline = new Paint(Paint.ANTI_ALIAS_FLAG);
    polyline.setAntiAlias(true);
    polyline.setStyle(Paint.Style.STROKE);
    polyline.setStrokeWidth(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
    polyline.setStrokeCap(Paint.Cap.ROUND);
    polyline.setColor(polylineColor);

    path = new Path();
    smp = new SphericalMercatorProjection(polylineSize);
}

@Override protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    point = smp.toPoint(polylineCoordinates.get(0));

    path.moveTo((float) (point.x * scale), (float) (point.y * scale));

    for (int i = 1; i < polylineCoordinates.size(); i++) {
        point = smp.toPoint(polylineCoordinates.get(i));

        path.lineTo((float) (point.x * scale), (float) (point.y * scale));
    }

    canvas.drawPath(path, polyline);
}

public void setPolyline(List<LatLng> polylineCoordinates, RealmLatLngBounds polylineBounds) {
    this.polylineBounds = polylineBounds;
    this.polylineCoordinates = polylineCoordinates;

    //Find the scale
    Point northeast = smp.toPoint(polylineBounds.getNortheast());
    Point southwest = smp.toPoint(polylineBounds.getSouthwest());
    scale = polylineSize / Math.max(Math.max(northeast.x, southwest.x), Math.max(northeast.y, southwest.y));

    invalidate();
    requestLayout();
}

After can I transform the polyline coordinates so that the full size of the view is used?
Edit:
One of the problems that I can see is when converting to x and y, values are two close (precision)

A:

With the help of @pskink I've managed to achieve this
private int polylineSize;
private Paint polyline;
private SphericalMercatorProjection smp;

PointF northeast;
PointF[] points;
PointF southwest;

Path originalPath;
Path transformedPath;

public PolylineView(Context context) {
    super(context);
}

public PolylineView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    polylineSize = (int) context.getResources().getDimension(R.dimen.polyline_size);
    setupAttributes(attrs);
}

public PolylineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    polylineSize = (int) context.getResources().getDimension(R.dimen.polyline_size);
    setupAttributes(attrs);
}

private void setupAttributes(AttributeSet attrs) {
    // Obtain a typed array of attributes
    TypedArray a = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.PolylineView, 0, 0);
    // Extract custom attributes into member variables
    int polylineColor;
    try {
        polylineColor = a.getColor(R.styleable.PolylineView_polylineColor, Color.BLACK);

    } finally {
        // TypedArray objects are shared and must be recycled.
        a.recycle();
    }

    polyline = new Paint(Paint.ANTI_ALIAS_FLAG);
    polyline.setAntiAlias(true);
    polyline.setStyle(Paint.Style.STROKE);
    polyline.setStrokeWidth(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
    polyline.setStrokeCap(Paint.Cap.ROUND);
    polyline.setColor(polylineColor);

    smp = new SphericalMercatorProjection(polylineSize);

}

public void setPolylineData(List<LatLng> polylineCoordinates, RealmLatLngBounds polylineBounds) {

    originalPath = new Path();
    transformedPath = new Path();

    Point point = smp.toPoint(polylineBounds.getNortheast());
    northeast = new PointF((float) point.x, (float) point.y);

    point = smp.toPoint(polylineBounds.getSouthwest());
    southwest = new PointF((float) point.x, (float) point.y);

    points = new PointF[polylineCoordinates.size()];

    for (int i = 0; i < polylineCoordinates.size(); i++) {
        point = smp.toPoint(polylineCoordinates.get(i));
        points[i] = new PointF((float) point.x, (float) point.y);
    }

    originalPath.moveTo(points[0].x, points[0].y);

    for (PointF p : points) {
        originalPath.lineTo(p.x, p.y);
    }

    RectF src = new RectF(southwest.x, northeast.y, northeast.x, southwest.y);
    RectF dst = new RectF(0, 0, polylineSize, polylineSize);
    Matrix matrix = new Matrix();
    matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
    originalPath.transform(matrix, transformedPath);

    invalidate();
    requestLayout();
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawPath(transformedPath, polyline);
}

This view is used on a RecyclerView and the data is set on onBindViewHolder


Q:

declare two foreign key that are also primary key

i'm facing a strange problem by declaring two foreign key on a table, that are also a primary key in my table. This is my sql code:
CREATE TABLE IF NOT EXISTS guest (
    id_guest varchar(50) NOT NULL,
    PRIMARY KEY(id_guest)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS product (
    id_product varchar(100) NOT NULL,
    PRIMARY KEY(id_product)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS product_guest_resale (
    id_guest varchar(50) NOT NULL,
    id_product varchar(100) NOT NULL,
    amount int(100) NOT NULL,
    PRIMARY KEY (id_guest, id_product),
    FOREIGN KEY id_guest REFERENCES guest(id_guest),
    FOREIGN KEY id_product REFERENCES product(id_product)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;

when i execute my code, i obtain this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REFERENCES guest(id_guest),
FOREIGN KEY id_product REFERENCES product(' at line 6

what's wrong?

A:

You miss the parenthesis:
CREATE TABLE IF NOT EXISTS product_guest_resale (
    id_guest varchar(50) NOT NULL,
    id_product varchar(100) NOT NULL,
    amount int(100) NOT NULL,
    PRIMARY KEY (id_guest, id_product),
    FOREIGN KEY (id_guest) REFERENCES guest(id_guest),
    FOREIGN KEY (id_product) REFERENCES product(id_product)
) ENGINE=InnoDb DEFAULT CHARSET=latin1;


Q:

How to send sms from Android NDK or Cocos2dx

I want to send sms from cocos2d-x engine.If this engine can't send sms, does Android NDK support it? Anyone can help me? Thanks.

A:

There isn't any native C functionality for sending SMS messages, but you can always use JNI to access SMSManager.


Q:

ORACLE PL/SQL: Dynamic SQL Select using a Collection

Is it possible to create a dynamic SQL statement that pulls from an existing collection?
l_collection := pack.get_items(
                i_code => get_items_list.i_code ,
                i_name => get_items_list.i_name );

Now, let's say I want to select a COUNT from that collection using dynamic SQL. Is that possible? Furthermore, I want to do a sub select from that collection as well.

A:

If the collection type is declared at the schema level, it can be used in SQL statements, including dynamic ones.  You need to explicitly cast it to the proper collection type, or the SQL engine has no idea what type it is.
EXECUTE IMMEDIATE
  'SELECT COUNT(*) FROM TABLE(CAST(:collection AS collection_type))'
   INTO l_count
   USING l_collection
  ;

I'm not sure if there's some other reason you want to use dynamic SQL, or if you're just assuming that it's necessary in this case.  It shouldn't be necessary if all you want to do is select the count.  This inline SQL should work fine:
SELECT COUNT(*) INTO l_count FROM TABLE(CAST(l_collection AS collection_type));

Of course, if that's all you want you don't need SQL at all, just l_count := l_collection.COUNT.
Edit -- adding fully worked out example
CREATE OR REPLACE TYPE testtype AS OBJECT( x NUMBER, y NUMBER);
/

CREATE OR REPLACE TYPE testtypetab AS TABLE OF testtype;
/

DECLARE
  t  testtypetab := testtypetab();
  l_count integer;
BEGIN
  -- Populate the collection with some data
  SELECT testtype(LEVEL, LEVEL) BULK COLLECT INTO t FROM dual CONNECT BY LEVEL<21;

  -- Show that we can query it using inline SQL
  SELECT count(*) INTO l_count FROM TABLE(CAST(t AS testtypetab));
  dbms_output.put_line( l_count );

  -- Clear the collection
  t.DELETE;

  -- Show that we can query it using dynamic SQL
  EXECUTE IMMEDIATE 'select count(*) from table(cast(:collection as testtypetab))'
    into l_count using t;
  dbms_output.put_line( l_count );
END;
/


Q:

Open map in a given address using MapKit and Swift

I am having a bit of trouble understanding Apple's MapKit in Swift 3.
I found an example here: How to open maps App programmatically with coordinates in swift?
public func openMapForPlace(lat:Double = 0, long:Double = 0, placeName:String = "") {
    let latitude: CLLocationDegrees = lat
    let longitude: CLLocationDegrees = long

    let regionDistance:CLLocationDistance = 100
    let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
    let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
    let options = [
        MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
        MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
    ]
    let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = placeName
    mapItem.openInMaps(launchOptions: options)
}

This works absolutely swimmingly, except that I need to use an address instead of coordinates in this case.
I have found methods for doing this using google maps, but I cant seem to find a specific answer for Apple Maps, if it exists, I've completed glazed over it.
If anyone can help me to understand what the correct approach is, that would be amazing. I'm using:

Xcode 8.3.1
Swift 3.1
macOS
Targeting iOS 10+

A:

You need to use the Geocoding service to convert an address to the corresponding geolocation.
For instance, add this function to your toolkit:
func coordinates(forAddress address: String, completion: @escaping (CLLocationCoordinate2D?) -> Void) {
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(address) {
        (placemarks, error) in
        guard error == nil else {
            print("Geocoding error: \(error!)")
            completion(nil)
            return
        }
        completion(placemarks.first?.location?.coordinate)
    }
}

and then use it like this:
coordinates(forAddress: "YOUR ADDRESS") {
    (location) in
    guard let location = location else {
        // Handle error here.
        return
    }
    openMapForPlace(lat: location.latitude, long: location.longitude)
}

A:

You need to use geoCode to get the coordinates from the address... This should work:
let geocoder = CLGeocoder()

geocoder.geocodeAddressString("ADDRESS_STRING") { (placemarks, error) in

  if error != nil {
    //Deal with error here
  } else if let placemarks = placemarks {

    if let coordinate = placemarks.first?.location?.coordinate {
       //Here's your coordinate
    }
  }
}


Q:

Search and Click Experience

I am after a solution where a user can search for an inducted user (Just a String using Title field), once the search results are returned the user can click on the returned search results title and then be taken to all results related to that user.
Example, Inductee List contains a user named 'Greg Smith' (Title Field), another List named Inductions contains a Lookup to the Inductee Lists Title field. When a search is performed on Greg the results return several list items named Greg, the user could then click on Greg Smith and be shown the entries from the Inductee list and inductions list just for Greg Smith.
Is this possible or is there another approach I can take?
Using SharePoint Online, Modern Experience.

A:

You can do this quite easily if you understand how to change the search rendering in the UI. You say you are using the "Modern Experience" so I would suggest you look into the PnP Modern Search web parts. Here is a thumbnail of how you do this:

Optional, but it makes the initial query way easier, make inductee a content type.
Tag all relevant data with a person field (eg. InducteeName) if Greg Smith is part of your tenant org. If not then you may want to use Text or MMS depending on your needs. Make it a Site Column if you are using it on several lists.
Create a Managed Property (eg. InducteeName) for the field above. (I would use a Refinable field)
Create two Search Pages (you can do it with one, but I'd start with two for simplicity)
On the first page the search results web part craft the query like ContentType=Inductee Title:{query} or similar. This way you only get inductee results and hits from the title field. (My syntax may not be perfect, but you get the idea. If you are not using a content type, you'll have to use Path)
Change the results rendering for the link on the title field. This will be the URL to the second results page with a query appended to it something like k="InducteeName={the title field value}"

This is all easy in the traditional SharePoint Search Center using display templates and query rules. Sadly, in Modern, these features are not available without the PnP. NOTE: All queries are approximations. You'll have to mess with them to get it just right.


Q:

How to bind wxpython listctrl with onclick button event

I have a wxpython listctrl , which contains 4 column[A, B, C, D]. User selects any one of the row from listctrl. Now i have a button in my gui so when i click that i want to print the value of column D from that selected row.
For example lets user has selected this row:
                       [PYTHON, JAVA, MATLAB, RUBY]
now if user clicks the button it should give output: RUBY
I am binding THE BUTTON in this way
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnPlot, self.list)

self.list.Append((j[0],j[1],j[2],j[3]))     #values are inserted in the listctrl

And OnPlot event i have defined as:
    def OnPlot(self, event):
        click =  event.GetText()
It doesn't work but.  How can i accomplish this?

A:

The event will pass the index of the selected item from the listctrl.
Use the index to get the item and column within the listctrl, in this case 3.
Get the text of the column.
Namely:
def on_plot(self, event):
    ind = event.GetIndex()
    item = self.list_ctrl.GetItem(ind,3)
    print item.GetText()

This assumes that you have bound the listctrl like this:
self.list_ctrl.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_plot, self.list_ctrl)

Edit:
With regard to your comment and the edit to the title of the question.
You cannot bind an arbitrary event to something. A button has a set of defined events as does a listctrl and never the twain shall meet. The way around your issue is to bind the button to a button event.
plot_button.Bind(wx.EVT_BUTTON, self.on_plot)

then define on_plot like this:
def on_plot(self, event):
    ind = self.list_ctrl.GetFirstSelected()
    if ind >=0:
        item = self.list_ctrl.GetItem(ind,3)
        print item.GetText()

As you will see it achieves the same end result but and it's a big but, you have already had to click on the listctrl to select an item. That being the case, you could have already achieved the same result, using the first method, without having to define the button in the first place and using this method you now have to check in case nothing was selected (ind must not be -1).


Q:

Qt Creator no option for Qt Application

I've installed the Qt Creator v2.6.2 based on Qt 4.8.3(32-bit). When I started new project, I couldn't find the "Qt C++ Application" tab.
it only shows libraries, other projects, Non-Qt projects and import projects
what am I missing here?
thx b4

A:

Go to Tools -> Options -> Build & Run > Qt Versions tab and check whether your installed Qt versions are recognized or not. If the list is empty that means: for some reason Qt Creator has stopped detecting your Qt library.
To solve this problem, Press the "Add" button in that dialog "Tools -> Options -> Build & Run > Qt Versions" and locate your installed 'qmake.exe' file. It should be in the bin directory of where you installed the Qt library (e.g. C > Qt > 4.8.4 > bin > qmake.exe ). If still not recognized, you should look for the easiest way like installing "qt SDK" which takes care of everything.


Q:

Group homomorphism between $\Bbb{Q}$ and $\Bbb{Q}\times\Bbb{Q}$

I am trying to find out the number of homomorphisms from $(\mathbb{Q},+)$ to $(\mathbb{Q}\times \mathbb{Q},+)$. All I understood is that if $f$ is a homomorphism, then it must satisfy
$f(0)=f(0,0)$. Moreover,
How do I make the conclusion that there exists no isomorphisms between them?

A:

There's a lot more we can tell about a homomorphism $f:\mathbb{Q}\to G$ for any abelian group $(G,+)$. If $n\in\mathbb{N}$ then
$$f(n)=f(1+\cdots+1)=f(1)+\cdots+f(1)=nf(1)$$
Now if $q\in\mathbb{N}$ is nonzero, then
$$f(1)=f\bigg(\frac{q}{q}\bigg)=f\bigg(\frac{1}{q}+\cdots+\frac{1}{q}\bigg)=f\bigg(\frac{1}{q}\bigg)+\cdots+f\bigg(\frac{1}{q}\bigg)=qf\bigg(\frac{1}{q}\bigg)$$
and thus $f\big(\frac{1}{q}\big)=\frac{1}{q}f(1)$ if $G$ is a divisible group (like $\mathbb{Q}\times\mathbb{Q}$). Combining both together, and extending to negatives, we obtain that if $G$ is a divisible group, then
$$f\bigg(\frac{p}{q}\bigg)=\frac{p}{q}f(1)$$
Note the subtlety: on the right side we don't have a multiplication, but rather a solution to $qf(p/q)=pf(1)$.
In the case when $G=\mathbb{Q}\times\mathbb{Q}$ we obtain that
$$f\bigg(\frac{p}{q}\bigg)=\bigg(\frac{p}{q}v_1, \frac{p}{q}v_2\bigg)$$
for some fixed $v_1,v_2\in\mathbb{Q}$. Here on the right side we have the standard rationals multiplication (which corresponds to the solution to the equation mentioned earlier).
So can $f$ be an isomorphism? If $v_1=v_2=0$ then it is the zero morphism. On the other hand if $v_1\neq 0$, then $(0,1)$ does not belong to the image of $f$. If $v_2\neq 0$ then $(1,0)$ does not belong to the image of $f$. Hence $f$ is never surjective.
As an alternative we can utilize linear algebra. The formula $f(k)=kf(1)$ also means that every group homomorphism $f:\mathbb{Q}\to\mathbb{Q}^n$ is also a linear map over $\mathbb{Q}$. And thus we can simply use the dimension argument to conclude that it cannot be an isomorphism when $n>1$.


Q:

What is $\cos\left(\frac{\arctan(x)}{3}\right)$ and $\sin\left(\frac{\arctan(x)}{3}\right)$?

I know that $$\cos(\dfrac{\pi}{3} - \arctan(x))= \dfrac{1}{2\sqrt{(1+x^2)}} + \dfrac{\sqrt{3}x}{2\sqrt{(1+x^2)}}$$
$\cos\left(\dfrac{\pi}{3} - \dfrac{\arctan(x)}{3}\right)$ = ?
$\cos\left(\dfrac{\pi}{3} - \dfrac{\arctan(x)}{3}\right) = \cos\left(\dfrac{\pi}{3}\right)\cos\left(\dfrac{\arctan(x)}{3}\right) + \sin\left(\dfrac{\pi}{3}\right)\sin\left(\dfrac{\arctan(x)}{3}\right) = \dfrac{1}{2}\cos\left(\dfrac{\arctan(x)}{3}\right) + \dfrac{\sqrt{3}}{2}\sin\left(\dfrac{\arctan(x)}{3}\right)$
but I can't go further since I don't know how to solve $\sin\left(\dfrac{\arctan(x)}{3}\right)$ and $\cos\left(\dfrac{\arctan(x)}{3}\right)$.
Any suggestion?

A:

Let us care about
$$t:=\tan\left(\frac{\arctan(x)}3\right), $$
using the fact that
$$\tan\left(3\frac{\arctan(x)}3\right)=x.$$
By the triple angle formula, this equation writes
$$\frac{3t-t^3}{1-3t^2}=x$$
or
$$t^3-3xt^2-3t+x=0.$$
We depress it with $u:=t-x$, giving
$$u^3-3(x^2+1)u-2x(x^2+1)=0.$$
Now the discriminant is given by
$$(x(x^2+1))^2-(x^2+1)^3=-(x^2+1)^2.$$
As it is negative, the final expression will involve cubic roots of complex numbers, which cannot be expressed without… trigonometry, and you are circling in rounds.


Q:

How to remove values from text file with conditions

I am trying to make a function to convert srt to vtt so I specified the differences between the two files:
srt
1
    00:00:05,795 --> 00:00:09,832
    Are you alright?

vtt
00:00:05.795 --> 00:00:09.832
Are you alright?

The difference is in the number above every line which increases by 1 in every line and the , in the time.
I made a function to replace , with . but I don't know how to remove all numbers from the file. I am thinking about removing the lines that is 5 letters length but maybe there is another option?
Here is what I have done:
function srttovtt($file){
    $str = implode("\n", file($file));
    $name = basename($file, '.srt');
    $fp = fopen('uploads/subs/' . $name . '.vtt', 'w');

    $str = str_replace(',', '.', $str); // replace comma

    fwrite($fp, $str, strlen($str));
    return $fp;
}

A:

regex to the rescue
$text = preg_replace('~\d+\s*(\d{2}):(\d{2}):(\d{2}),(\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2}),(\d{3})~', '\1:\2:\3.\4 --> \5:\6:\7.\8', $text);

the first \d+ is the number that's got to go and the \s* following is every whitespace after it.
next we have the times we want modified, so we keep the numeric values in parenthesis, so we can use it later on with \1, \2 etc in the format we want.
I should have included a \s* at the start too, but then I would need a newline at the start of the formatted text, which I could not find how to insert. \n didn't seem to do the job. If anyone knows how, please edit. Though it's only visual and you don't really care for that in a subtitles file.


Q:

Which IndexedDB data structure for Chrome app?

I'm on the way to build a Chrome app, dedicated to fulfill shop/marketplace orders. The orders come from marketplace APIs like Amazon MWS. The data is stored only in the app (with backup). The system need also to work in a quick way if 50.000 or 100.000 orders are stored.
So how to structure the IndexedDB for that?
Each order can have multiple ordered items. It can also have multiple parcel tracking codes and so on.
var simplifiedOrderObject = {
    "ordernumber": "123-12345-234",
    "name": "Mr. Sample",
    "address": "Foostreet 12, 12345 Bar York",
    "orderitems": [
        {
            "item": "brush",
            "price": "2.00"
        },
        {
            "item": "phone",
            "price": "30.90"
        }
    ],
    "parcels": [
        {
            "service": "DHL",
            "track": "12345"
        },
        {
            "service": "UPS",
            "track": "3254231514"
        }
    ]
}

Should i create only one objectStore, which holds the complete order data in one object/row like shown above? If i would do so: Is it possible and fast to have an index for search for a parcel number? - Again: multiple parcel numbers can be in each object/row.
Or is it better or even needed to do it like in relational DBs:

One ObjectStore for order
one for orderItem
one for parcels shipped
...
and all of this is connected by having the same orderNumber?

Which is the faster and more efficient way?

A:

Answering my own question: I have made some tests now. It looks like it is not possible to do this with that object in only 1 objectStore.
An other example object which would work:
var myObject = {
    "ordernumber": "123-12345-234",
    "name": "Mr. Sample",
    "shipping": {"method": "letter",
                 "company": "Deutsche Post AG" }
}

Creating an index will be done by:
objectStore.createIndex(objectIndexName, objectKeypath, optionalObjectParameters);

With setting objectKeypath it is possible to address a value in the main object like "name":
objectStore.createIndex("name", "name", {unique: false});

It would also be possible to address a value form a subobject of an object like "shipping.method":
objectStore.createIndex("shipping", "shipping.method", {unique: false});

BUT it is not possible to address values like the ones of "track", which are contained in objects, stored in an array. Even something like "parcels[0].track" to get the first value as index does not work.
Anyhow, it would be possible to index all simple elements of an array (but not objects).
So the following more simple structure would allow to create an index entry for each parcelnumber in the array "trackingNumbers":
var simplifiedOrderObject = {
    "ordernumber": "123-12345-234",
    "name": "Mr. Sample",
    "address": "Foostreet 12, 12345 Bar York",
    "orderitems": [
        {
            "item": "brush",
            "price": "2.00"
        },
        {
            "item": "phone",
            "price": "30.90"
        }
    ],
    "trackingNumbers": ["12345", "3254231514"]
}

when creating the index with multiEntry set to true:
objectStore.createIndex("tracking", "trackingNumbers", {unique: false, multiEntry: true});

Anyhow, the missing of the possibility to index object values in arrays, makes using indexedDB really unneeded complicated. It's a failure in design. This forces the developer to do things like in relational DBs, while lacking all the possibilities of SQL. Really bad :(


Q:

Python: Format placeholder multiple times for the same variable

I would like to perform both a padding and limit the number of decimal points of a variable that will be inputted into a string using .format. I have managed to limit the decimal places but I can't seem to add the padding as well. The documentation wasn't much help. Below is a copy of my code.
print "Frame No. {:6d} Expected: {:7.3f}ms Actual: {:7.3f}ms Difference: {:7.3f}ms - ERROR".format(currentImage, expected_time, regression_obj.timeFromStart, (regression_obj.timeFromStart - expected_time))

The output here shows that there is not enough spaces between values. I would like all the values to be aligned.
Frame No.     17 Expected: 582.080ms Actual: 484.971ms Difference: -97.109ms - ERROR
Frame No.     18 Expected: 616.320ms Actual: 513.498ms Difference: -102.822ms - ERROR

Expected Output;
Frame No.     17 Expected:       582.080ms Actual:     484.971ms Difference:   -97.109ms - ERROR
Frame No.     18 Expected:       616.320ms Actual:     513.498ms Difference:  -102.822ms - ERROR

A:

Use {:9.3f}. The first digit is minimum width of the entire number, including the minus sign, decimal point and decimal digits.
In your example -102.822 is already 8 characters, so it goes out of alignment when you specify width of 7.


Q:

Azure function TimerTrigger result code in Application Insights is always success

I've got a simple C# Azure Function using a timer trigger to run every X minutes. No output binding.
In application insights, the function is always in success with a result code of 0:

[Despite having called the .Error() of the TraceWriter several times.]
I'd like to get the correct final status in application insights but I don't see how to do it. Documentation never talks about that :-/
Can someone guide me how to do it in C# ?
I tried to set Environment.ExiCode but same result.
I also tried to change return type to int but then the function isn't called anymore. I suppose because its the way to declare an output binding for the azure function itself.
Here is my function:
[FunctionName("SendToOfflineArchive")]
public static void Run([TimerTrigger("%TimerInterval%")]TimerInfo myTimer, TraceWriter log)
{
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

    // do stuff

    int nbErrors = 7;
    //return nbErrors;
}

It would be great to have a result code other than 0... Like the number of errors (an integer).

A:

Azure Function is considered failed if it threw an exception (there is an embedded integration between AF and AI and it considers successfully executed function a "success"). Logging an error as a trace should yield corresponding Trace message in Application Insights if logging forwarding is enabled.


Q:

Why can't I add a comment?

I asked two Star Trek questions a while ago and I'm trying to comment back. For some reason I can't add a comment. Any help?

A:

For commenting anywhere, you need 50 reputation points. (This equates to 5 upvotes on answers or questions, so you should be able to pick up those points fairly quickly if you have good content to contribute.)
For commenting on your own posts, or on answers to your own questions, there's no reputation requirement - you should be able to do this. If this is what you're trying to do and failing, then perhaps for some reason your account isn't associated with the questions you asked? I can only see one question in your account history, but you mention that you asked two. (Could you provide a link to the other one?) If you asked the questions using two different accounts and you need to merge accounts, you can do that by following the instructions here.
In general, the help centre has most of the info you need about the basic workings of the site, but you can always feel free to ask on meta if you still need help. (The main site is only for questions about sci-fi or fantasy; questions about the site should be asked here on meta instead.)


Q:

Is this possible without using javascript?

I made a simple web UI with JSFiddle and I am wondering if the same UI can be made without using JavaScript.
A Fiddle says more than 1000 words.
So the question is (because it seems unclear for some people): How can I achieve the same results without using any JavaScript?
PS: I don't want to use JavaScript to re-calculate the position on every scroll event because the repositioning in IE is not smooth enough.
HTML:

        B

        This stays fixed when scrolling horizontally, but scrolls along when scrolling down the parent.

CSS:
.A {
    background-color: yellow;
    height: 400px;
    width: 700px;
    overflow:scroll;
    position: relative;
}

.B {
    background-color: green;
    height: 1000px;
    width: 1500px;
    position: absolute;
    top:0;
    color:white;
}

.C {
    background-color: red;
    position: absolute;
    left: 100px;
    top: 0px;
    height: 1000px;
    width: 100px;
}

JS (with jQuery):
$('.A').scroll(function(e) {
    $('.C').css('left', e.target.scrollLeft + 100);
});

A:

When enough browsers support it, you will be able to use the new sticky position value:
.C {
    position: sticky;
    position: -webkit-sticky;
    left: 100px;
    top: auto; /* Default value */
}

http://jsfiddle.net/5z3nLqq5/12/


Q:

permanently decrypt messages in outlook (S/MIME)

I have messages encrypted with S/MIME in Microsoft Outook. These can only be decrypted with the certificate installed on the client.
Encryption stays even when saving the messagesto disk (as .msg) or moving them to another e-mail account (drag and drop in exchange).
How can I permanently decrypt these messages?
Either for saving them on disk or inside of Exchange/IMAP.

A:

I just found this option in Outlook:

Open the encrypted email (you might need your password or whatever)
in the email window, use the menu item 'File/Info/Properties'
In the pop-up, under Security (top right), uncheck 'Encrypt email...', close, and save:

(It is grayed out in this shot, but if you have an encrypted email, it will be checked and changeable)


Q:

Why is os.path.abspath adding the alias name when it expands an alias?

My code needs to be able to search through a list of directories for a specific file. It needs to handle an alias as part of a path name and still find the actual path to a file. For example, it needs to turn something like $HOME/test.dat into /home/greenmatt/test.dat. As such, I'm trying to use os.path.abspath.
Unfortunately, the results come back with the alias name glued onto the end of the actual directory name. The following demonstrates what I'm seeing.
From the command line:
> echo $HOME
/home/greenmatt

Then inside Python:
> python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print(os.path.abspath('$HOME'))
/home/greenmatt/$HOME

os.path.realpath does the same thing:
>>> print(os.path.realpath('$HOME'))
/home/greenmatt/$HOME

Why is the extra '$HOME' getting added to the path? How do I get the absolute path without it?

A:

os.path.expandvars(path) expands environment variables in a path. After expanding, the absolute path can be created. Together:
os.path.abspath(os.path.expandvars(path))


Q:

Generate input button with onClick function using JavaScript DOM

I use JavaScript to generate form input fields on my page. Everything works fine, except the button. I came across some problems generation the button's onClick function using DOM. You can see the code below, but on my page, there is no the onClick function as the attribute of the input button tag:
n = 1;
function generate() {
    var radiomore = document.createElement("input");
    radiomore.type = "button";
    radiomore.name = "opt[" + n + "]";
    radiomore.value = "Add more options";
    radiomore.setAttribute = ('onClick',addradiomore);
    var div = document.createElement("div");
    div.innerHTML = "Op: " + radiomore.outerHTML + "<br/>";
    document.getElementById("mydiv").appendChild(div);
n++;
}

function addradiomore() {
    //here goes the function code
}

And this is what it generates on my page:
<input type="button" name="opt[1]" value="Add more options">

There is no function?!?!
P.S.
Even if I use like this it doesn't work:
radiomore.onclick = addradiomore();

A:

You should use this:
radiomore.onclick = addradiomore;

DEMO


Q:

Appending  tag separately to every Array value using Javascript

This is my first JavaScript project and I am having some difficulties to append the  tag separately to each value of an array. Whatever I tried so far results in a single  tag. What could be an elegant solution using native JavaScript? Thanks in advance for any help.

let numbers = [1990, 1991, 1992];

let history = [];
let historyContainer = document.getElementById("output");
let para = document.createElement("p");
history.push(numbers.join(" "));

for (let k in history) {
 let text = document.createElement("span");
 let node = document.createTextNode(history[k]);
 text.appendChild(node)
 para.appendChild(text);
 historyContainer.appendChild(para);
}

Link to external jsfiddle

A:

history.push(numbers.join(" ")); is your problem - by the time the loop runs history is an array with a single value of 1990 1991 1992 because of the join. In fact you don't even need history, just iterate over numbers

let numbers = [1990, 1991, 1992];
let historyContainer = document.getElementById("output");
let para = document.createElement("p");

for (let k in numbers) {
  let text = document.createElement("span");
  let node = document.createTextNode(numbers[k]);
  text.appendChild(node)
  para.appendChild(text);
  historyContainer.appendChild(para);
}
span+span {
  margin-left: 4px;
}


Q:

How to make element in svg not stretched by viewbox?

This example draw two circle in a box sized 10 x 10.
<svg width="10" height="10" viewbox="0 0 10 10">
    <circle cx="2" cy="2" r="2" fill="purple" /> <!-- circle A-->
    <circle cx="4" cy="4" r="2" fill="purple" /> <!-- circle B-->
</svg>

Circle A have same size as circle B. Suppose i want to resize the svg to 100 x 100 like this:
<svg width="100" height="100" viewbox="0 0 10 10">
    <circle cx="2" cy="2" r="2" fill="purple" /> <!-- circle A-->
    <circle cx="4" cy="4" r="2" fill="purple" /> <!-- circle B-->
</svg>

The size of circles will resized. How to make specific element inside svg, lets say circle A only, so it is not affected to the resize.

A:

I made another sample. I use nested svg element to split effect of viewBox. You can place shape nodes relative position by using percentage value, but this technique is not useful for general path shapes. Since, I use "use" element to split shape definition and positioning.
<svg width="100" height="100">
    <defs>
        <!--shape definition-->
        <circle r="2" fill="red" id="circleA"/> <!-- circle A-->
    </defs>
    <!--parcentage positioning by viewport-->
    <use x="20%" y="20%" xlink:href="#circleA"/>
    <svg viewBox="0 0 10 10">
        <circle cx="4" cy="4" r="2" fill="purple" /> <!-- circle B-->
    </svg>
</svg>


Q:

JSON Schema validating a range of numbers for a integer property

I'm using TV4 to validate my schema, and I saw that this lib use Json Schema model to validate a JSON.
But I didn't found a way to do a specific validation.
I have a integer property and this property can only have one of some numbers. For example, the valid number for me is, 10, 20, 30 and 40, so if I put some number different than these numbers, I need to show a validation error.
Has some way to do this specific validation in JSON Schema ?

A:

I'm not sure if you want an enum or you want your integer values to be multiples of 10.
For enum, you have an array of the allowed values. For example:
{
  "type": "string",
  "enum": ["red", "amber", "green"]
}

source
If you want values to be only multiples of a number, you want multipleOf.
{
    "type"       : "number",
    "multipleOf" : 10
}

source
These links are for the draft-4 version of JSON Schema, as that's what the library you're using supports, however these key words are also present in the lates version of JSON Schema (draft-7 at the time of writing). You may consider using a differnet library which supports newer versions.


Q:

Nonsingularity and inverse of a matrix.

I am having some trouble solving this question:
Let $A,B,C,D$ be $n\times n$ matrices. Suppose $C$ and $A-BC^{-1}B^T$  are nonsingular.
Show that the matrix mentioned is nonsingular and find its inverse
\begin{bmatrix}A&B\\B^T&C\end{bmatrix}
For nonsingularity $\det(M)$ is not $0$.
Any help is appreciated :)
Edit:
I found that M is nonsingular, can anyone help me finding the inverse?

A:

$$
\begin{bmatrix}
A & B \\
B^T & C
\end{bmatrix}
\begin{bmatrix}
U & V \\
W & X
\end{bmatrix}=
\begin{bmatrix}
AU+BW & AV+BX \\
B^TU+CW & B^TV+CX \\
\end{bmatrix}
$$
So we want

$B^TU+CW=0$, hence $W=-C^{-1}B^TU$
$AU+BW=I$, so $AU-BC^{-1}B^TU=I$ and therefore $U=(A-BC^{-1}B^T)^{-1}$

Similarly for $V$ and $X$:

$B^TV+CX=I$, so $X=C^{-1}(I-B^TV)$
$AV+BX=0$, so $AV+BC^{-1}(I-B^TV)=0$, so
$$
AV+BC^{-1}-BC^{-1}BTV=0
$$
and $V=-(A-BC^{-1}B^T)BC^{-1}$

You can compute $X$.


Q:

How to redefine a function at runtime, without restarting the program?

Let's say I have a code like this:
def draw():
    Display.render_text(color="white", align="left", text="This is a text")

while True:
    draw()

And suddenly I want to edit draw() to something like:
def draw():
    Display.render_text(color="green", align="center", text="THIS CHANGES EVERYTHING!")

How do I do this without restarting the whole program? When I'm in the python's interactive console, I just edit draw() a bit, copypaste it into console, and then copypaste while True: loop. But I don't know how to do something like that with a programs which are started from the shell.
So, I need to somehow tell python to pause execution as soon as he leaves the draw() function, quickly swap it with a new version, and continue the execution.
I suspect that Common Lisp can do something like that, it has really good debugging features. C# can do this, but you have to manually pause your program before editing anything, which I'm too lazy to do (I need to teach Visual Studio to automatically pause execution at the right time, hotkey for recompilation, etc). C can do this with hotpatching, but I'm yet to meet a working example of that. Go probably can do something like this if you disable some of it's optimisations, like inlining and maybe some others, in a way simular to C. Lua was created for this. Python probably can do this, but I don't know how.

A:

exec("def pt():\n    print('two')")


Q:

move a image in a ouside div when hovering a menu with jquery

well, i have 5 elements in a menu, and a little line under this with an image that moves depend on which element you are hovering. By default is under the current website, so it can start in any of the 5 elements.
So if you hover something it moves to that place, if you stop hovering the menu, it comes back to current. But if you hover other element before the current, it goes directly to that point.
All menus have the same part of the begining of the id, for example #fxmenu_1. From 1 to 5, i think is faster to take just the number of the id and avoid writting 5 jquerys.
I tried a little bit, but there is something wrong with my jquery.
$(document).ready(function(){
var id;
    $('#fxmenu_'+id+':not(.totalactive)').hover(function (){
        $('#img').animate({"marginTop": "-70px"},1000, function(){
            $('#img').animate({"marginLeft":+(180*id)+"px"},1000, function(){
                $('#img').animate({"marginTop": "-90px"},1000);
                });
        });
    });
});

Here you can see my example: http://jsfiddle.net/rzJMv/1/
This is another try
$(document).ready(function(){
var id,
    hovermenu = $('#fxmenu_'+id);
    $(hovermenu).hover(function (){
        $('#img').animate({marginTop: "-70px"},1000, function(){
            $('#img').animate({marginLeft:+(180*id)+"px"},1000, function(){
                $('#img').animate({marginTop: "-90px"},1000);
            });
        });
    }, function() {
        $('#img').removeAttr('style');

    });
});

A:

May I suggest using this javascript plugin?
http://www.scriptiny.com/2008/05/sliding-javascript-menu-highlight-1kb/
It has the functionality you are trying to recreate. Why try to recreate the wheel?
Edit 1
Anyway, if you did want to do this with your code, here is a reworking.
HTML

LOGO

The team

Services

Projects

Contact

Javascript
$(document).ready(function() {
    var activeIndex = $('#bmenul > li.active').index();

    $('#img').css({
        'marginLeft': (180 * activeIndex) + 'px'
    }).show();

    $('#bmenul > li').not('.active').hover(function() {
        var index = $(this).index();
        $('#img').stop().animate({
            'marginLeft': (180 * index) + 'px'
        }, 400);
    }, function() {
        $('#img').stop().animate({
            'marginLeft': (180 * activeIndex) + 'px'
        }, 400);
    });
});

CSS
...
#img {
    max-height: 180px;
    width: 180px;
    border-bottom: 2px solid #000000;
    display: none;
}

Demo