Q:

Powershell import-module webadministration

Every time I execute this command
invoke-command -computername REMOTEPC -scriptblock { import-module WebAdministration; new-item "$env:systemdrive\inetpub\testsite" -type directory; New-WebSite -Name TestSite -Port 81 -PhysicalPath "$env:systemdrive\inetpub\testsite" }

I get the following error
Invalid class string (Exception from HRESULT: 0x800401F3 (CO_E_CLASSSTRING))
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.PowerShell.Commands.GetChildItemCommand

The website is created successfully as far as I can see.
The following command gives the same error when enumerating the testsite
Invoke-Command -computername REMOTEPC { import-module webadministration; dir -path IIS:\Sites\ }

Name             ID   State     Physical Path     Bindings      PSComputerName
Default Web Site 1    Started                     http *:80:    REMOTEPC

Invalid class string (Exception from HRESULT: 0x800401F3 (CO_E_CLASSSTRING))
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.PowerShell.Commands.GetChildItemCo
   mmand

Any suggestions would be appreciated

A:

This is a serialization problem. New-WebSite and top-level WebSite information from the IIS:\Sites\{sitename} protocol both return objects of type Microsoft.IIs.PowerShell.Framework.Configuration. That object contains a property ftpServer; and ftpServer isn't serializable.
New-WebApplication and Sub-WebApplication information from the IIS:\Sites\{siteName}\{subappname} protocol do not have an ftpServer property. They won't have the same serialization error.
@cad's solution is great, because it prevents the remote script from returning any objects.
But, if you want to return the website information from the remote machine, you can use:
$scriptBlock = {
    Import-Module WebAdministration

    $site = Get-Item IIS:\Sites\www.sitename.com

    $site.ftpServer = $null   # this won't affect the real server value

    return $site
}

Invoke-Command -ComputerName REMOTEPC -ScriptBlock $scriptBlock

A:

I had same problem as you. I was in an iteration trying to create 16 sites. First one was being created and had same exception... exiting from iteration and leaving me with only one site created. I didn't fix it, but as a workaround I added

| out-null

at the end of the line. This suppresed output so exception was ignored and my iteration was happily continuing.
Something like:
invoke-command -computername REMOTEPC -scriptblock { import-module WebAdministration; new-item "$env:systemdrive\inetpub\testsite" -type directory; New-WebSite -Name TestSite -Port 81 -PhysicalPath "$env:systemdrive\inetpub\testsite" | out-null}

(Notice that | out-null at the end of the code snippet)


Q:

how to remove an image in an Article. OnetoOne association. What should I do in the form?

I use ->add('file','file') to add an IMAGE associated to an ARTICLE. It works just fine.
But how should I do to remove an IMAGE from the ARTICLE. the form with file only allows me to add or change the IMAGE associated with the ARTICLE. No option to simple say: remove the IMAGE.
how should I do it?

Does an option existe in File to add this fonctionality into the form?
Should I add a new field in ArticleType (mapped' to 'false' because won't be an attribut nor an entity) This field allow user to select a checkbox "remove image". And I process to the remove of the image in the controller when value is set to true?

I AM MORE ASKING FOR METHODOLOGY RATHER THAN CODE ISSUE, thanks for any help
THE CODE
class ArticleType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
       ->add('image', new ImageType());
       ->add('removeimage', 'checkbox', array(
                'label'  => 'Remove the image?',
                'mapped' => false,))
  }
}

.
class ImageType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
     $builder
        ->add('file', 'file');
  }
}

A:

If you have some time for setting up your file uploads then I recommend you  to Handle File Uploads with Doctrine . I have a working project that uses practices, described in this article, and it works really well.
If you want to make "delete" button within your form, just follow this simple steps:
first add this lines in your form builder:
->add('save', 'submit', array('label' => 'Save')) // it's for saving article
->add('delete', 'submit', array('label' => 'Delete')) // it's for deleting file

then in controller check which button was clicked:
if ($form->get('delete')->isClicked()) { // your code here }

instead of your code here write something like:
$article->getImage()->removeUpload();
$this->getDoctrine()->getManager()->flush();

That was it!


Q:

Binding list of variable-sized arrays to DataGridView

I've got a situation in which I want to populate a DataGridView from a list of arrays.  Each row contains the values of a single array.  The size of the arrays can change dynamically due to user interaction, but all the arrays in the list always have identical sizes.
I can dynamically adjust the columns of the DataGridView instance to reflect the size of the arrays, and I simply name the columns after the array indices ("1", "2", etc.).  But I need to know how to shove the actual data at the DataGridView so it can update its rows.
I understand I can use a BindingSource to act as intermediary between the data source (the list of arrays) and the DataGridView, but I don't know how to set it up to perform the necessary mapping.
Thanks.

A:

Let's assume you've got a set of arrays like this (it may differ but you should get the idea):
var row1 = new[] { "A", "B", "C" }
var row2 = new[] { "D", "E", "F" }

And so now let's build a bindable object:
DataTable table = new DataTable();
for (int i = 0; i < row1.Length; i++) { table.Columns.Add(i.ToString(), typeof(string)); }
table.LoadDataRow(row1, true);
table.LoadDataRow(row2, true);

And now let's bind the grid:
dataGridView.DataSource = table.DefaultView;


Q:

Use minimum of two threads in android?

When I was reading some posts here I noticed that android main thread is ui thread and that any long operation should be on another thread by its own
So I was wondering, if would it be a good design habit to always create two threads(at least) at for any Android app? One would be the UI thread that is used for updating UI and the other thread for any other thing
Or should I just stick with one thread and spawn a thread only when I need to (Long operation)
Thank u

A:

It is heavily depend on your application. In simple words If user feel any lag in application, then your probably need to move your work in another thread. AsyncTask make it really easy to work with thread.


Q:

SAS Proc SQL --- how to do Listagg function in SAS

Good afternoon
I am looking for listagg function on SAS by using Proc SQL.
for example
id         product_name
1001        Bananas
1002        Bananas
1002        Apples
1002        Peach
1003        Pears

proc sql;
create table work.test2 as
select id, _____(',', product_name)
from  test1
group by id
order by 1;
quit;

Result
    id          product_name

    1001        Bananas
    1002        Bananas,Apples,Peach
    1003        Pears

There is function like this in SAS?

A:

you can do
data have;
input id product_name $;
datalines;
1001        Bananas
1002        Bananas
1002        Apples
1002        Peach
1003        Pears
 ;

  data want(rename=(product=product_name));
 do until(last.id);
 set have;
 by id;
 length product $50.;
  product =catx(',',product_name, product);
 end;
drop product_name;
run;


Q:

How do I check the start time of windows/explorer from batch?

I'm attempting to get the time of when windows booted, while using batch, then change the current system time to when windows booted, execute a command, then change back to the current time.  I know how to store the current time, then using that information to change back to its original time after the commands are ran, I'm just not sure how to get the time of when Windows started, or explorer since explorer starts with windows.
Example:
'Storing the current system time so we can change back to it at the end.
FOR /F "tokens=*" %%i IN ('time /t') DO SET CurrentTime=%%i

'Change System time to when Windows booted [Not sure how to do this part]
time %WindowsBootTime%

'Run Commands

'Now change back to it's original time.
time %CurrentTime%

A:

I'm attempting to get the time of when windows booted
Use the following batch file (GetBootTime.cmd)
@echo off
setlocal
for /f %%a in ('wmic os get lastbootuptime ^| find "."') do (
  set _datetime=%%a
  )
set _boottime=%_datetime:~0,4%-%_datetime:~4,2%-%_datetime:~6,2% %_datetime:~8,2%:%_datetime:~10,2%
echo %_boottime%
endlocal

Example output:
> GetBootTime.cmd
2016-12-20 23:49

Further Reading

An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
for /f - Loop command against the results of another command.
wmic - Windows Management Instrumentation Command.


Q:

Java,Spark,Sql2o,H2: Could not acquire a connection from DataSource - IO Exception

I want to create an API using Java Maven, with Spark and H2 database and Sql2o library.
This is the full Error message:

Exceptionorg.sql2o.Sql2oException: Could not acquire a connection from
  DataSource - IO Exception: "java.io.IOException: The filename,
  directory name, or volume label syntax is incorrect";
  "C:\Users\Claudiu/reviews.db:INIT=RUNSCRIPT from
  'classpath:db/init.sql.mv.db" [90031-191]
      [qtp1133151800-16] ERROR spark.webserver.MatcherFilter -
      ro.sparkmaven.exc.DaoException: Problem adding Course
        at ro.sparkmaven.dao.Sql2oCourseDao.add(Sql2oCourseDao.java:28)
        at ro.sparkmaven.App.lambda$0(App.java:37)
        at ro.sparkmaven.App$$Lambda$1/1607460018.handle(Unknown Source)

This is the main class:
public class App
{
    public static void main(String[] args) {
        String connectionString= "jdbc:h2:~/reviews.db:INIT=RUNSCRIPT from 'classpath:db/init.sql";
        Sql2o sql2o = new Sql2o(connectionString, "", "");
         CourseDao courseDao = new Sql2oCourseDao(sql2o);
         Gson gson = new Gson();

        post("/courses", "application/json", (req, res) -> {
            Course course = gson.fromJson(req.body(), Course.class);
            courseDao.add(course);
            res.status(201);
            res.type("application/json");
            return null;
        } , gson::toJson);

        get("/courses", "application/json", (req, res) -> courseDao.findAll(), gson::toJson);

        get("/courses/:id", "application/json", (req, res) -> {
            int id;
            id = Integer.parseInt(req.params("id"));
            //TO DO: What if this not found
            Course course = courseDao.findById(id);

            return null;
        });

        after((req,res)->{
            res.type("application/json");
        });
    }
}

This is init.sql:
CREATE TABLE IF NOT EXISTS courses (
   id int PRIMARY KEY auto_increment,
   name VARCHAR,
   url VARCHAR
);

CREATE TABLE IF NOT EXISTS reviews (
   id INTEGER PRIMARY KEY auto_increment,
   course_id INTEGER,
   rating INTEGER,
   comment VARCHAR,
   FOREIGN KEY(course_id) REFERENCES public.courses(id)
);

Thanks in advance!

A:

As the exception message says, the URL is formatted incorrectly. Use a semicolon instead of a colon before INIT. The final ' is missing as well. Try:
String connectionString =
  "jdbc:h2:~/reviews.db;INIT=RUNSCRIPT from 'classpath:db/init.sql'";


Q:

How to properly spell the slang “Hé bé”?

Whilst living in France, I used 'Hé bé' a lot, although, I have never written it. I was just wondering how the French would spell it?

A:

D'un point de vue étymologique, eh/hé bien correspond exactement à ce qu'on cherche à écrire. Toutefois, si on cherche à mettre l'accent sur la prononciation plus régionale, il n'y a rien de mal à écrire hé bé, au même titre qu'on écrit (dans le cas de prononciation familière) y'a qu'à (ou même yaka), pô (Dans Titeuf, par exemple, si ma mémoire est bonne) ou encore chuis.

A:

Je l'écrirais eh bien sauf dans les contextes où on cherche absolument à marquer les variations de prononciations, alors « eh bin » est plus proche de ce que je dis que « eh bé », mais j'imagine sans mal des variations.
Note, pour moi « eh » et « hé » sont deux orthographes admissibles du même mot, certains cherchent à faire une nuance entre les deux (parfois même une différence de prononciation, [e] ou [ɛ]).  Je n'ai jamais compris quel était exactement la nuance, et j'ai l'impression que la prononciation [e] ou [ɛ] dépend plus du locuteur que d'une nuance sous-jacente.


Q:

How to set text right after textbox twitter bootstrap

I have a form elements using the following markup.. And the current look of the form you can find in the following screenshot:

How can I set the "In" and"Lbs" right after their corresponding textbox?

    Height:

        <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />In

    Weight:

        <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />

    BMI:

        <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />Lbs

    Waist:

        <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />

A:

You can use Bootstrap's input groups to attach the units to the inputs:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  Height:

      <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />
      In

  Weight:

      <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />
      Lbs

  BMI:

      <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />

  Waist:

      <input type="text" id="BI16" name="medicareNumber" class="form-control" ng-model="hraFormData.HraValuesJson.BI16" />


Q:

Is this incorrect way to implement asynchronous method

I work in LAN application, this application will receive connection from many client
in many situation, I have to ensure that the client which I try to communicate with , It's already connected before sending any data to it, so I create List of currently connected client, and a method to send "test-packet" continuously, as follows
I separate the Main UI Thread from The other's thread That I Will refer to it later
 I create public class for managing the communication process
public class Listner
{
  static TcpListener Listnerobj;
  static List<Client> Online;
  public static int port;
  public static void BeginListening()
   {
      Online = new Online(50);
      Listnerobj= new TcpListener(System.Net.IPAddress.Any, port);
      Listnerobj.Start();
      System.Threading.Thread PingerH = new System.Threading.Thread(new System.Threading.ThreadStart(PingX));
   }
}

again I created the thread PingerH to separate the main UI thread and communication process
private static async void PingX()
{
    while(_ping)
    {
        await PingAll();
        await CheckWhoAreDisConnected();
        System.Threading.Thread.Sleep(1000);
    }
}

the method PingAll Iterate Through all Online list Item and send test packet
the client will replay "just echo" the test packet and the LastPing field will be updated
the method CheckWhoAreDisConnected check for LastPing field in the Client Class
if the subtraction of DateTime.Now and LastPing is more than 200 seconds then
that client is disconnected so the CheckWhoAreDisConnected method will remove it from Online list
I create two thread,one of them check for data Avaliable in the network stream
and the other check for pending attempt from new client if(Listnerobj.Pending())
Is this Incorrect way to implement asynchronous patterns side by side with multithreading ?
generally, does the application logic is good or bad ?
Do I made a mistake?

A:

If you implement your asynchronous method correctly you don't need to run it in a separate thread. Make the return type Task as void returning async methods swallow all exceptions and are usually reserved for event handlers only. Instead of Thread.Sleep use await Task.Delay. The former blocks a thread, the later waits asynchronously without blocking a thread. For best practices, see this article.
private static async Task PingX()
{
    while(_ping)
    {
        await PingAll();
        await CheckWhoAreDisConnected();
        await Task.Delay(1000);
    }
}

I'd also change my BeginListening method to return a Task and await PingX()
public static Task BeginListening()
{
   Online = new Online(50);
   Listnerobj= new TcpListener(System.Net.IPAddress.Any, port);
   Listnerobj.Start();
   await PingX();
 }


Q:

Excel VBA type mismatch - Public Object

I am trying to read a global public Object foo. I declared it in one module and want to read it in every other module. Why do I get a type mismatch error?
Modul1:
Public Sub Test()
    If foo Is Nothing Then MsgBox "Foo is not initialized", vbOKOnly
End Sub

foo:
Public foo As Object

A:

What's happening is a phenomenon called identifier shadowing: the public variable foo exists in the same scope as the module foo.
And since Sub Test doesn't exist in the same module as the foo variable, the identifier foo in Modul1 resolves to the module foo, because it syntactically can: the syntax does not differentiate between a standard module and a class module with a VB_PredeclaredId attribute, so this:
If Foo Is Nothing Then

Is syntactically no different than:
If UserForm1 Is Nothing Then

Or:
If ThisWorkbook Is Nothing Then

VBA will always try to resolve an in-scope identifier to a module if a module exists by that name... unless it's a class module without a VB_PredeclaredId attribute, in which case it knows you can't possibly be referring to the class itself (a class is a type, not an object). Arguably VBA should be smart enough to also know that a standard module isn't an object either, but I wouldn't hold my breath for a fix ;-)

Rubberduck (disclaimer: I'm heavily involved in this open-source project) can shed more light about what's resolving to what:

You can use the Foo (the module) as a qualifier for Foo (the variable) to fix the compile error:
If Foo.Foo Is Nothing Then

This is now unambiguous, because now Foo.Foo is clearly referring to the member Foo of the module Foo.
Another (perhaps better) solution, would be to rename either the module or the variable.


Q:

How can I WPF bind dynamically created checkboxes to dynamically created series in LiveCharts?

I have a liveChart and am creating checkboxes for each item in a list.  This list also has data for each series in liveCharts.  How do I bind my dynamically created checkboxes with each individual LiveCharts.LineSeries from my data?
I've created the checkboxes:
<!-- Creating checkboxes by binding to list -->
<ListView ItemsSource="{Binding ElementItemList}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" Width="600">
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel />
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=ElementName}" />
                        <CheckBox IsChecked="{Binding Path=ElementIsSelected}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

        </ListView>

<!-- Display the chart -->
<Grid Grid.Row="1" x:Name="TestGrid"></Grid>

A:

So I assume that you want to have a CheckBox representing each LineSeries in your SeriesCollection.
So I would have two public properties, one for the SeriesCollection and the other for the list of CheckBox controls.
public SeriesCollection SeriesCollection { get; set; }
public List<CheckBox> CheckBoxCollection { get; set; }

Then following is a function that mimics dynamically creating your LineSeries and CheckBox controls since you didn't provide that code. It is important to have some sort of a connection between the CheckBox controls and your line series, and in this case I decided to set LineSeries.Title and CheckBox.Name the same.
Also note that in order to have the CheckBox do something upon checking/unchecking, you'd need to register two events for each.
public void DynamicallyCreateStuff()
{
    SeriesCollection = new SeriesCollection();
    CheckBoxCollection = new List<CheckBox>();

    var count = 3;
    var val1 = new List<double>() { 1, 2, 3 };
    var val2 = new List<double>() { 9, 5, 3 };
    var val3 = new List<double>() { 1, 4, 9 };

    for (int i = 1; i <= count; i++)
    {
        var name = string.Format("LineSeries{0}", i);

        var checkBox = new CheckBox
        {
            Name = name,
            Content = name,
            Margin = new Thickness() { Left = 8, Top = 8, Right = 8, Bottom = 8 },
            IsChecked = true
        };
        checkBox.Checked += DynamicCheckBoxChecked;
        checkBox.Unchecked += DynamicCheckBoxUnchecked;
        CheckBoxCollection.Add(checkBox);

        var lineSeries = new LineSeries
        {
            Title = name
        };
        if (i == 1)
        {
            lineSeries.Values = new ChartValues<double>(val1);
        }
        else if (i == 2)
        {
            lineSeries.Values = new ChartValues<double>(val2);
        }
        else if (i == 3)
        {
            lineSeries.Values = new ChartValues<double>(val3);
        }

        SeriesCollection.Add(lineSeries);
    }
}

In my case, I decided to have the corresponding series become visible/hidden upon clicking the CheckBox, so my check/uncheck methods look like this:
private void DynamicCheckBoxChecked(object sender, EventArgs e)
{
    ShowHideSeries(sender, Visibility.Visible);
}

private void DynamicCheckBoxUnchecked(object sender, EventArgs e)
{
    ShowHideSeries(sender, Visibility.Collapsed);
}

private void ShowHideSeries(object sender, Visibility visibility)
{
    var checkBox = (CheckBox)sender;
    var found = SeriesCollection.FirstOrDefault(x => x.Title == checkBox.Name);
    if (found != null)
    {
        var series = (LineSeries)found;
        series.Visibility = visibility;
    }
}

I didn't use a ViewModel in order to save time and for the sake of simplicity, so my MainWindow constructor looks like this:
public MainWindow()
{
    InitializeComponent();
    DynamicallyCreateStuff();
    DataContext = this;
}

And XAML is pretty bare bones here:
<Window x:Class="SOLineCharts.MainWindow"
        ....
        xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ItemsControl Grid.Column="0"
                      ItemsSource="{Binding CheckBoxCollection}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Vertical" ScrollViewer.HorizontalScrollBarVisibility="Disabled"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
        <lvc:CartesianChart Series="{Binding SeriesCollection}" Grid.Column="1"/>
    </Grid>
</Window>

Result:
Upon loading:

Unchecking one check box:


Q:

Transform HashMap to HashMap>()

I have this code,
ArrayList<HashMap<String, String>> eventosList;

     HashMap<String, String> contact = new HashMap<String, String>();

                            contact.put("id", id);
                            contact.put("name", name);

eventosList.add(contact);

Is it possible to transform this HashMap<String, String> contact to HashMap<String, List<String>>() contact? How can I do this? Thank you so much

A:

Try like this:
ArrayList<HashMap<String, List<String>>> eventosList = new ArrayList<HashMap<String, List<String>>>();
HashMap<String, List<String>> contact = new HashMap<String, List<String>>();

List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
contact.put("id", list);
List<String> list1 = new ArrayList<String>();
list1.add("Mohammed");
list1.add("Ali");
contact.put("name", list1);
eventosList.add(contact);

Also Note as given here: List is an INTERFACE, and you cannot Initialize an Interface, so use any of its implementing classes like Arraylist, Vector, LinkedList, AbstractList, AbstractSequentialList, AttributeList,  etc, to initialize it.


Q:

Add a additional condition to Case Statement in Switch

Is it possible to add a additional Condition to Switch Statement like below in C#
switch(MyEnum)
{
  case 1:
  case 2:
  case 3 && Year > 2012://Additional Condtion Here
       //Do Something here..........
      break;
  case 4:
  case 5:
       //Do Something here..........
      break;
 }

In above mentioned example if MyEnum = 3 then it has to be excuted if Year > 2012... Is it possible?
[EDITED]
Year > 2012 is not applicable to case 1 & case 2.

A:

C#7 new feature:
case...when
https://docs.microsoft.com/hu-hu/dotnet/articles/csharp/whats-new/csharp-7
public static int DiceSum4(IEnumerable<object> values)
{
    var sum = 0;
    foreach (var item in values)
    {
        switch (item)
        {
            case 0:
                break;
            case int val:
                sum += val;
                break;
            case IEnumerable<object> subList when subList.Any():
                sum += DiceSum4(subList);
                break;
            case IEnumerable<object> subList:
                break;
            case null:
                break;
            default:
                throw new InvalidOperationException("unknown item type");
        }
    }
    return sum;
}

A:

In order for it to work the way you've indicated with the fallthrough logic for 1 and 2, I'd suggest moving the //do something here portion out to a method or function and then doing this:
  case 1:
  case 2:
      DoSomething();
      break;
  case 3:
      if(Year > 2012) { DoSomething(); }
      break;

The other alternative would be:
  case 1:
  case 2:
  case 3:
      if (MyEnum != 3 || Year > 2012) {
         // Do something here
      }
      break;

but I think the first option is much more intuitive and readable.

A:

The answer is no.
You'll need the following:
switch (MyEnum)
{
   case 1:
   case 2:
       DoSomething();
       break;
   case 3:
       if (Year > 2012) DoSomething();
       break;
}


Q:

What will be the equivalent of following code in kotlin?

Here is a Java code I found in a library and I am using kotlin. But I yet don't know how to convert it to kotlin.
  myWebView.setWebChromeClient(new WebChromeClient() {

    @Override
    public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

        return true;
    }
}

A:

myWebView.setWebChromeClient(object : WebChromeClient() {
            override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
                return true
            }
        })


Q:

Pythons fetchall eats all my swap memory

I'm executing a query on a table where I get a column with some hundred million rows back, this is because I want to plot them in a histogram. The problem is that this eats up nearly all my memory (7.8 gb) and all my swap memory (8gb) before the program exits with exit code -9 before cur.fetchall() is done.
How can I prevent this from happening? Should I sort my column first, then do several queries on chuncks of it - or is there maybe a better way to fetch the data in my query? The cur.execute itself takes almost no time.
#!/usr/bin/python

import sqlite3 as lite
import numpy as np
import sys
import os
import matplotlib.pyplot as plt

def getQuantity(databasepath):
    con = lite.connect(databasepath)
    binwidth = 1
    start = time.time()
    with con:
        cur = con.cursor()
        cur.execute('SELECT latitude FROM MessageType1')
        con.commit()
        latitudes = cur.fetchall() #Breakdown here
        latitudes = [x[0] for x in latitudes]
        plt.hist(latitudes, bins=range(int(min(latitudes)), int(max(latitudes)) + binwidth, binwidth))
        plt.title("Bucket size: " + str(binwidth))
        plt.ylabel("Number of message")
        plt.savefig('latlongstats'+'t'+str(time.strftime("%H:%M:%S")), format='png')

if __name__ == "__main__":

    getQuantity('database/database.db')

A:

I found that if I replaced the following:
    latitudes = cur.fetchall()
    print "fetched"
    latitudes = [x[0] for x in latitudes]

with:
    while True:
        tmp = cur.fetchone()
        if tmp != None:
            latitudes.append(tmp[0])
        else:
            break

I got the same result, allthough it takes forever, and only nearly eats up my ram (but not my swap).


Q:

ConcurrentModificationException on iteration through list, synchronized and using iterators

How is it possible to get a ConcurrentModificationException for this code-block?
synchronized (list) {
        for (Iterator<?> it = list.iterator(); it.hasNext(); ) {
            Object object = it.next();
            // do something to object without touching list
        }
}

Edit: sorry, that was not specific enough: // do something to object does not touch the list

A:

By having another thread modifying the list, for example.
Just because you synchronize this code block doesn't mean all the accesses to the list are blocked. It only makes sure that all the other blocks synchronized on the list can't execute in parallel.
If the list is shared by several threads, all its usages must be synchronized on the same monitor.


Q:

Can I create a polymorphic key from a custom object?

I'm creating a custom object that needs to be related to multiple other objects (but only one per record). I.e. via a ParentId field it could be related to a Opportunity, a Contact, an Account, or another custom object.
This would be pretty much the same as the Polymorphic Key Attachment.ParentId that can reference multiple other object types.
I can't do this via the UI as the lookup can only be related to a single type.

Is it possible to create a polymorphic reference through another means, such as the metadata api?
Failing that, are there any viable alternatives?
I'd like to use the lookup so I can show the related objects via the page layouts. This object will also be deployed as part of a managed package and clients may want to reference their own custom objects from it.

A:

As of now, polymorphic keys only exist as standard fields. See the idea - Custom Polymorphic Id field (WhoId/WhatId)
To mimic the functionality by say using a custom text field, would be a rigorous customization:

Custom text field, mark as ExternalId for indexing purpose.
UI control...probably would have to be custom visualforce + apex controller.
Related Lists...again, custom visualforce + apex controller.
Probably some other stuff I can't think of right now, but that would be the minimum as I envisage it.


Q:

How can I find out how much a dealer would really pay for my car?

I need to sell a car.
I want to sell it to a dealer.
I checked the estimated price on Kelly Blue Book, edmunds.com, and clearbook.com. According to those sources, it's worth somewhere around $23,000 to $24,000.
I also searched for similar cars for sale on autotrader.com, cars.com, carmax.com, and Kelley Blue Book used car search. It's difficult to find an apples-to-apples comparison because there aren't a lot of late-model single-owner Murano SLs in perfect condition with less than 10K miles on the market. I found an SV (a lower trim line) being offered in my area for close to $27,000.
I've presented the car to two local Nissan dealers. One offered $21,000 and the other, upon hearing about that, offered $22,000.
I strongly suspect that the actual maximum amount they would be willing to give me for the car is higher.
The question is, how can I discover what that amount is?

A:

So far you have two quotes. The difference between the 27K you saw advertised and the highest amount you were offered (22k) is to cover the dealers overhead, expenses, and profit.
Can you do better? Nobody can know. If there is a glut of cars like yours the amount they will offer you is lower because they don't need more cars like yours. Remember glut is relative. If they have 3 cars and only sell one a quarter they don't need yours. If they sell 3 a week and only have 5 left they are looking to buy more.
You have to decide what the minimum you want or need to take. Then you keep trying to find a buyer; sell it on your own; or drop your price.
One other thing with a new car dealer: if you are selling a car only, then you are only a partial customer. They also make money from selling cars and making loans on cars. When somebody does all three it can be very hard to get the true amount they received from the trade-in, because the dealer is working all three numbers.
You might get a better price from a dealer who sells mostly used vehicles. The regular dealer gets most of their used cars in trade-ins and end of lease events.


Q:

VACUUM sqlite database from the SQLiteOpenHelper

My app's database keeps growing and I want to perform a VACUUM to retrieve some lost space. From what I've read VACUUM does not run if there are other transactions.
My question is: how do I run the command from my SQLiteOpenHelper? is something like db.execSQL("VACUUM") work? But how do I get some sort of progress while doing this so I can block the UI with a loading dialog?

A:

You can run VACUUM like any other SQL commands; execSQL() will work.
However, there is not mechanism to track the progress.
And SQLite automatically reuses free pages, so VACUUM is unlikely to help. (It is useful only if you have deleted a large amount of data, and know that you will not insert new data again.)


Q:

What is the batch script equivalent for the following OS X batch script iterating installed fonts?

I am trying to make use the answer given here. What is the batch script equivalent for the following OS X batch script iterating installed fonts?
for F in /Library/Fonts/*.ttf
do
   FONT=`basename "$F" .ttf`
   xelatex "\def\myfont{$FONT}\input{handout.tex}"
   mv handout.pdf "$FONT".pdf
done

A:

Excluding xelatex, that is not part of the base OS, the rest of the script could be
for %%f in ("%systemroot%\Fonts\*.ttf") do (
    echo full path to file          : %%~ff
    echo name and extension of file : %%~nxf
    echo only name of file          : %%~nf

    rem xelatex "\def\myfont{%%~nf}\input{handout.tex}"
    rem move handout.pdf "%%~nf.pdf"
)


Q:

What kind of tree is this and what's wrong with it?

The developer in my neighboorhood was so kind as to plant trees in everyone's yard.  But after 3 or 4 years all but one or two (so probably 180 or so) look scrawny and pathetic.  I know nothing of horticulture, so I was wondering if  anyone knows what kind of tree this is.  Also, it looks like it's diseased as do all of the others.  Is there a way to fix this, or are they all doomed to be terrible?

A:

This is definitely an Acer, but what you're seeing there is a case of Rhytisma acerinum, commonly known as Tar Spot of Acer, or Acer Leaf Spot. It's a fungal infection, and in the UK, there is no effective fungicide treatment available, though you may find there is something you can use where you are.
This infection doesn't kill the tree, but it can make it look unsightly (as you've discovered). Some control can be effected by removing fallen leaves, particularly in Fall, because the spores over winter on the leaves. Removing the worst affected leaves might help, but I'm not convinced it makes any difference other than to reduce the aesthetic effect a bit.
UPDATE: Regarding sun burn from water spots, this isn't possible. I was shocked when I found out it was a myth, been warning people about it for years, but the original tests for this theory were performed with water droplet sized glass placed on leaves - the leaves burned. But when the same tests were performed with real water droplets, on both smooth and non smooth leaves, no damage could be reproduced. Water droplets have a different refractive index from glass, and don't maintain their shape, which isn't true of glass droplets - the water also cools the leaf surface generally. Further, I've tested it myself when the temperature on my very sheltered balcony has been 55 deg C in direct sun by placing droplets on a Foxglove leaf, which is ridged and not smooth. No damage resulted. Reference: www.AmericanScientist.org/issues/pub/sunburned-ferns.
UPDATE: Laughing-Jack may well be right when he mentions Phyllosticta - I jumped to Tar Spot, but actually, looking at it again, it might not be, but I'm 100% convinced this IS a fungal leaf spot - whether its phyllosticta or another type. I suggest you check to see if there are any fungal sprays or treatments you can use in your area - the UK is very short on effective anti fungal treatments, but maybe its better there. Point given, LaughingJack, though I'm not sure that counts for a comment - post as an answer!

A:

That is a Red Maple, Acer rubrum. The damage resembles fungal leaf spot.
They were obviously planted at near the same size they are at now. They were probably 5-7 years old at planting, and planted as a balled and burlapped tree. You can see the last year of growth from when they were at the nursery. It is about the top 1/4-1/5 of the tree. When a tree growing that fast is dug, more than half of the root system is removed. If the top isn't pruned properly, the plant will not be able to grow well, and will only put out leaves with very little terminal growth.
Cases like this are very common where I live. Here's what you can do:

Prune the whips of the last nursery-years growth by about two-thirds. This will put the tree back into (somewhat) proportion root-wise. Always cut back to a comparatively healthy outward facing twig/growth bud.
Start giving some growth stimulaters. The tree hasn't got many roots in the lawn, which obviously has had some nitrogen. Use a balanced, but fairly high nitrogen slow release fertilizer. This will give the tree something to build with.
Again, the tree doesn't have a great root system. Water very deeply if the ground has been dry for two weeks or more. If it doesn't rain, water deeply only once per week. If the ground is constantly moist, the tree will grow a shallow root system.
You should be able to easily see the root flare of a tree. Pull the mulch/soil away from the base of the tree until you find where it widens, and lateral roots appear. When a tree is planted too deeply, the roots will start circling the trunk of the tree, and can cause lots of damage that way. This is one of the biggest problems I run into on new properties that had a less than ideal landscaping job. Keep the mulch a couple inches from the trunk.
Stake you're tree. The tree will benefit from some support, as rocking at ground level will cause major root severing and will greatly set back even an otherwise healthy tree. I would use two 6' 2x2" stakes, pounded at least 18 inches into the ground, placed opposite each other, with the tree directly centered. Do not pound the into the root ball. The edge of the mulch should be fine. Use wire to hold the tree up, but allow some play. Measure the distance between the stake and the tree, and multiply that by 21/2 times, for your wire length. Put some form of padding in the center to protect the trunk. I use 8" pieces of cut hose. Put the wire in place and wind the ends around the stakes. You can tighten these by inserting your pruners or similar between the wire strands and spinning.

A:

I believe this is Acer rubrum.  Red Maple.  There are a couple of things you should check:

How deep this tree was buried.  A very common contractor thing. Make sure that the bark is out of the soil and mulch.  Only the roots should be buried. Your picture tells me the mulch is up too high on the bark of this tree.  Pull it away, 6" or more.  Moisture being held next to the bark of woody plants will encourage bacteria.  They will kill the vascular system within a year or two.
Have you ever fertilized this tree?  Your tree and lawn shows nutrient deficiency.  Contractors pretty much strip the good soil away and you need to get organic matter into your soil. Fertilizer alone won't work. Get decomposed organic matter and spread 1/2" over your lawn, aerate (pull soil plugs out of lawn and allow to disintegrate), get rid of the chunky wood  mulch around the tree and elsewhere.  Use Dr. Earth's Lawn Fertilizer...incredible stuff. Also puts bacteria into your soil. Get mycorrhizal fungi to add to your soil.  It might come in that fertilizer, I know soil bacteria is added.  If not, you can get it separately.
Don't worry about the spots on your leaves.  It is fungus and the plant itself, is killing the infected tissues causing the spots.  Don't water late in the day or at night.

The best mulch is human poo mixed with sawdust.  Completely decomposed, it won't smell the same, it is a fine-textured dark taupe, no rocks, no weed seeds, no pesticide residues and no funky smell! Completely different product!  If you can find this stuff, use it on your lawn, all your plant beds.  I wouldn't even weed.  Just put this on your lawn (1/2") and 2" on your plant beds.  For shallow rooted plants like rhododendrons, azaleas, daphne...only 1" around their drip line.  Keep away from the base of trees, shrubs.  Not recommended for vegetable gardens as a little high in heavy metals.
Mow your lawn no shorter than 3".  Trust me, try this.  When you water, water deep!!! 4 - 6"!!! Then allow soil to dry out.  Your footprints should be clear when you step on the grass.  The blades don't bounce back up.  Then! Water deeply. Check the depth.  If you are watering everyday, your lawn, your plants, your tree have shallow roots and are stressed and are in danger of dying.  You will actually save money watering this way. Mow once a week or twice is better.  Sharp blades! No shorter than 3"....no shorter than 3". Aerate once a year.
Ideally, we treat plants separately from lawn.  This tree should thrive taking care of your lawn correctly.  Get a test of the pH of your lawn. It should be 6.5-7.0.  If not, apply lime but stay away from the drip line of your tree.  It likes slightly more acidic than a lawn.
This should get your tree growing and your lawn lush.  Let us know what you decide and send another picture, same spot, taken a couple of months from now?


Q:

Porting some Processing code to Eclipse, getting slew of errors

I'm making an Android app using Processing, and have decided to port my code to Eclipse. I guess there are a lot of differences between Processing and pure Java, because right off the bat I am getting errors that make little sense to me. For example:
int inactiveThreshold = 300 + int(random(-100, 100));

int randomPointInterval = int(random(300, 500));

I get the error "Syntax error on token "int", delete this token"
As for the random function, I extend PApplet and have imported processing.core.* so I don't see why that wouldn't work properly.
Also getting errors on anything referencing a color that I created:
back.drawBackground("shadow", backgroundColor);
back.drawBackground("front", backgroundColor);

"Color cannot be resolved to a type", despite initializing backgroundColor as an integer:
int backgroundColor = color(100, 100, 120);

There's also a function in the main class that handles mouse movement, and when I make a reference to it says that the function is undefined.
These errors are just in the main class, so I figured I should tackle that before anything else. I've mainly been following this for porting the code:
http://www.learningprocessing.com/tutorials/processing-in-eclipse/
I haven't done much in pure Java so there are probably a lot of differences that Processing's precompiler handles that I'm not noticing.

A:

For int casting: do
int i = (int)(valueToCase);

For randoms:
java.util.Random rand = new java.util.Random();
// can't do random(min,max) - instead, do
int randNum = rand.nextInt(max-min) + min;

Any time you see java.blah.ClassName, you can do this so it's not cluttered with java.blah qualifiers.
import java.blah.ClassName;

    ClassName cn = new ClassName...


Q:

How to involve a variable in numerical integration?

Now I have two functions f[x] and g[x] which both contains another variable a, or we can note as f[a,x] and g[a,x]. Now I need to solve the equation
Solve[Integrate[f[a,x],{x,0,2Pi}]==Integrate[g[a,x],{x,0,2Pi}],a]
to solve the value of a, however, f and g are both hard to do an analytical integral. So now I have to use NIntegrate instead, but the NIntegrate function seems cannot contain a variable a in it.
What can I do to solve the a?
Update:
 I can show the example of f[x] and g[x] as follow.
f[abratio_] :=
  Integrate[(\[Zeta]1[\[Theta]] \[Zeta]2[\[Theta]] Cos[\[Theta]]^4)/(
   DD[\[Theta]] (abratio^2 Cos[\[Theta]]^2 + Sin[\[Theta]]^2)^(3/
       2)), {\[Theta], 0, 2 Pi}];
g[abratio_] :=
  Integrate[(\[Zeta]1[\[Theta]] \[Zeta]2[\[Theta]] Cos[\[Theta]]^2 \
Sin[\[Theta]]^2)/(
   DD[\[Theta]] (abratio^2 Cos[\[Theta]]^2 + Sin[\[Theta]]^2)^(3/
       2)), {\[Theta], 0, 2 Pi}];

or
$$f(a)=\int^{2\pi}_0 \frac{\zeta_1(\theta)\zeta_2(\theta)\cos^4(\theta)}{DD(\theta)[a^2 \cos^2(\theta)+\sin^2(\theta)]^{3/2}}d\theta $$
$$g(a)=\int^{2\pi}_0 \frac{\zeta_1(\theta)\zeta_2(\theta)\cos^2(\theta) \sin^2(\theta)}{DD(\theta)[a^2 \cos^2(\theta)+\sin^2(\theta)]^{3/2}}d\theta $$
where $\zeta$ and DD are other functions about $\theta$.

A:

If you define the functions f[a] and g[a] to be only defined for numerical input, like:
f[abratio_?NumericQ] :=
  Integrate[(\[Zeta]1[\[Theta]] \[Zeta]2[\[Theta]] Cos[\[Theta]]^4)/(
   DD[\[Theta]] (abratio^2 Cos[\[Theta]]^2 + Sin[\[Theta]]^2)^(3/
       2)), {\[Theta], 0, 2 Pi}];
g[abratio_?NumericQ] :=
  Integrate[(\[Zeta]1[\[Theta]] \[Zeta]2[\[Theta]] Cos[\[Theta]]^2 \
Sin[\[Theta]]^2)/(
   DD[\[Theta]] (abratio^2 Cos[\[Theta]]^2 + Sin[\[Theta]]^2)^(3/
       2)), {\[Theta], 0, 2 Pi}];

Then you can numerical solve for a using FindRoot:
FindRoot[f[a]==g[a], {a,a0}]

where a0 is an initial numerical guess for a.


Q:

Typespec declaration for a passed function's return value

So let's say that I have a function like this:
def something(callback) do
  case *some condition* do
    0 ->
     :ok
    1 ->
      {:error, :foo}
    _ ->
      callback.()
  end
end

where the callback function can return either :ok or {:error, *some atom*} where some atom is an unknown atom.
Now, I am wondering if there is a way to write the spec for the something/1 function that doesn't use the general atom spec. So, the question is, basically, if there is a way to write a more specific typespec than this:
@spec something(() -> :ok | {:error, atom}) :: :ok | {:error, atom}

Instead, I would like my spec to show that something/1 function can return :ok, {:error, :foo} or the value returned by callback
PS I know that this kind of thing doesn't' matter on the practical level so it's just a question based on curiosity.

A:

You're looking for type variables. Erlang does support declaring them but dialyzer does not seem to be doing any checks based on these types at the moment (Erlang/OTP 20).

Type variables can be used in specifications to specify relations for the input and output arguments of a function. For example, the following specification defines the type of a polymorphic identity function:
-spec id(X) -> X.

The type signature you want is:
@spec something(() -> t) :: :ok | {:error, atom()} | t


Q:

Python: Revealing a word for Hangman (Strings, replace, index, and strip)

lets say I have the word: "Pizza"
sAnswer = "Pizza"
sReveal = len(sAnswer)* "_ "

Above I've built a string that'd display "_ _ _ _ _ "
Like any other Hangman game it would contain underscores my problem is: How do I strip the sReveal of spaces, find the index of the letter guessed (example: 'z') and then replace the underscores with z's where necessary and then rebuild the spaces in between, therefore it would become: "_ _ z z _ "
I've tried something like this to no avail:
if sLetterGuessed in list(sAnswer):

    for character in list(sAnswer):
        index = sAnswer.find(sLetterGuessed)
        sReveal = sReveal.replace(" ", "")
        list(sReveal)[index] = "z"

        print sReveal

        for char in sReveal:
            sReveal = sReveal.strip(" ")
            sReveal = sReveal.replace("_", char)

    print sReveal
    print HangingMan[iErrors]

## The code is just consideration of the route I'm taking with this; the horrible route.

A:

An easy way to update sReveal is use a list comp and str.join:
sAnswer = "Pizza"
sReveal = len(sAnswer)* "_ "
letter_guessed = "z"
# if letter_guessed == current letter in word, add that letter else add a _
sReveal = " ".join([x if x==letter_guessed else "_" for x in sAnswer ])
print(sReveal)
_ _ z z _

An old hangman game I had to do for a course might be useful:
def hangman(secret_word):
    from string import ascii_lowercase
    print ("Welcome to Hangman!")
    print ("I am thinking of a word that is {} letters long\n-----------".format(len(secret_word)))
    guesses = 8
    letters_guessed = []
    missed_l = ''
    correct_l = ''
    secret_word = secret_word.lower()
    while True:
        # if all the letters in secret_word are in correct_l , the user has won
        if all(x in correct_l for x in secret_word):
            print ("Congratulations, you won!")
            break
        # if len missed letters is 8, user has used up all guesses so break/end teh game
        elif len(missed_l) == 8:
            print ("Sorry, you ran out of guesses. The word was {}.".format(secret_word))
            break
        print ("You have {} guesses left".format(guesses))
        print ("Available Letters: {}".format(" ".join([x for x in ascii_lowercase if x not in letters_guessed])))
        guess = raw_input("Please guess a letter: ").lower()
        # if guess in letters_guessed  user has already guessed that letter
        if guess in letters_guessed:
            print ("Sorry You've already guessed that letter: {}\n-----------".format(guess))
        # else if it is in the word, add  guess to correct_l and to letters guessed
        elif guess in secret_word:
            letters_guessed.append(guess)
            correct_l += guess
            print("Good guess: {}\n-----------".format(" ".join([x if x in letters_guessed else "_" for x in secret_word])))
        # if users guess is not in the word, minus a  life/guess
        elif guess not in secret_word:
            letters_guessed.append(guess)
            guesses -= 1
            print (" That letter is not in my word: {}\n-----------".format(" ".join([x if x in letters_guessed else "_" for x in secret_word])))
            missed_l += guess


Q:

how to divide the sum of a groupby value with the count the another value

I wanted to groupby by 'label' and 'month' to sum the Quantity sold for each month and for each label.

I am trying to do 'groupby and apply' method for achieving this, but not sure how to count the month for each label. Say, for label value AFFLELOU (DOS), I have two values for 7th month. so, I should sum the quantity sold and divide by 2.
for 9th and 10th month, I just have one value, so the count would be 1 and it would divide the quantity sold.
I wrote the code below, but it doesn't take count as a function and return count not defined error.
t1.groupby(['label', 'month']).apply(lambda x: x['Quantity sold']
.sum()/count('month'))

Can someone tell me how to get the count value of each month for each label?
Thanks in Advance.

A:

Instead of summing, counting and dividing, you could use agg('mean'):
t1.groupby(['label', 'month'])['Quantity sold'].agg('mean')

Or, if you do wish to retain the sum and count, use:
t1.groupby(['label', 'month'])['Quantity sold'].agg(['sum', 'count', 'mean'])

For example,
import numpy as np
import pandas as pd

t1 = pd.DataFrame(np.random.randint(4, size=(20,3)), columns=['label', 'Quantity sold', 'month'])
t1.groupby(['label', 'month'])['Quantity sold'].agg(['sum', 'count', 'mean'])

yields a DataFrame like
             sum  count  mean
label month
0     1        2      1  2.00
      2        0      1  0.00
      3        2      2  1.00
1     1        1      2  0.50
      2        3      1  3.00
      3        1      1  1.00
2     0        0      1  0.00
      1        0      3  0.00
      3        5      4  1.25
3     0        1      1  1.00
      1        0      1  0.00
      2        0      1  0.00
      3        3      1  3.00

Using groupby/agg with its builtin aggregators sum, count and mean is clearly more convenient here, but if you did need to use groupby/apply with a custom function you could use:
t1.groupby(['label', 'month']).apply(lambda x: x['Quantity sold'].sum()/len(x))

Note that while calling custom functions with groupby/apply gives you more flexibility, it comes at a cost because calling a custom Python function once for each group is generally slower than calling the builtin Cythonized aggregators available in groupby/agg.

If you have missing (NaN) values in Quantity sold, it may help to know that group/agg has both 'count' and 'size' aggregators:

'count' returns the number of non-NaN values
'size' returns the length of the group (including NaN values)

The count is always less than or equal to the size. The mean is the sum (of the non-NaN values) divided by the count. To see the difference between count and size, you could experiment with this code:
np.random.seed(2018)
t1 = pd.DataFrame(np.random.randint(4, size=(50,3)), columns=['label', 'Quantity sold', 'month'])
t1.loc[np.random.choice([True, False], len(t1)), 'Quantity sold'] = np.nan
t1.groupby(['label', 'month'])['Quantity sold'].agg(['sum', 'count', 'size', 'mean'])

which yields
             sum  count  size      mean
label month
0     1      0.0      0     3       NaN
      2      6.0      2     2  3.000000
      3      0.0      0     1       NaN
1     0      3.0      2     5  1.500000
      1      0.0      0     1       NaN
      2      5.0      3     5  1.666667
      3      0.0      2     3  0.000000
2     0      7.0      3     5  2.333333
      1      4.0      4     8  1.000000
      2      5.0      2     3  2.500000
      3      5.0      2     3  2.500000
3     0      1.0      2     5  0.500000
      1      3.0      1     1  3.000000
      2      2.0      1     2  2.000000
      3      2.0      1     3  2.000000


Q:

Outrigger and/or leeboard when sailing a canoe?

I have been considering adding a sail to my open 17 foot Coleman canoe.  Browsing images on the internet show pretty much every imaginable configuration but they all share 3 or 4 combinations of outrigger and/or leeboard.

Neither, typically seen with small sails and or low budget rigs going down wind only.
Outrigger only, typically seen on canoes with and without sails.
Leeboard only, typically seen on mid-range to high performance rigs.
Outrigger and leeboard, occasionally seen in all ranges.  Seems to be the least photographed and posted option.

On browsing the web, everyone seems to think their choice is the best, so I am having difficulty assessing the pro and cons of each choice.  What should I consider when designing my canoe sailing solution as it relates to outriggers and leeboards?
My current plans are limited to inland water ways (rivers) but you never know where the next adventure will take you so, considerations for all types of water would be appreciated.

A:

I looked into this a while ago when I was planning on making my own sailing rig for my canoe. The answer largely depends on the size of your sail, and whether or not you have a prominent keel, but if you want to put your paddle away and actually sail your canoe, then you need both a outriggers and leeboards.
I've been looking at getting this kit for my 17.5' Clipper Tripper for some time now:

Considering how light canoes are, and how easy they are to tip, I think both outriggers and leeboards are pretty much essential for beginner canoe sailors. With some skill and experience you may be able to go without one or the other, but you're definitely going to have a much easier time with both.

A:

The right way to view the pros and cons is to understand the basic mechanics of how a sailboat works, so you can decide what's appropriate for your situation.
The first thing to be aware of is that unless you only ever sail straight downwind, then sails don't work like parachutes, they work like airplane wings. The motion of the air over the shape of the sail generates a force which can be used to propel the boat. In addition to that force generated, the air generates two forces that must be resisted: the force of the wind trying to blow the sail over and heel or capsize the boat, and the force to push the boat sideways.
Resisting the sidways force is addressed in most boats with a hydrodynamic element called a keel, which shares the same name as the structural element of the boat, and includes weighted keels, centerboards, daggarboards, leeboards, and others. Leeboards are popular with sailing canoes, because they don't requite much if any special built provisions in the canoe, and they don't increase the draft of the boat.
Resisting the heeling force is usually handled by ballasting the boat, either lead in a fin keel, water ballast in trailerable weekender type sailboats, or the body mass of the crew on smaller boats. On many small racing sailboats, the crew of the boat hangs out off the edge of the windward side to balance the powerful force of the air on the sails. As canoes are not really meant to handle sideways loads and can easily tip, this makes an outrigger of some sort usually necessary.
Now, you could make an outrigger to address both those forces, by designing one with a shape to resist the lateral motion. This can work, and there are boats that have that, such as a Hobie 16 which has no daggerboards and instead has asymmetric hulls, but there are some trade-offs. The shape has a less than ideal cross section for buoyancy, so it will have greater drag than a 'plain' outrigger and a centerboard. Additionally, they will be much more difficult to turn than the alternative. The Hobie 16 example, turns very poorly compared to other sailboats. However, in the case of the Hobie 16, both of those trade-offs are worth it because the lack of centerboards means you can ride right up onto the beach without risking damage to your boat if you don't pull up the boards in time.
In this image of a racing Hobie 16, you can see the crew trapezed out to control the heel of the boat, and you can see the shape of the hull, it's nearly flat facing the water, to resist the sideways force of the wind. The other hull in the water is a mirror image of the starboard hull.

Ultimately, every element of boat design is a trade-off of some sort. As you make adjustments for better and better sailing performance, your result will start looking less and less like a canoe and more like a traditional sailing boat. Only you can decide where there right balance is.

A:

I sail about everyday. In bay water.
Outrigger is nice to keep from tipping. But sailing up wind and to stop the sideways slippage you need a leeboard. And fill your pvc out rigger with foam you will just make it heavy. If you must do that use empty soda bottles.  I sail with out Lee board when conditions are right. But in order to tack I have to shift my weight forward to the mast. Just gotta learn your boats balance. P.s. with all that rigging use a telescopic fishing rod.save space.


Q:

how to install GnuPG::Interface perl module on windows?

When I try to do this : cpan install GnuPG::Interface
either on Strawberry or Activeperl ( windows ) I get this error :
I use last perl version available 5.26.1.1
CPAN: File::Temp loaded ok (v0.2304)
CPAN: YAML::XS loaded ok (v0.66)
CPAN: CPAN::Meta::Requirements loaded ok (v2.140)
CPAN: Parse::CPAN::Meta loaded ok (v2.150010)
CPAN: CPAN::Meta loaded ok (v2.150010)
CPAN: Module::CoreList loaded ok (v5.20170821)
Configuring A/AL/ALEXMV/GnuPG-Interface-0.52.tar.gz with Makefile.PL
which gpg ... 'which' is not recognized as an internal or external command,
operable program or batch file.
gpg (GnuPG) not found at Makefile.PL line 7.
 Warning: No success on command[C:\Perl64\bin\perl.exe Makefile.PL INSTALLDIRS=si
te]
   ALEXMV/GnuPG-Interface-0.52.tar.gz
   C:\Perl64\bin\perl.exe Makefile.PL INSTALLDIRS=site -- NOT OK

Any tip ? Im actually trying to install Mail::GnuPG but GnuPG::Interface is required.
thank you

A:

This line in Makefile.PL:
system("which", "gpg");
die "gpg (GnuPG) not found" if ( $? != 0 );

is attempting to check if gpg exists in your %PATH% but since you do not have the standard *nix utility which, it fails. You can install Perl's App::pwhich and replace that line with system("pwhich", "gpg"); if you want or, if you know that gpg is in your %PATH%, delete that line from Makefile.PL entirely.
Alternatively, you can install Git for Windows which will provide both which and gpg along with perl 5.24.1.
If one were to rewrite this Makefile.PL from scratch, I would recommend using File::Which to check for all locations on your %PATH% where a gpg executable exists.


Q:

PHP Form Insertion Into Specific Table Within Db

I'm new to php form insertion and can't seem to find an answer to my specific issue. I'm able to send the name/email to a database, however I need to specify the input table in order to keep it more organized. With my current setup, I only know how to create new databases for each product giveaway, but I'm sure there is a better way than that.
Here is my current php code, please keep in mind I'm two weeks into php! If you could specify where I need to enter anything that would help a lot.
<?php

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
mysql_connect("localhost","username","password");//database connection
mysql_select_db("myusername_mytable");

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

            include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';

            $securimage = new Securimage();

if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
  // you should handle the error so that the form processor doesn't continue

  // or you can use the following code if there is no validation or you do not know how
  echo "The security code entered was incorrect.

";
  echo "Please go back and try again.";
  exit;
}

// Get values from form

$name = $_POST['name'];
$email = $_POST['email'];

//inserting data order
$order = "INSERT INTO user_info
       (name, email)
      VALUES
       ('$name','$email')";

//declare in the order variable
$result = mysql_query($order);

        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // show a message of success and provide a true success variable
        $data['success'] = true;
        $data['message'] = 'Registration Complete!';
    }

*********UPDATE***********
Turns out I was using deprecated language, so I switched to PDO. Thank you all for the help!
IF any other newbies were wondering with the previous form, I was missing an incredibly easy fix where it says $order = "INSERT INTO user_info which was the table name!

A:

Firstly, you need to be using the MySQLi or PDO libraries, which are more secure than the now deprecated mysql_ library.
Assuming you want to store information on the giveaway and the entrants, you can create a single database with two tables, entrants and giveaways.
Give giveaways the structure of
id int primary key auto_increment
name varchar(100),
start_date datetime
end_date datetime

and entrants the structure of
id int primary key auto_increment
giveaway_id int //this is a foreign key linking the entrant to the relevant giveaway
email varchar(100),
name varchar(150)

With that in mind, let's have a look at your code:
//setting your arrays for later
$data = array();
$errors = array();

//checking your posted data values
if(empty($_POST['name'])) $errors['name'] = "Name is required.";
if(empty($_POST['email'])) $errors['email'] = "Email is required.";

//find out if we had any errors
if(!empty($errors)) {

    //if we did, then we return them
    $data['success'] = false;
    $data['errors'] = $errors;

} else {
    //and if we didn't, continue

    $sql = new MySQLi(/*your host, username, password and database name here */);

    if($sql->connect_error) {
        //if we can't get a connection to the database, kill the script and print out a handy message
        die("Connection error: ".$sql->connect_error." ".$sql->connect_errorno);
    }
}

//get your securimage script
include_once($_SERVER['DOCUMENT_ROOT'].'/securimage/securimage.php');
if ($securimage->check($_POST['captcha_code']) == false) {
    //do some error handling for the captcha checking
    echo "The security code entered was incorrect.

";
    echo "Please go back and try again.";
    exit;
}

//did all that work? Awesome, let's continue

//ALWAYS escape your form data. It's not a sure win against SQL injection but it's the best place to start
$email = $sql->real_escape_string($_POST['email']);
$name = $sql->real_escape_string($_POST['name']);

//assuming that there can only be one giveaway running at any one time...
//get the id of the active giveaway, where it's end date is more than the current time
$query = "SELECT id FROM giveaways WHERE end_date > NOW()";

//query the database or kill the script and print an error (further down the line, don't print the error for security reasons
$result = $sql->query($query) or die($sql->error);

if($result->num_rows > 0) {
    //if there's an active giveaway, fetch that result
    $row = mysqli_fetch_assoc($result);
    //and set a variable to the id we want
    $id = $row['id'];

    //insert into your entrants the now linked entrant details and giveaway key
    $query = "INSERT INTO entrants (giveaway_id, name, email) VALUES ('$id', '$name', '$email')";

    //again, query or error handling
    $result = $sql->query($query) or die($sql->error);

    //if that query worked, do your success message, if it didn't tell the entrant that something went wrong
    if($result) {
        $data['success'] = true;
        $data['message'] = "Registration complete!";
    } else {
        $data['success'] = false;
        $data['message'] = "There was an error registering you, please try again soon.";
    }
}

Now, when you need to return all entrants to a specific giveaway you simply do:
SELECT name, email FROM entrants WHERE giveaway_id = //the id of the giveaway


Q:

IllegalArgumentException with Hive when executing query

Ok so I'm trying to execute SHOW DATABASES on hive, but then when I do it, it returns this error

Failed with exception java.io.IOException:java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: ${system:user.name%7D

I've checked around in my XML to see what's going one, but nothing I change fixes this error.
Here's the relevant parts of the XML:
   <property>
    <name>hive.exec.scratchdir</name>
    <value>/tmp/hive-${user.name}</value>
    <description>HDFS root scratch dir for Hive jobs which gets created with write all (733) permission. For each connecting user, an HDFS scratch dir: ${hive.exec.scratchdir}/<username> is created, with ${hive.scratch.dir.permission}.</description>
  </property>
  <property>
    <name>hive.exec.local.scratchdir</name>
    <value>/tmp/${system:user.name}</value>
    <description>Local scratch space for Hive jobs</description>
  </property>
  <property>
    <name>hive.downloaded.resources.dir</name>
    <value>/tmp/${hive.session.id}_resources</value>
    <description>Temporary local directory for added resources in the remote file system.</description>
  </property>
  <property>
    <name>hive.scratch.dir.permission</name>
    <value>733</value>
    <description>The permission for the user specific scratch directories that get created.</description>
  </property>

 <property>
    <name>hive.querylog.location</name>
    <value>/tmp/${system:user.name}</value>
    <description>Location of Hive run time structured log file</description>
  </property>

Other than that, I can't think of any other property causing those errors, but then again I'm completely new this. I still haven't figured out a lot of things, for example how to connect my windows program in my windows VM to hive in my linux VM.
Anyway, if I can get any help I'd appreciate it.

A:

What is ${system:user.name}? Why not use ${user.name} for hive.exec.local.scratchdir and hive.querylog.location. It seems like ${system:user.name} is not expanded.


Q:

Hazelcast: What would be the implications of adding indexes to huge existing IMaps?

Given 4-5 nodes having many IMaps with lots of data in it, some of the predicate queries started to become significantly slow. One of the solutions for solving this performance issue (as I think) could be adding indexes. However, this data is part of a sensible system which is currently being used in production.
Before adding indexes, I was wondering what would be the consequences of doing it on huge IMaps? (would it lock the entire map ?; would it bring down the entire system?; etc.) Hazelcast documentation includes information about how to do it, but doesn't give any other explanation.

A:

If you want to add the index in runtime this is what will happen:

the AddIndexOperation will be executed on every partition
during the execution of the AddIndexOperation the partition will be blocked until all partition data are iterated and added to the index.

Queries won't be blocked in this timeframe - but get/put operations will.
I would recommend doing it in the "maintenance window" where you have the smallest load.
lots of data is relative - just execute a test in your dev environment having exactly the same amount of data to see how long it will take to add an index in your environment.


Q:

Adding a switch to UITableViewCell: storyboard vs code

I want to add a UISwitch to my settings view controller. The switch looks identically to Airplane Mode toggle in the 'Settings' app on iOS. I'm not sure about what is the best way to implement this.
I am choosing between:

adding a UISwitch in code
creating a custom cell in the Storyboard and creating an outlet for a switch

Here's my Swift code for adding a switch to UITableViewCell:
let soundSwitch = UISwitch(frame: CGRectZero)
soundSwitch.addTarget(self, action: "test:", forControlEvents: UIControlEvents.ValueChanged)
// I created an outlet for the cell that will contain a switch
soundCell.accessoryView = tickingSoundSwitch

What are advantages and disadvantages of using these solutions?

A:

My suggestion is to use either
1.UISwitch in storyboard along with an IBAction  , if you use this approach things becomes easy ,you need not to add target and mess with lot of codes.
or
2.Completely rely on code, Using this approach your UISwitch will not get tight coupled with storyboard's UI. Even in the future if you want to change the UI stuffs in storyboard you need not to do any changes for your UISWitch ,i.e you don't need to  attach all those IBAction and outlet stuffs as you are using pure code based approach(provided your UISwitch requirement doesn't change).


Q:

Replacing first character in file Python 2.7

I'm trying to replace the first character in a file so that I end up with either a 1 or a 0 in it. Here's my code:
import os

hostName = raw_input("IP: ")
communicate = open("communicate.txt", "w")

while True:
    response = os.system("ping " + hostName + " -c 1")
    if response == 0:
        # Replace first character with '1'
    else:
        # Replace first character with '0'

I am running the code in a Linux virtual machine through the terminal.

A:

This appears to do what you want:
import os
import time

hostName = raw_input("IP: ")
communicateFd = os.open("communicate.txt", os.O_CREAT | os.O_RDWR)
communicate = os.fdopen(communicateFd, 'r+b')

while True:
    communicate.seek(0)
    response = os.system("ping " + hostName + " -c 1")
    if response == 0:
        communicate.write('1')
    else:
        communicate.write('0')
    time.sleep(1)

communicate.close()

As noted by others, opening with mode 'w' will truncate the file, destroying the previous contents, if any.
Using the os module, we can have a bit more control over how the file is opened.  In this case, it's created only if it doesn't exist, and then opened in read/write mode.
At the top of the loop we seek to the beginning of the file, allowing us to simply rewrite the first byte as many times as necessary.
A sleep statement was added to keep this from being a tight loop, but it can be removed without affecting the file I/O.


Q:

CruiseControl.net failing with HTTP Error 500 on Vista x64

I installed CruiseControl.net ( from the CruiseControl.NET-1.4-Setup.exe installer ) on my Vista x64 development machine.  The server portion is running fine; however, the webdashboard piece is not working.
The first error message I saw when I tried to pull up http://localhost/ccnet squawked about not being able to run in integrated pipeline mode.  Easily fixed.  I opened up the IIS7 admin panel and changed the ccnet application to use the "Classic .NET App Pool" application pool.
However, I am now getting a persistent HTTP Error 500 when I try to connect.  I set the NTFS permissions on the webdashboard folder wide open in the hopes that maybe it was a file permissions issue.  No joy.
After a bit of digging and trial and error I found a set of steps which seems to fix the problem.  I'll post a follow up answer right after this, but wanted to share this out on stackoverflow in the hopes that it might aid someone else down the line.  Also, if there's a better configuration solution I'm all ears :)

A:

Here's the top of the HTTP 500 error dump I was getting:

HTTP Error 500.0 - Internal Server Error
Description: The page cannot be displayed because an internal server error has occurred.
Error Code: 0x800700c1
Notification: ExecuteRequestHandler
Module: IsapiModule
Requested URL: http://localhost/ccnet/default.aspx
Physical Path: C:\Program Files (x86)\CruiseControl.NET\webdashboard\default.aspx
Logon User: Anonymous
Logon Method: Anonymous
Handler: AboMapperCustom-80778
Most likely causes:
IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
  IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.
  IIS was not able to process configuration for the Web site or application.
  The authenticated user does not have permission to use this DLL.
  The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.

The key to fixing this for me was the Handler line.  For some reason the ccnet web application was configured with two handlers vying for control over *.aspx.  The real handler, from Thoughtworks, is set in the web.config file.  However, when I opened the Handler Mappings section of the IIS7 control panel for the ccnet app I saw that there was another handler named AboMapperCustom-80778 already created and set to look for *.aspx.
I right clicked the handler and selected "Remove".  After that the ccnet app started running fine for me.


Q:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors

I'm trying to find and think of this problem I can't find the best solution to solve it!! And I can't understand What does it mean?!

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors  and  because they have no common ancestor.  Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

Code:
private let logoImageView: UIImageView = {
    let imgView = UIImageView()
    imgView.image = UIImage(named: "LogoBlue")
    return imgView
}()

func setupLogo() {

    if #available(iOS 11.0, *) {
        view.add(subview: logoImageView) { (v, p) in [
            v.topAnchor.constraint(equalTo: p.safeAreaLayoutGuide.topAnchor, constant: 50),
            v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
            v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
            v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
        ]}
    } else {
        view.add(subview: logoImageView) { (v, p) in [
            v.topAnchor.constraint(equalTo: p.topAnchor, constant: 50),
            v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
            v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
            v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
        ]}
    }
}

Extension:
extension UIView {
    func add(subview: UIView, createConstraints: (_ view: UIView, _ parebt: UIView) -> [NSLayoutConstraint]) {
        subview.activate(constraints: createConstraints(subview, self))
    }

    func activate(constraints: [NSLayoutConstraint]) {
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(constraints)
    }
}

A:

You need to add the UIView on the hierarchy before applying constraints.
In other words, you need to <#PARENT_HERE#>.addSubview(<#CHILD_HERE#>)
You can change your extension to:
extension UIView {
    func add(subview: UIView, createConstraints: (_ view: UIView, _ parebt: UIView) -> [NSLayoutConstraint]) {
        self.addSubview(subview) // <
        subview.activate(constraints: createConstraints(subview, self))
    }

    func activate(constraints: [NSLayoutConstraint]) {
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate(constraints)
    }
}

This would definitely be my solution, if you can modify your extension.

Another not so fancy solution is to manually add each subview outside the extension:
func setupLogo() {
    self.view.addSubview(logoImageView) // assuming self.view is not nil
    if #available(iOS 11.0, *) {
        view.add(subview: logoImageView) { (v, p) in [
            v.topAnchor.constraint(equalTo: p.safeAreaLayoutGuide.topAnchor, constant: 50),
            v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
            v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
            v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
        ]}
    } else {
        view.add(subview: logoImageView) { (v, p) in [
            v.topAnchor.constraint(equalTo: p.topAnchor, constant: 50),
            v.centerXAnchor.constraint(equalTo: p.centerXAnchor),
            v.heightAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5),
            v.widthAnchor.constraint(equalTo: p.widthAnchor, multiplier: 0.5)
        ]}
    }
}

Note: This is a secondary solution, don't use both at the same time.


Q:

Selecting a custom color in an applet

I am creating a paint program in java for class. The user needs to be able to define custom colors to paint with. I figure the best way to go about this would be to have an icon the user clicks on, resulting in a pop-up selection window with sliders to define the three RGB values of a color. What would be the best way to go about this? I've found JSlider but can't figure out how to implement it as a pop-up window as a result of an icon being clicked.

A:

Use a JColorChooser.  See How to Use Color Choosers for details.


Q:

Call a method of another component

How to call a method of another component ?
Like I have a component named Modal.vue . I have a method like below
<script>
    export default {
        name: 'modal'
        methods: {
            getUsers() {
                //some code here
            }
        },
        created: function () {
            this.getUsers();
        }
    }
</script>

I would like to call that method in another component named Dashboard.vue.
<script>
    export default {
        name: 'dashboard'
        methods: {
            add_adddress () {
                this.getUsers();  // I would like to access here like this
                //some code here
            }
        },
    }
</script>

I read this question, but how can I use $emit,$on,$broadcast in my current setup ?

A:

In order to use emit one of the components need to call the other (parent and child). Then you emit from the child component to the parent component. For example if Dashboard component uses the Modal component you can emit from the Modal to the Dashboad.
If your components are separate from one another you can make use of Mixins.  You can create a mixin UsersMixin.js like the following:
export default {
    methods: {
        getUsers: function () {
            // Put your code here for a common method
        }
    }
}

Then import the mixin in both your components, and you will be able to use its methods:
Modal.vue
<script>
import UsersMixin from './UsersMixin';
export default {
    name: 'modal'
    mixins: [
        UsersMixin
    ],
    created: function () {
        this.getUsers();
    }
}
</script>

Dashboard.vue
<script>
import UsersMixin from './UsersMixin';
export default {
    name: 'dashboard',
    mixins: [
        UsersMixin
    ],
    methods: {
        add_adddress () {
            this.getUsers();  // I would like to access here like this
            //some code here
        }
    },
}
</script>


Q:

How to UV-Map a complex plane?

I'm having trouble adding texture to a complex plane object, where can I place the seams so that the UV-Map doesn't appear very distorted and overlapped.
Here is the file

A:

In your case, I would separate the pillars from the rest of the mesh, if they are buildings. Otherwise, they are okay.
There are lots of techniques for unwrapping, but here are a few things to keep in mind.

You can use more than one UV map on an object. For example, you could "project from view, bounds" for the top of the mesh, and use a texture for the ground surface, then unwrap the sides of the pillar on a different map, and use a different texture for that.
Smart UV unwrap usually does a pretty good job, and you can base your unwrap on that if you want.
It is not always necessary to unwrap an object, if you want it to be textured. Your best and simplest bet may be to use generated coordinates with box projection.
You usually want to mark seams on sharp angles, and places that are hard to see, like the bottom of your pillars.

I noticed you are using "Blender Render", not Cycles. Are you sure that is what you want to do? From my knowledge, texturing can be easier in Cycles and many of the tips I suggested only work with Cycles nodes, as far as I know. I don't know very much about Blender render though.
Just some tips, I hope they help. Here is an example of using box projection on your model.


Q:

Array of files and value assigning

I have 2 questions.
I want to create an array of files in C. But I'm not sure whether I have to malloc the size before or not.Can I just use FILE** files as an array or do I have to malloc them before. And if I have to make space, do I need to reserve 4 bytes (x86)?
I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.
char extra[8] = { 0xAE00AF00B000B100 };
// index is a random place in the string
name[index] = '\0';
i = 0;
if (index > 16) {
    for (i = 24-index; i < 8; i++) {
        index++;
        name[index] = extra[i];
        }
    }
else {
    name[17] = 0xAE;
    name[18] = 0x00;
    name[19] = 0xAF;
    name[20] = 0x00;
    name[21] = 0xB0;
    name[22] = 0x00;
    name[23] = 0xB1;
    name[24] = 0x00;
}

I need to add those extra bytes btw.

A:

I want to create an array of files in C. But I'm not sure whether I
  have to malloc the size before or not.Can I just use FILE** files as
  an array or do I have to malloc them before. And if I have to make
  space, do I need to reserve 4 bytes (x86)?

If you need to have an array of files, it is possible to use an array of pointers as follow:
#include <stdio.h>

FILE *array[NB_FILES];

Or you can do it dynamically if NB_FILES is only known at runtime.
#include <stdio.h>
#include <stdlib.h>

FILE **array = malloc(nb_files * sizeof *array);

I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.

The standard C library provides the function memcpy, which is a builtin on many compiler (so it will be faster than a for loop).
#include <string.h>

char array[24];
char extra[8];

memcpy(array + sizeof array - sizeof extra - 1, extra, sizeof extra);


Q:

How to set headers to $.get() or $.post() function

How do I add authorization headers to the following ajax request?
$.get(urlAPI + "/api/account/get", function (data) {
                    alert(data);
                }, 'json');

A:

You can define ajaxsetup before your request $ .get () to include the authorization in the header
$.ajaxSetup({
   headers:{
      'Authorization': "auth username and password"
   }
});

$.get(urlAPI + "/api/account/get", function (data) {
    alert(data);
}, 'json');

A:

$.ajax({
  url: 'foo/bar',
  headers: { 'x-my-custom-header': 'some value' }
});

A:

based on jquery page $.get() document
from version 1.12 there is a settings option to pass the base settings to the method.
jQuery.get( [settings ] )

or
$.get( [settings] )

settings is a plain object so you can use it like
{
  url: 'http://requesturl.io',
  data: {},
  headers: { 'your-custom-header': 'custom-header-value' }
}


Q:

For loop only stores final result in R

I am trying to run a for loop in R which stores the result in a list. I cannot store the data in a matrix as my outputs vary in length. For example, the following code produces a list with all entries as 'NULL' apart from the last section.
for(i in 1:n) {
  time <- list()
  time[[i]] <- (sample(1:96, wb[i], replace=T, prob=weekday[,1]))
print(time)
}

However, if I do this, the result is what I want, but it is not stored, so I cannot use it later.
for(i in 1:n) {
   print(sample(1:96, wb[i], replace=T, prob=weekday[,1]))
}

Any help would be appreciated!

A:

For added fun (and efficiency) you can try
time <- lapply(1:n, function(i) sample(1:96, wb[i], replace=T, prob=weekday[,1]))


Q:

Azure Key Vault limits

We are developing authentication service (using identityServer) and we want to sign the JWT token returned to the user with private key stored in Azure Key Vault HSM
Our domain consists of millions of users that expected to call the authentication service once an hour in average (and therefore the key vault)
According to Microsoft docs the key vault service limits is 100 calls per second. See: https://azure.microsoft.com/en-us/documentation/articles/key-vault-service-limits/
Are we using Azure Key Vault as we suppose to do? It seems that the Key Vault transactions volume is very low.

A:

If you look at the pricing page there is a footnote that says -

contact Microsoft for pricing for operation volumes exceeding 50 million operations per month

The alternative is to use Key vault as a key signing service, so you have a key that is signed by the key in key vault, that is rotated amongst your servers. It would be an extra piece of work, but it means that you can have very short lived certificates, which could provide a little additional security.


Q:

Kafka Connect JDBC Sink Connector

I am trying to write data from a topic (json data) into a MySql Database.  I believe I want a JDBC Sink Connector.
How do I configure the connector to map the json data in the topic to how to insert data into the database.
The only documentation I can find is this.

"The sink connector requires knowledge of schemas, so you should use a
  suitable converter e.g. the Avro converter that comes with Schema
  Registry, or the JSON converter with schemas enabled. Kafka record
  keys if present can be primitive types or a Connect struct, and the
  record value must be a Connect struct. Fields being selected from
  Connect structs must be of primitive types. If the data in the topic
  is not of a compatible format, implementing a custom Converter may be
  necessary."

But how do you configure?  Any examples?

A:

I assume that means you need to use Confluent Schema Registry?

For "better" schema support, then yes. But no, it is not required.
You can use the JsonConverter with schemas.enable=true
Your JSON messages will need to look like this though,
{
   "schema" : {
      ... data that describes the payload
   },
   "payload": {
      ... your actual data
   }
}

For reference to this format, you can see this blog
You can use Kafka Streams or KSQL to more easily convert "schemaless" JSON to a schema-d Avro payload


Q:

JavaFX (2.2) loading a String from memory into a WebView

I have to display some value with JavaFX (2.2) WebView. But value have to query form data base. This value may contain some reference to external web page and internal local file. How can make enable users to open those web pages and local files with WebView. Thanks.
  WebView wv = new WebView();
    wv.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() {

        @Override
        public WebEngine call(PopupFeatures p) {
            Stage stage = new Stage(StageStyle.UTILITY);
            WebView wv2 = new WebView();
            stage.setScene(new Scene(wv2));
            stage.show();
            return wv2.getEngine();
        }
    });

    String value = "Open a URL" +
                      " Open a File ";

    wv.getEngine().loadContent(value);

    StackPane root = new StackPane();
    root.getChildren().add(wv);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

A:

I have got resolved this issue as following manner. For make this enable following stackoverflow post was very helpful. Thanks.
    // Set HostService inherit from Application class
    ServiceUtil.hostServices = getHostServices();

    // HTML code
    final String htmlCode = "Open a Web URL" +
                            "Open a Local File ";

    // Create a WebView
    final WebView webView = new WebView();

    webView.getEngine().loadContent(htmlCode);

    webView.getEngine().locationProperty().addListener(new ChangeListener<String>() {
         @Override
         public void changed(ObservableValue<? extends String> observable, final String oldValue, final String newValue) {

                      if((newValue != null) && (!newValue.trim().equals(""))) {

                          Platform.runLater(new Runnable() {

                              @Override
                              public void run() {

                                  // Reset content as HTML codes
                                  // NB: This will make stop opening URL in WebView
                                  webView.getEngine().loadContent(htmlCode);

                                  // Direct URL to local browser
                                  ServiceUtil.hostServices.showDocument(newValue);
                              }
                          });
                      }
                  }
     });


Q:

Storing unit test data in an external file

I know that we normally say unit tests should be entirely self-contained with no dependency on external systems or data - those are called integration tests.
But...
I want to write a mock which provides the result of a certain method which by its nature returns quite a large amount of JSON/XML data (as a string). In this scenario can I legitimately store the data in a text file that's part of my unit test project or would this strictly speaking still be an integration test?

A:

Yes, you can store it in a text file, and it will still be a unit test. (Though, preferably, I would suggest to put the text in the test code itself, unless you already have it in a file, or the text is really large.)
What differentiates a unit test from an integration test is not whether it touches the file system and/or other external resources. The difference that matters is whether the unit test only aims to verify the behavior/state of a single unit, or of multiple interdependent units. In the later case, you have an integration test.
So, a unit test can run code from other units or systems it depends on. But it should assume that those other units just work as expected, without validating their behavior. Another approach for unit testing is to isolate the tested unit from dependencies through mocking or faking. Both approaches are valid.


Q:

Ruby mixins looking for a best practice

I'm writing Ruby Gem where I have Connection module for Faraday configuration
module Example
  module Connection
    private

    def connection
      Faraday.new(url: 'http://localhost:3000/api') do |conn|
        conn.request  :url_encoded             # form-encode POST params
        conn.response :logger                  # log requests to STDOUT
        conn.adapter  Faraday.default_adapter  # make requests with Net::HTTP
        conn.use      Faraday::Response::ParseJson
        conn.use      FaradayMiddleware::RaiseHttpException
      end
    end
  end
end

Second module which makes API requests looks like this:
module Example
  module Request
    include Connection

    def get(uri)
      connection.get(uri).body
    end

    def post(url, attributes)
      response = connection.post(url) do |request|
        request.body = attributes.to_json
      end
    end

    def self.extended(base)
      base.include(InstanceMethods)
    end

    module InstanceMethods
      include Connection

      def put(url, attributes)
        response = connection.put(url) do |request|
          request.body = attributes.to_json
        end
      end
    end
  end
end

Class Cusomer where I use Request looks like this:
module Example
  class Customer
    extend  Request

    attr_accessor :id, :name, :age

    def initialize(attrs)
      attrs.each do |key, value|
        instance_variable_set("@#{key}", value)
      end
    end

    def self.all
      customers = get('v1/customer')
      customers.map { |cust| new cust }
    end

    def save
      params = {
        id:   self.id,
        age:  self.age
        name: self.name,
      }

      put("v1/customers/#{self.id}", params)
    end
  end
end

So here you see in Customer#all class method I'm calling Request#get  method which is available because I extended Request in Customer. then I'm using self.extended method in Request module to be make Request#put available in Customer class, so I have question is this good approach to use mixins like this, or do you have any suggestion?

A:

Mixins are a strange beast. Best practices vary depending on who you talk to. As far as reuse goes, you've achieved that here with mixins, and you have a nice separation of concerns.
However, mixins are a form of inheritance (you can take a peek at #ancestors). I would challenge you saying that you shouldn't use inheritance here because a Customer doesn't have an "is-a" relationship with Connection. I would recommend you use composition instead (e.g. pass in Connection/Request) as it makes more sense to me in this case and has stronger encapsulation.
One guideline for writing mixins is to make everything end in "-able", so you would have Enumerable, Sortable, Runnable, Callable, etc. In this sense, mixins are generic extensions that provide some sort of helpers that are depending on a very specific interface (e.g. Enumerable depends on the class to implement #each).
You could also use mixins for cross-cutting concerns. For example, we've used mixins in the past in our background jobs so that we could add logging for example without having to touch the source code of the class. In this case, if a new job wants logging, then they just mixin the concern which is coupled to the framework and will inject itself properly.
My general rule of thumb is don't use them if you don't have to. They make understanding the code a lot more complicated in most cases
EDIT: Adding an example of composition. In order to maintain the interface you have above you'd need to have some sort of global connection state, so it may not make sense. Here's an alternative that uses composition
class CustomerConnection
  # CustomerConnection is composed of a Connection and retains isolation
  # of responsibilities. It also uses constructor injection (e.g. takes
  # its dependencies in the constructor) which means easy testing.
  def initialize(connection)
    @connection = connection
  end

  def all_customers
    @connection.get('v1/customers').map { |res| Customer.new(res) }
  end
end

connection = Connection.new
CustomerConnection.new(connection).all_customers