问:
How to Dynamically build Select as relates to Linq & Entity Framework
I would like to do the following

```<code>public async Task<List<dynamic>> searchEntities(string query, list<string> columnNames)
{
   var columNames = GetPropertiesUsingReflectionAndfilter<Entity>(columnNames);
   await db.entities.select(x => { columnNames }).where(...)..ToListAsync();
}
</code>```

I need to expose a custom EF Search Method in a Controller.  I would like to offer a partial response.  $search is not avail in version of OData I am using.

Is this possible with IQueryable perhaps?

Alternative would be to build Parameterized SQL query.  Would like to know if there is a better way using EF and Linq?  Thanks..

Solution:

Thanks to @IvanStoev, I ultimately added a library, System.Linq.Dynamic (free with > 1 million downloads), to accomplish this.  I now have.

```<code>using System.Linq.Dynamic;

            var columnNames = GetColumNames<Entity>(qry.TableList);
            var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

            var results = await db.Lessons
                .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
                .Select(selector)
                .ToListAsync();

            return Ok(results);
</code>```

TLDR.  Full usage for my scenario.

Controller:

```<code>[HttpPost, Route("Search/Lessons")]
public async Task<IHttpActionResult> SearchLessons([FromBody] SearchQuery qry)
{
    var columnNames = GetColumNames<Lesson>(qry.TableList);

    if (columnNames.Count < 1) {
        return BadRequest();
    }

    var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

    var results = await db.Lessons
        .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
        .Select(selector)
        .ToListAsync();

    return Ok(results);
}
</code>```

And Helpers:..

```<code>private List<string> GetColumNames<T>(List<string> columnsToFetch = null)
{
    var properties = GetProperties<T>();
    var columnNames = new List<string>();

    if (columnsToFetch == null)
    {
        return properties;
    }

    foreach (var columnRequested in columnsToFetch)
    {
        var matchedColumn = properties
            .Where(x => x.ToLower() == columnRequested.ToLower())
            .FirstOrDefault();

        if (matchedColumn != default(string))
        {
            columnNames.Add(matchedColumn);
        }
    }

    return columnNames;
}
</code>```

And..

```<code>private List<string> GetProperties<T>()
    {
        dynamic model = TypeDescriptor.GetProperties(Activator.CreateInstance<T>());

        List<string> result = new List<string>();
        foreach (var prop in model)
        {
            result.Add(prop.Name);
        }
        return result;
    }
</code>```

答:
Disclaimer: I'm the owner of the project Eval-Expression.NET

This library is not FREE but allows you to compile & execute C# code at runtime. By example, you can perform any LINQ dynamically

Tutorial: LINQ Dynamic

Example:

```<code>public searchEntities(string query, list<string> columnNames)
{
   await db.entities.SelectDynamic(x => "{" + string.Join(",", columnNames) + "}")
           .where(...)..ToListAsync();
}
</code>```

Body:
I would like to do the following

public async Task<List<dynamic>> searchEntities(string query, list<string> columnNames)
{
   var columNames = GetPropertiesUsingReflectionAndfilter<Entity>(columnNames);
   await db.entities.select(x => { columnNames }).where(...)..ToListAsync();
}

I need to expose a custom EF Search Method in a Controller.  I would like to offer a partial response.  $search is not avail in version of OData I am using.

Is this possible with IQueryable perhaps?

Alternative would be to build Parameterized SQL query.  Would like to know if there is a better way using EF and Linq?  Thanks..

Solution:

Thanks to @IvanStoev, I ultimately added a library, System.Linq.Dynamic (free with > 1 million downloads), to accomplish this.  I now have.

using System.Linq.Dynamic;

            var columnNames = GetColumNames<Entity>(qry.TableList);
            var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

            var results = await db.Lessons
                .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
                .Select(selector)
                .ToListAsync();

            return Ok(results);

TLDR.  Full usage for my scenario.

Controller:

[HttpPost, Route("Search/Lessons")]
public async Task<IHttpActionResult> SearchLessons([FromBody] SearchQuery qry)
{
    var columnNames = GetColumNames<Lesson>(qry.TableList);

    if (columnNames.Count < 1) {
        return BadRequest();
    }

    var selector = "new(" + String.Join(", ", columnNames.ToArray()) + ")";

    var results = await db.Lessons
        .Where(x => x.LessonName.Contains(qry.Query) == true || x.HTML.Contains(qry.Query) == true)
        .Select(selector)
        .ToListAsync();

    return Ok(results);
}

And Helpers:..

private List<string> GetColumNames<T>(List<string> columnsToFetch = null)
{
    var properties = GetProperties<T>();
    var columnNames = new List<string>();

    if (columnsToFetch == null)
    {
        return properties;
    }

    foreach (var columnRequested in columnsToFetch)
    {
        var matchedColumn = properties
            .Where(x => x.ToLower() == columnRequested.ToLower())
            .FirstOrDefault();

        if (matchedColumn != default(string))
        {
            columnNames.Add(matchedColumn);
        }
    }

    return columnNames;
}

And..

private List<string> GetProperties<T>()
    {
        dynamic model = TypeDescriptor.GetProperties(Activator.CreateInstance<T>());

        List<string> result = new List<string>();
        foreach (var prop in model)
        {
            result.Add(prop.Name);
        }
        return result;
    }

Body:
Disclaimer: I'm the owner of the project Eval-Expression.NET

This library is not FREE but allows you to compile & execute C# code at runtime. By example, you can perform any LINQ dynamically

Tutorial: LINQ Dynamic

Example:

public searchEntities(string query, list<string> columnNames)
{
   await db.entities.SelectDynamic(x => "{" + string.Join(",", columnNames) + "}")
           .where(...)..ToListAsync();
}


来源: stackexchange

问:
User inserting pictures in excel with macro
I'm a bit stuck on this one, since I couldn't find much on the web. Basically, I'd like the user to be able to click a button which formats some cells, and then opens a box which makes the user navigate through windows explorer in order to insert one or two pictures in the newly formatted cells.

This is what I have so far:

```<code>Private Sub AddPic_Click()
    Dim lastCell As Range
    Dim newCell1 As Range
    Dim newCell2 As Range
    Dim newCellMergePic1 As Range
    Dim newCellMergePic2 As Range
    Dim myRange As Range

    Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

    For Each r In myRange
        If r.MergeCells Then
            Set lastCell = r
        End If
    Next r

    Set newCell1 = lastCell.Offset(1, 0)
    Set newCell2 = newCell1.Offset(0, 5)

    Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
    Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))

    newCellMergePic1.Merge
    newCellMergePic2.Merge

    With newCellMergePic1
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With

    With newCellMergePic2
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With
End Sub
</code>```

It works, but I don't know how to integrate the feature which allows the user to navigate through their folders in order to select the picture(s) they want to add. Thank you for the taking the time to read my post.

答:
You will need to use a dialog box:

```<code>Option Explicit

Public Sub addImage1()
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Ok"
        .Title = "Select an image"
        .Filters.Clear
        .Filters.Add "JPG", "*.JPG"
        .Filters.Add "JPEG File Interchange Format", "*.JPEG"
        .Filters.Add "Graphics Interchange Format", "*.GIF"
        .Filters.Add "Portable Network Graphics", "*.PNG"
        .Filters.Add "All Pictures", "*.*"
        If .Show = -1 Then
            Dim img As Object
            Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))
        Else
            MsgBox ("Cancelled.")
        End If
    End With
End Sub
</code>```

or

```<code>Public Sub addImage2()
    Dim result, imgTypes As String

    imgTypes = imgTypes & "JPG files (*.jp*),*.jp*"
    imgTypes = imgTypes & ", GIF files (*.gif),*.gif"
    imgTypes = imgTypes & ", PNG files (*.png),*.png"
    imgTypes = imgTypes & ", All files (*.*),*.*"

    result = Application.GetOpenFilename(imgTypes, 1, "Select Image", , False)

    If result <> False Then
        ActiveSheet.Pictures.Insert (result)
    End If
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm a bit stuck on this one, since I couldn't find much on the web. Basically, I'd like the user to be able to click a button which formats some cells, and then opens a box which makes the user navigate through windows explorer in order to insert one or two pictures in the newly formatted cells.

This is what I have so far:

Private Sub AddPic_Click()
    Dim lastCell As Range
    Dim newCell1 As Range
    Dim newCell2 As Range
    Dim newCellMergePic1 As Range
    Dim newCellMergePic2 As Range
    Dim myRange As Range

    Set myRange = Worksheets("Product Packaging").Range("A1:A1000")

    For Each r In myRange
        If r.MergeCells Then
            Set lastCell = r
        End If
    Next r

    Set newCell1 = lastCell.Offset(1, 0)
    Set newCell2 = newCell1.Offset(0, 5)

    Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
    Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))

    newCellMergePic1.Merge
    newCellMergePic2.Merge

    With newCellMergePic1
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With

    With newCellMergePic2
        .Font.Name = "Calibri"
        .Font.Color = vbBlack
        .VerticalAlignment = xlVAlignCenter
        .HorizontalAlignment = xlHAlignCenter
        .Font.Bold = True
        .Value = "Picture Here"
    End With
End Sub

It works, but I don't know how to integrate the feature which allows the user to navigate through their folders in order to select the picture(s) they want to add. Thank you for the taking the time to read my post.

Body:
You will need to use a dialog box:

Option Explicit

Public Sub addImage1()
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .ButtonName = "Ok"
        .Title = "Select an image"
        .Filters.Clear
        .Filters.Add "JPG", "*.JPG"
        .Filters.Add "JPEG File Interchange Format", "*.JPEG"
        .Filters.Add "Graphics Interchange Format", "*.GIF"
        .Filters.Add "Portable Network Graphics", "*.PNG"
        .Filters.Add "All Pictures", "*.*"
        If .Show = -1 Then
            Dim img As Object
            Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))
        Else
            MsgBox ("Cancelled.")
        End If
    End With
End Sub

or

Public Sub addImage2()
    Dim result, imgTypes As String

    imgTypes = imgTypes & "JPG files (*.jp*),*.jp*"
    imgTypes = imgTypes & ", GIF files (*.gif),*.gif"
    imgTypes = imgTypes & ", PNG files (*.png),*.png"
    imgTypes = imgTypes & ", All files (*.*),*.*"

    result = Application.GetOpenFilename(imgTypes, 1, "Select Image", , False)

    If result <> False Then
        ActiveSheet.Pictures.Insert (result)
    End If
End Sub


问:
Parameter Validation on Reports
I'm new to SSRS, so I apologize if this question is too simple:

I have a report which accepts a parameter called "Amount". I want to constrain valid inputs to currency values >= 0, and pop open an error message if the user enters improper values.

I don't want to validate inputs in my stored procedure and throw exceptions, because SSRS displays a very generic "Query execution failed for 'someTable'" message to users who access the report from another machine, and my business does not want to turn on the "Enable Remote Errors" flag.

How do I add input validation to report parameters and notify users of bad input?

Yes, I've googled around, but haven't had much luck. Thanks in advance :)

答:
Okay, how about this?

All you have in SSRS, really, is the SQL query and expressions in report fields.

Perhaps you could add a big, red text box at the top of the report for your error message, and give it an expression like '=IIf(Parameters!Amount.Value < 0, "Error: Invalid Amount", "")'.

Then go to your table's "Hidden" property and give it the expression "=Parameters!Amount.Value < 0"

You could also add into your query's where clause and add "AND @Amount >= 0" so you aren't fetching from the database when there's an error.

OwnerDisplayName: Princess

ContentLicense: CC BY-SA 2.5

Title: Parameter Validation on Reports

OwnerDisplayName: Darcy Casselman


问:
C# 20,000 records selected from oracle need to be inserted into SQL2005
i have a console app in c# that extracts 20 fields from an oracle DB witht he code below and i wanted an efficient way to insert them into SQL 2005.

i dotn want to insert each one of the 20,000 within the while loop, obviously. i was thinking to change the code to use a data set to cache all the records and then do a bulk insert...

thoughts?

pseudo code would be nice since i am new to oracle.

this is my code where i was testing getting a connection to oracle and seeing if i can view the data... now i can view it i want to get it out and into sql2005... what do i do from here?

```<code>static void getData()
{
    string connectionString = GetConnectionString();
    using (OracleConnection connection = new OracleConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();

        OracleCommand command = connection.CreateCommand();
        string sql = "SELECT * FROM BUG";
        command.CommandText = sql;

        OracleDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //string myField = (string)reader["Project"];
            string myField = reader[0].ToString();
            Console.WriteLine(myField);
        }
    }

}
</code>```

答: You can create a CSV file and then use BULK INSERT to insert the file into SQL Server. Have a look here for an example.</p>

Body:
i have a console app in c# that extracts 20 fields from an oracle DB witht he code below and i wanted an efficient way to insert them into SQL 2005.

i dotn want to insert each one of the 20,000 within the while loop, obviously. i was thinking to change the code to use a data set to cache all the records and then do a bulk insert...

thoughts?

pseudo code would be nice since i am new to oracle.

this is my code where i was testing getting a connection to oracle and seeing if i can view the data... now i can view it i want to get it out and into sql2005... what do i do from here?

static void getData()
{
    string connectionString = GetConnectionString();
    using (OracleConnection connection = new OracleConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();

        OracleCommand command = connection.CreateCommand();
        string sql = "SELECT * FROM BUG";
        command.CommandText = sql;

        OracleDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //string myField = (string)reader["Project"];
            string myField = reader[0].ToString();
            Console.WriteLine(myField);
        }
    }

}


问:
How to get price of Chart HLine objects and calculate Fibonacci levels
Three part question:

How to find 2 user created horizontal lines on a chart by name and return the price of each.

Then determine which HLine was crossed by the price most recently to determine trend direction.

Calculate Fibonacci levels based on prices and direction

答:
Working example of Fibonacci object that can be edited by the user and printing of fibonacci levels.</p>

```<code>#include <ChartObjects/ChartObjectsFibo.mqh>
CChartObjectFibo *Fibo;

int OnInit()
    {
     Fibo = new CChartObjectFibo();
     #Create object and set some defaults
     if(!Fibo.Create(0,"Fibonacci",0,Time[5],Open[5],Time[0],Open[0]))
     {
            return(INIT_FAILED);
     }
     # Allow user to drag object
     Fibo.Selectable(true);
     return(INIT_SUCCEEDED);
    }

void OnDeinit(const int reason)
    {
     delete Fibo;
    }

void OnTick()
    {
     string level_description;
     double level_value;
     string printString="Fibonacci Levels - ";
     # Get the two anchor prices
     double p1 = Fibo.GetDouble(OBJPROP_PRICE,0);
     double p2 = Fibo.GetDouble(OBJPROP_PRICE,1);
     # Calculate range
     double range=MathAbs(p1-p2);
     for(int i=0;i<Fibo.LevelsCount();i++)
     {
            level_description=Fibo.LevelDescription(i);
            # Calculate price of level
            level_value=(p2>p1)?p2-range*Fibo.LevelValue(i):p2+range*Fibo.LevelValue(i);
            printString=StringFormat("%s %s:%.5f",printString,level_description,level_value);
     }
     Print(printString);
    }
</code>```

Body:
Working example of Fibonacci object that can be edited by the user and printing of fibonacci levels.

#include <ChartObjects/ChartObjectsFibo.mqh>
CChartObjectFibo *Fibo;

int OnInit()
    {
     Fibo = new CChartObjectFibo();
     #Create object and set some defaults
     if(!Fibo.Create(0,"Fibonacci",0,Time[5],Open[5],Time[0],Open[0]))
     {
            return(INIT_FAILED);
     }
     # Allow user to drag object
     Fibo.Selectable(true);
     return(INIT_SUCCEEDED);
    }

void OnDeinit(const int reason)
    {
     delete Fibo;
    }

void OnTick()
    {
     string level_description;
     double level_value;
     string printString="Fibonacci Levels - ";
     # Get the two anchor prices
     double p1 = Fibo.GetDouble(OBJPROP_PRICE,0);
     double p2 = Fibo.GetDouble(OBJPROP_PRICE,1);
     # Calculate range
     double range=MathAbs(p1-p2);
     for(int i=0;i<Fibo.LevelsCount();i++)
     {
            level_description=Fibo.LevelDescription(i);
            # Calculate price of level
            level_value=(p2>p1)?p2-range*Fibo.LevelValue(i):p2+range*Fibo.LevelValue(i);
            printString=StringFormat("%s %s:%.5f",printString,level_description,level_value);
     }
     Print(printString);
    }


问:
grant access to user on amazon RDS server
i need to grant all privileges for user master to the database 'mysql'(i mean the database not the server) on amazon RDS
i am trying to use

```<code>GRANT ALL PRIVILEGES ON mysql.* To 'master'@'aurora-wqeqwe-rdscluster-1jjch50tq2n3s.qrwerw-2.rds.amazon
aws.com' IDENTIFIED BY 'm3vyrtywrsY026y';
</code>```

答: In your example is "master" any user or is it the name of your RDS Master User account?  For the latter take a look at https://aws.amazon.com/premiumsupport/knowledge-center/duplicate-master-user-mysql/</p>

ContentLicense: CC BY-SA 4.0

Body:
i need to grant all privileges for user master to the database 'mysql'(i mean the database not the server) on amazon RDS
i am trying to use

GRANT ALL PRIVILEGES ON mysql.* To 'master'@'aurora-wqeqwe-rdscluster-1jjch50tq2n3s.qrwerw-2.rds.amazon
aws.com' IDENTIFIED BY 'm3vyrtywrsY026y';


问:
Mocking Javascript objects (specifically YUI)
I'm trying to mock YUI for javascript testing. I want to mock a datatable, but im not sure how to do it.

Something like

```<code> YAHOO.widget.DataTable = function(){

  };
</code>```

so latter I could do something like

```<code>   assert.that(returnedDatatable, isOfType(YAHOO.widget.DataTable));
</code>```

答: My answer: js mockito or don't use YUI :)</p>

Body:
I'm trying to mock YUI for javascript testing. I want to mock a datatable, but im not sure how to do it.

Something like

 YAHOO.widget.DataTable = function(){

  };

so latter I could do something like

   assert.that(returnedDatatable, isOfType(YAHOO.widget.DataTable));


问:
C# resource not found at design time
Since a few days I get a "Resource not found" message when opening any of my xaml files, compiling and executing the application however is no problem. I am using MahApps.Metro for my UI design and already tried to clean and rebuild the whole solution and also "reinstalled" the MahApps.Metro (version 1.4.3) package using Visual Studio Blend 2015.

My App.xaml looks like this: (There are more styles defined, but the WindowStyle shows the "Resource could not be resolved" error)

```<code><Application x:Class="Edge_Player.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:Edge_Player"
         xmlns:metro="http://metro.mahapps.com/winfx/xaml/controls"
         xmlns:system="clr-namespace:System;assembly=mscorlib"
         StartupUri="Player.xaml">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Theme/Dark.xaml"/>
            <ResourceDictionary Source="Localization/StringResources.xaml"/>
            <ResourceDictionary Source="Resources/Icons/Icons.xaml"/>

            <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatButton.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatSlider.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />

            <ResourceDictionary Source="Theme/Base/Dark.xaml"/>
            <ResourceDictionary Source="Theme/Accents/Orange.xaml"/>
            <ResourceDictionary Source="Controls/Slider.xaml"/>
            <ResourceDictionary Source="Controls/Menu.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <system:Double x:Key="WindowTitleFontSize">14</system:Double>

        <BitmapImage x:Key="DesignCover" UriSource="Resources/emptyCover.png"/>
        <BitmapImage x:Key="DesignImage" UriSource="Resources/osu_mp_wallpaper.jpg"/>

        <Style x:Key="WindowStyle"
           TargetType="{x:Type metro:MetroWindow}"
           BasedOn="{StaticResource {x:Type metro:MetroWindow}}">
            <Setter Property="Background" Value="{DynamicResource Primary}"/>
            <Setter Property="Foreground" Value="{DynamicResource Accent}"/>
            <Setter Property="BorderBrush" Value="{DynamicResource Border}"/>
            <Setter Property="GlowBrush" Value="{DynamicResource Border}"/>
            <Setter Property="NonActiveBorderBrush" Value="{DynamicResource Warn}"/>
            <Setter Property="NonActiveGlowBrush" Value="{DynamicResource Warn}"/>
            <Setter Property="NonActiveWindowTitleBrush" Value="{DynamicResource PrimaryDark}"/>
            <Setter Property="WindowTitleBrush" Value="{DynamicResource PrimaryDark}"/>
            <Setter Property="ShowIconOnTitleBar" Value="False"/>
        </Style>
</code>```

All of the DynamicResources used in the "WindowStyle" are defined in a seperate file.

答: I just found out what caused this behaviour to occur: In the XAML editor, project code has been deactivated somehow... (I feel so stupid right now)</p>

Title: C# resource not found at design time

Body:
Since a few days I get a "Resource not found" message when opening any of my xaml files, compiling and executing the application however is no problem. I am using MahApps.Metro for my UI design and already tried to clean and rebuild the whole solution and also "reinstalled" the MahApps.Metro (version 1.4.3) package using Visual Studio Blend 2015.

My App.xaml looks like this: (There are more styles defined, but the WindowStyle shows the "Resource could not be resolved" error)

<Application x:Class="Edge_Player.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:Edge_Player"
         xmlns:metro="http://metro.mahapps.com/winfx/xaml/controls"
         xmlns:system="clr-namespace:System;assembly=mscorlib"
         StartupUri="Player.xaml">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Theme/Dark.xaml"/>
            <ResourceDictionary Source="Localization/StringResources.xaml"/>
            <ResourceDictionary Source="Resources/Icons/Icons.xaml"/>

            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatButton.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/FlatSlider.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />

            <ResourceDictionary Source="Theme/Base/Dark.xaml"/>
            <ResourceDictionary Source="Theme/Accents/Orange.xaml"/>
            <ResourceDictionary Source="Controls/Slider.xaml"/>
            <ResourceDictionary Source="Controls/Menu.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <system:Double x:Key="WindowTitleFontSize">14</system:Double>

        <BitmapImage x:Key="DesignCover" UriSource="Resources/emptyCover.png"/>
        <BitmapImage x:Key="DesignImage" UriSource="Resources/osu_mp_wallpaper.jpg"/>

All of the DynamicResources used in the "WindowStyle" are defined in a seperate file.


问:
How to use "dateRestrict" parameter in Custom Search API
I am trying to modify some java code which uses the Google API. One of the features I have not been able to get is the dateRestrict. Information about this can be found here:

GoogleAPI

To implement this I attach the following string after my query. It is properly connected with the full URL because other parameters work with it.

String parameters = "&dateRestrict=2012-01-01";

I have also tried 1d and 1m but those don't work either as parameters

If someone could show me of an example of dateRestrict I would greatly appreciate it. I just don't understand how they mean to use it in the API. Thank you.

答:
I was trying the same thing, and dateRestrict for an absolute time range didn't seem to work. The pages that were not in the date range also appeared. The workaround I found is to use the sort feature. The query will look something like this:

```<code>(q='search_term' , cx='search_engine_id', sort = 'date:r:yyyymmdd:yyyymmdd')
</code>```

The sort feature allows us to sort and filter the date of the results to the time range specified.

Body:
I was trying the same thing, and dateRestrict for an absolute time range didn't seem to work. The pages that were not in the date range also appeared. The workaround I found is to use the sort feature. The query will look something like this:

(q='search_term' , cx='search_engine_id', sort = 'date:r:yyyymmdd:yyyymmdd')

The sort feature allows us to sort and filter the date of the results to the time range specified.


问:
Hiding text for an image gallery - SEO implications
So i've created a dynamic photo gallery using jquery. Its basically a large image with accompanying descriptive text to the right and a film strip running across the bottom. I structured the filmstrip so that each thumbail is accompanied by its hidden descriptive text and jquery udpates the main text area with the hidden text when the thumbnail is clicked.

I did all this before looking into SEO techniques and now am unsure if this technique could penalize me. I really don't want to have to redo everything. I've heard conflicting advice, some say hidden text is always bad, some say its the "intent" that matters.

What should I do?

答: I follow the philosophy that it both "depends" and is really about "intent". For example, when you say that you have the descriptive text "hidden" it depends on what you mean by that. If you are using the images "alt" attribute and then pulling that with jQuery into a visual description - I see that as completely appropriate. If you are using hidden divs and then showing them onclick or something - it's not the cleanest solution, but I don't think it's going to bring you an penalties.</p>


问:
Sum up combobox values using formulas in extjs
Let's assume we have 2 fields - a tagfield (aka multiSelect combobox) and a textfield. The tagfield is populated from the underlying store having name and amount as parameters. On tagfield select I want to show corresponding amount into the textfield. If there are several fields have been selected from the tagfield I want to sum up the amount values.

There is no problem to implement that using tagfield onSelect listener:

```<code>onComboSelect: function(combo, recordArray) {
    var sum = recordArray.reduce(function(sum, record) {
        return sum + record.data.amount;
    }, 0);
    this.lookup('textfield').setValue(sum)
}
</code>```

But I would like to give a try to MVVM formulas where I faced the following problems:

There is a 'delay' in one selected value between tagfield selection and populating textfield

There is no obvious way on how to sum up value with itself using the formulas.

Please see the fiddle

答:
Binding to selection behaves really strange. I would bind the formula to the tagfield value. It will provide an array with the selected record ids. Then in the viewmodel, you loop through them, get the related records, and sum their amounts. You will need a way to reference the store from the viewmodel. I solved this by moving the store declaration to the viewmodel.

Tagfield bindings:

```<code>bind: {
    value: '{tagValue}',
    store: '{tagStore}'
}
</code>```

Viewmodel config:

```<code>viewModel: {
    formulas: {
        summedAmout: {
            bind: '{tagValue}',
            get: function (valueArray) {
                var sum = 0,
                    tagStore = this.getStore('tagStore');

                if (!valueArray.length) {
                    return '';
                }

                valueArray.forEach(function(tagId) {
                    sum += tagStore.getById(tagId).get('cost');
                });
                return sum;
            }
        }
    },
    stores: {
        tagStore: {
            data: [{
                id: 1, cost: 100, name: 'foo'
            }, {
                id: 2, cost: 200, name: 'bar'
            }]
        }
    }
},
</code>```

Here is the fiddle: https://fiddle.sencha.com/#fiddle/2154&view/editor

Body:
Let's assume we have 2 fields - a tagfield (aka multiSelect combobox) and a textfield. The tagfield is populated from the underlying store having name and amount as parameters. On tagfield select I want to show corresponding amount into the textfield. If there are several fields have been selected from the tagfield I want to sum up the amount values.

There is no problem to implement that using tagfield onSelect listener:

onComboSelect: function(combo, recordArray) {
    var sum = recordArray.reduce(function(sum, record) {
        return sum + record.data.amount;
    }, 0);
    this.lookup('textfield').setValue(sum)
}

But I would like to give a try to MVVM formulas where I faced the following problems:

There is a 'delay' in one selected value between tagfield selection and populating textfield

There is no obvious way on how to sum up value with itself using the formulas.

Please see the fiddle

Body:
Binding to selection behaves really strange. I would bind the formula to the tagfield value. It will provide an array with the selected record ids. Then in the viewmodel, you loop through them, get the related records, and sum their amounts. You will need a way to reference the store from the viewmodel. I solved this by moving the store declaration to the viewmodel.

Tagfield bindings:

bind: {
    value: '{tagValue}',
    store: '{tagStore}'
}

Viewmodel config:

viewModel: {
    formulas: {
        summedAmout: {
            bind: '{tagValue}',
            get: function (valueArray) {
                var sum = 0,
                    tagStore = this.getStore('tagStore');

                if (!valueArray.length) {
                    return '';
                }

                valueArray.forEach(function(tagId) {
                    sum += tagStore.getById(tagId).get('cost');
                });
                return sum;
            }
        }
    },
    stores: {
        tagStore: {
            data: [{
                id: 1, cost: 100, name: 'foo'
            }, {
                id: 2, cost: 200, name: 'bar'
            }]
        }
    }
},

Here is the fiddle: https://fiddle.sencha.com/#fiddle/2154&view/editor


问:
Why a business' catch block does not catch a Spring Batch exception?
I am working with Spring Batch 3.0.7

I have the following code:

```<code>    JobExecution jobExecution = null;

    try{
        jobExecution = jobLauncher.run(job, jobParameters);
        logger.info("jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }
    catch(Throwable t){
        logger.error("Throwable: {}", t.getClass().getSimpleName());
        logger.error("{}", t.getMessage());
        logger.info("jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }
</code>```

Due an experiment scenario the Job executed must fail when the ItemProcessor process a specific record, thus a customized exception (PersonBatchException) is thrown:

```<code>44207 [RMI TCP Connection(3)-192.168.1.8] ERROR o.s.batch.core.step.AbstractStep - Encountered an error executing step one in job simpleDatabaseJdbcReaderErrorProcessorDatabaseJdbcWriter
com.manuel.jordan.batch.exception.PersonBatchException: The record 999 has been selected to fail
    at com.manuel.jordan.batch.processor.PersonExceptionItemProcessor.process(PersonExceptionItemProcessor.java:36)
</code>```

In this case the catch block should work, but it is never executed.

Of course the Console prints all the error stack trace how shown above.

Even if <skippable-exception-classes> would be used, lets assume an exception thrown would be arised but is not listed in the section mentioned.

Let's assume the jobLauncher.run(job, jobParameters) is called through either a JMX or special @Service process

How handle this?

Alpha

```<code>public class PersonBatchException extends RuntimeException {

    private static final long serialVersionUID = -7424725101950190824L;

    public PersonBatchException(String message){
        super(message);
    }

}
</code>```

答:
Thanks to this post:

How to throw exception from spring batch processor process() method
to Spring batch job started method?

I have this version:

```<code>    JobExecution jobExecution = null;

    try{
        jobExecution = jobLauncher.run(job, jobParameters);
        logger.info("Try jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }
    catch(RuntimeException re){
        logger.error("NEVER NEVER EXECUTED NEVER NEVER");
        logger.error("RuntimeException Class: {}", re.getClass().getSimpleName());
        logger.error("{}", re.getMessage());
        logger.error("Catch jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }

    if(jobExecution.getExitStatus().equals(ExitStatus.FAILED)) {
        List<Throwable> exceptions = jobExecution.getAllFailureExceptions();
        for(Throwable throwable : exceptions){
            logger.error("Throwable Class: {}", throwable.getClass().getSimpleName());
            logger.error("{}", throwable.getMessage());
        }
    }
</code>```

The catch block never work, but through the for block is possible do practically the same how the catch block.

Seems Spring Batch's internal process works in some way that reflects this behavior to the catch block

Body:
I am working with Spring Batch 3.0.7

I have the following code:

    JobExecution jobExecution = null;

    try{
        jobExecution = jobLauncher.run(job, jobParameters);
        logger.info("jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }
    catch(Throwable t){
        logger.error("Throwable: {}", t.getClass().getSimpleName());
        logger.error("{}", t.getMessage());
        logger.info("jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }

Due an experiment scenario the Job executed must fail when the ItemProcessor process a specific record, thus a customized exception (PersonBatchException) is thrown:

44207 [RMI TCP Connection(3)-192.168.1.8] ERROR o.s.batch.core.step.AbstractStep - Encountered an error executing step one in job simpleDatabaseJdbcReaderErrorProcessorDatabaseJdbcWriter
com.manuel.jordan.batch.exception.PersonBatchException: The record 999 has been selected to fail
    at com.manuel.jordan.batch.processor.PersonExceptionItemProcessor.process(PersonExceptionItemProcessor.java:36)

In this case the catch block should work, but it is never executed.

Of course the Console prints all the error stack trace how shown above.

Even if <skippable-exception-classes> would be used, lets assume an exception thrown would be arised but is not listed in the section mentioned.

Let's assume the jobLauncher.run(job, jobParameters) is called through either a JMX or special @Service process

How handle this?

Alpha

public class PersonBatchException extends RuntimeException {

    private static final long serialVersionUID = -7424725101950190824L;

    public PersonBatchException(String message){
        super(message);
    }

}

Body:
Thanks to this post:

How to throw exception from spring batch processor process() method
to Spring batch job started method?

I have this version:

    JobExecution jobExecution = null;

    try{
        jobExecution = jobLauncher.run(job, jobParameters);
        logger.info("Try jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }
    catch(RuntimeException re){
        logger.error("NEVER NEVER EXECUTED NEVER NEVER");
        logger.error("RuntimeException Class: {}", re.getClass().getSimpleName());
        logger.error("{}", re.getMessage());
        logger.error("Catch jobExecution.getExitStatus().getExitCode(): {}", jobExecution.getExitStatus().getExitCode());
    }

    if(jobExecution.getExitStatus().equals(ExitStatus.FAILED)) {
        List<Throwable> exceptions = jobExecution.getAllFailureExceptions();
        for(Throwable throwable : exceptions){
            logger.error("Throwable Class: {}", throwable.getClass().getSimpleName());
            logger.error("{}", throwable.getMessage());
        }
    }

The catch block never work, but through the for block is possible do practically the same how the catch block.

Seems Spring Batch's internal process works in some way that reflects this behavior to the catch block


问:
using -replace to remove a string with special characters from cells in a csv
I have a CSV file like:

```<code>"localpath"
"C:\Users\calabresel"
"C:\Users\goslinep"
"C:\Users\deangelisr"
"C:\Users\bannont"
"C:\Users\goodwind"
</code>```

I am looking for a way to isolate just the username from each field.  I will then query the AD to determine if each user is disabled or enabled.  I haven't been able to figure out how to get just the last piece though.  My idea was to use -replace to replace the identical string with null like this:

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\Users\", ""}
</code>```

That came back with invalid regular expression pattern errors though which I assumed was a result of the target string containing special characters (the backslashes).  I then started looking for a way to get powershell to take the \ literally instead.  That lead me to try this:

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace [Regex]::Escape("C:\\Users\\"), ""}
</code>```

and this

```<code>$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\\Users\\", ""}
</code>```

both of those methods stop the invalid regular expression errors and just return me a fresh line without complaining.  however when I print the $txt variable it is empty...

I'm certain I am approaching this problem from the wrong angle and/or with improper syntax but I could use some guidance as I just started working with powershell a week ago.

any help provided would be greatly appreciated.

答:
other solution</p>

```<code>Get-Content "C:\temp\test.txt" | select @{N="Value";E={$_.split('\')[-1].replace('"', '')}} -Skip 1
</code>```

Body:
I have a CSV file like:

"localpath"
"C:\Users\calabresel"
"C:\Users\goslinep"
"C:\Users\deangelisr"
"C:\Users\bannont"
"C:\Users\goodwind"

I am looking for a way to isolate just the username from each field.  I will then query the AD to determine if each user is disabled or enabled.  I haven't been able to figure out how to get just the last piece though.  My idea was to use -replace to replace the identical string with null like this:

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\Users\", ""}

That came back with invalid regular expression pattern errors though which I assumed was a result of the target string containing special characters (the backslashes).  I then started looking for a way to get powershell to take the \ literally instead.  That lead me to try this:

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace [Regex]::Escape("C:\\Users\\"), ""}

and this

$txt = import-csv paths1.csv | % {$_.localpath = $_.localpath -replace "C:\\Users\\", ""}

both of those methods stop the invalid regular expression errors and just return me a fresh line without complaining.  however when I print the $txt variable it is empty...

I'm certain I am approaching this problem from the wrong angle and/or with improper syntax but I could use some guidance as I just started working with powershell a week ago.

any help provided would be greatly appreciated.

Body:
other solution

Get-Content "C:\temp\test.txt" | select @{N="Value";E={$_.split('\')[-1].replace('"', '')}} -Skip 1


问:
How do I alert the user that multiple fields are left blank in an HTML form after clicking submit?
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

```<code><form id="contactform" action="">
    <label> Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />
    </label>
    <label> Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />
    </label>
    <label> Address
        <input name="address" type="text" id="address" maxlength="200" />
    </label>
    <label> Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />
    </label>
    <label> City
        <input name="city" type="text" id="city" maxlength="100" />
    </label>
</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />
</code>```

Here is the javascript code:

```<code>function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}
</code>```

答:
Here's one way that you could do it - adding to a single alert string:

```<code>function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
var alertstring = "Make sure all fields are filled! Currently missing:"

if(firstname.value == "") {
    alertstring += " -First Name-"
    }

if(lastname.value == "") {
    alertstring += " -Last Name-"
    }

if(address.value == "") {
    alertstring += " -Address-"
    }

if(postcode.value == "") {
    alertstring += " -Postal Code-"
    }
if(city.value == "") {
    alertstring += " -City-"
    }
if(alertstring == "Make sure all fields are filled! Currently missing:")
    {
        return true;
    }
else {
    alert(alertstring);
    return false;
    }
</code>```

}

Body:
If the user leaves multiple fields blank, I want to let the user know which fields he left blank in one alert message after they click submit. How would I do this? Any help is appreciated!

Here is the HTML code:

<form id="contactform" action="">
     Name
        <input name="firstname" type="text" id="firstname" maxlength="50" autofocus="autofocus" />

     Last Name
        <input name="lastname" type="text" id="lastname" maxlength="150" />

     Address
        <input name="address" type="text" id="address" maxlength="200" />

     Postcode
        <input name="postcode" type="text" id="postcode" maxlength="50" />

     City
        <input name="city" type="text" id="city" maxlength="100" />

</form>
<input type="submit" value="Submit" onclick=" return validate()" />
<input type="reset" value="Clear" />

Here is the javascript code:

function validate() {

    var firstname = document.getElementById('firstname');
    var lastname = document.getElementById('lastname');
    var address = document.getElementById('address');
    var postcode = document.getElementById('postcode');
    var city = document.getElementById('city');

    if (firstname.value == "") {
        alert("Make sure the first name field is filled");
        return false;
    }

    if (lastname.value == "") {
        alert("Make sure the last name field is filled");
        return false;
    }
    if (address.value == "") {
        alert("Make sure the address field is filled");
        return false;
    }
    if (postcode.value == "") {
        alert("Make sure the post code field is filled");
        return false;
    }
    if (city.value == "") {
        alert("Make sure the city field is filled");
        return false;
    }
    return true;
}

Body:
Here's one way that you could do it - adding to a single alert string:

function validate() {

var firstname = document.getElementById('firstname');
var lastname = document.getElementById('lastname');
var address = document.getElementById('address');
var postcode = document.getElementById('postcode');
var city = document.getElementById('city');
var alertstring = "Make sure all fields are filled! Currently missing:"

if(firstname.value == "") {
    alertstring += " -First Name-"
    }

if(lastname.value == "") {
    alertstring += " -Last Name-"
    }

if(address.value == "") {
    alertstring += " -Address-"
    }

if(postcode.value == "") {
    alertstring += " -Postal Code-"
    }
if(city.value == "") {
    alertstring += " -City-"
    }
if(alertstring == "Make sure all fields are filled! Currently missing:")
    {
        return true;
    }
else {
    alert(alertstring);
    return false;
    }

}


问:
How do I use regex to take all numbers followed by the first digit of the identifier of a string using javascript?
I have the following string that needs to be converted to the following:</p>

```<code>3 Apples 5 Bananas 7 Oranges ===> 3A 5B 7O

3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries ===> 3A 5B 7O 19C
</code>```

答:
Try this:

function convert(s) {
    return s.replace(/(\d+)\s*([A-Z])\D*?(\s|$)/ig, '$1$2$3');
}

convert('3 Apples 5 Bananas 7 Oranges');                  // returns '3A 5B 7O'
convert('3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries'); // returns '3A 5B 7O 19C'
```

Body:
I have the following string that needs to be converted to the following:

3 Apples 5 Bananas 7 Oranges ===> 3A 5B 7O

3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries ===> 3A 5B 7O 19C


问:
Using plist in a DetailView
I have this tableview in my app which has a particular item name such as "Apple". When the user taps on that selected item they are directed to a detailView that views an image and description of that selected item. I was thinking to use plist´s to do this, but I don't know how to. Please help me.

I looked at some sources such as iCodeBlog but they don´t really explain retrieving and saving so well. Maybe you people can also give reference to some links that describe this better.

Heres a plist that I have tried. Each of the items (Orange, Apple) have the data that I want to display in my detailView. I basically want to display the data shown.

答:
Create an array in a plist with a number of items which is equal to the number of rows. Create a string called description and a string called image in each item.   Get the number of the selected row in didSelectRowAtIndex: method. Store the dictionary in an NSDictionary

[myDictionary initWithDictionary:[myArray objectAtIndex:indexPath.row]]

Then get the imagestring and the description string by calling

[myDictionary objectForKey:@"image"]

and pass these strings to the detail view.

Title: Using plist in a DetailView


问:
User interface becomes unresponsive when calling Sleep()
Sleep() is causing issues when pressing buttons.

I have an If loop with random delays (up to 10 seconds) between each mouse move/-click. However, when Sleep() is called the script stops responding to clicks on Close and Stop buttons of its user interface:

```<code>#cs ----------------------------------------------------------------------------
    Author: JesterRM
    Website: N/A
#ce ----------------------------------------------------------------------------

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>
#include <IE.au3>

;Comments On Information
;Set Mouse Position - MouseMove ( x, y)
;Mouse Click At Current Position - MouseClick ("Button")
;Wait Between Each Click Local $hTimer = TimerInit()>insert Link Break< Sleep(TIME)
;Random Sleep Time Sleep(Random(1000, 10000, 1)) = Random Sleep between 1 and 10 seconds
Opt('MustDeclareVars', 1)
MainGUI()

Func MainGUI()
    Local $Button1, $Button2, $Button3, $msg, $count, $OBJECT, $OBJECT_CTRL, $hTimer
    Global $count, $OBJECT, $OBJECT_CTRL

    $count = 0
    GUICreate("FREE KaW Bot V0.01", 1000, 650)
    ; Button Position and Names
    Opt("GUICoordMode", 2)
    $Button1 = GUICtrlCreateButton("Start", 370, 30, 100)
    $Button2 = GUICtrlCreateButton("Stop", 10, -1, 100)
    $Button3 = GUICtrlCreateButton("Close", 10, -1, 100)
    ;Create Internet Explorer in Window
    $OBJECT = ObjCreate("Shell.Explorer.2")
    $OBJECT_CTRL = GUICtrlCreateObj($OBJECT, -650, 20, 900, 550)
    GUISetState()
    _IECreateEmbedded()
    _IENavigate($OBJECT, "http://www.kingdomsatwar.com/play/")
    GUISetState()

    ; Run the GUI until the window is closed
    While 1
        $msg = GUIGetMsg()
        Select
            Case $msg = $GUI_EVENT_CLOSE
                ExitLoop
            ; Button PopUp Messages

            ; Start The Bot
            Case $msg = $Button1
                MsgBox(0, 'Start', 'Starting Bot in 10 Seconds after PopUp Closes')
                Sleep(10000)
                $count = 1
                If $count = 1 Then
                    Do
                        MouseMove(800, 100)
                        ; Begin The Timer and Store The Handle in a Variable
                        Local $hTimer = TimerInit()
                        ; Sleep For 3 Seconds
                        Sleep(Random(1000, 7000, 1))
                        Local $fDiff = TimerDiff($hTimer) ; Find the difference in time from the previous call of TimerInit. The variable we stored the TimerInit handlem is passed as the "handle" to TimerDiff.
                        MsgBox($MB_SYSTEMMODAL, "Time Difference", $fDiff)
                        MouseMove(200, 453)
                        ; Begin The Timer and Store The Handle in a Variable
                        Local $hTimer = TimerInit()
                        ; Sleep For 3 Seconds
                        Sleep(Random(1000, 7000, 1))
                        Local $fDiff = TimerDiff($hTimer) ; Find the difference in time from the previous call of TimerInit. The variable we stored the TimerInit handlem is passed as the "handle" to TimerDiff.
                        MsgBox($MB_SYSTEMMODAL, "Time Difference", $fDiff)
                    Until $count = 0
                Else
                    MsgBox(0, 'Stop', 'Stopping Bot')
                EndIf

            ; Stop The Bot
            Case $msg = $Button2
                MsgBox(0, 'Stop', 'Stopping Bot')
                $count = 0

            ; Close The Bot
            Case $msg = $Button3
                MsgBox(0, 'Close', 'Closing Bot')
                Exit
        EndSelect
    WEnd
EndFunc
</code>```

How could I fix this?

答:
As per AutoIt Wiki - Interrupting a running function:

AutoIt queues function calls in both OnEvent and MessageLoop modes. This means that it waits until a function is finished and the code is back in your idle While...WEnd loop before running the next.

Thus Sleep() delays processing of GUI messages. A workaround would be to contain Sleep() within a function that can be interrupted. Example:

```<code>Func _SleepInterrupted(ByRef $bStateInterrupt, Const $iTimeSleep, Const $iTimeInterrupt = 500)
    Local Const $iParts     = Ceiling($iTimeSleep / $iTimeInterrupt)
    Local Const $iRemainder = $iTimeSleep - ($iTimeInterrupt * Floor($iTimeSleep / $iTimeInterrupt))
    Local       $iCurrent   = $iTimeInterrupt
    Local       $iReturn    = 0

    For $i1 = 1 To $iParts

        If $bStateInterrupt Then
            $iReturn = 1
            ExitLoop 1
        EndIf

        If $i1 = $iParts And $iRemainder Then $iCurrent = $iRemainder
        Sleep($iCurrent)

    Next

    Return $iReturn
EndFunc
</code>```

If (anywhere in the process) $bStateInterrupt evaluates to True the function will return 1 immediately (disregarding time left). It returns 0 if uninterrupted.

$iTimeSleep defines total duration (in ms) for Sleep().

$iTimeInterrupt defines delay (in ms) between periodic checks.

Breaking up total time enables OnEvent- and MessageLoop events to be processed after each segment (every 0.5 seconds if $iTimeInterrupt = 500). Visual (simplified) explanation:

Body:
Sleep() is causing issues when pressing buttons.

I have an If loop with random delays (up to 10 seconds) between each mouse move/-click. However, when Sleep() is called the script stops responding to clicks on Close and Stop buttons of its user interface:

#cs ----------------------------------------------------------------------------
    Author: JesterRM
    Website: N/A
#ce ----------------------------------------------------------------------------

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>
#include <IE.au3>

;Comments On Information
;Set Mouse Position - MouseMove ( x, y)
;Mouse Click At Current Position - MouseClick ("Button")
;Wait Between Each Click Local $hTimer = TimerInit()>insert Link Break< Sleep(TIME)
;Random Sleep Time Sleep(Random(1000, 10000, 1)) = Random Sleep between 1 and 10 seconds
Opt('MustDeclareVars', 1)
MainGUI()

Func MainGUI()
    Local $Button1, $Button2, $Button3, $msg, $count, $OBJECT, $OBJECT_CTRL, $hTimer
    Global $count, $OBJECT, $OBJECT_CTRL

    $count = 0
    GUICreate("FREE KaW Bot V0.01", 1000, 650)
    ; Button Position and Names
    Opt("GUICoordMode", 2)
    $Button1 = GUICtrlCreateButton("Start", 370, 30, 100)
    $Button2 = GUICtrlCreateButton("Stop", 10, -1, 100)
    $Button3 = GUICtrlCreateButton("Close", 10, -1, 100)
    ;Create Internet Explorer in Window
    $OBJECT = ObjCreate("Shell.Explorer.2")
    $OBJECT_CTRL = GUICtrlCreateObj($OBJECT, -650, 20, 900, 550)
    GUISetState()
    _IECreateEmbedded()
    _IENavigate($OBJECT, "http://www.kingdomsatwar.com/play/")
    GUISetState()

    ; Run the GUI until the window is closed
    While 1
        $msg = GUIGetMsg()
        Select
            Case $msg = $GUI_EVENT_CLOSE
                ExitLoop
            ; Button PopUp Messages

            ; Start The Bot
            Case $msg = $Button1
                MsgBox(0, 'Start', 'Starting Bot in 10 Seconds after PopUp Closes')
                Sleep(10000)
                $count = 1
                If $count = 1 Then
                    Do
                        MouseMove(800, 100)
                        ; Begin The Timer and Store The Handle in a Variable
                        Local $hTimer = TimerInit()
                        ; Sleep For 3 Seconds
                        Sleep(Random(1000, 7000, 1))
                        Local $fDiff = TimerDiff($hTimer) ; Find the difference in time from the previous call of TimerInit. The variable we stored the TimerInit handlem is passed as the "handle" to TimerDiff.
                        MsgBox($MB_SYSTEMMODAL, "Time Difference", $fDiff)
                        MouseMove(200, 453)
                        ; Begin The Timer and Store The Handle in a Variable
                        Local $hTimer = TimerInit()
                        ; Sleep For 3 Seconds
                        Sleep(Random(1000, 7000, 1))
                        Local $fDiff = TimerDiff($hTimer) ; Find the difference in time from the previous call of TimerInit. The variable we stored the TimerInit handlem is passed as the "handle" to TimerDiff.
                        MsgBox($MB_SYSTEMMODAL, "Time Difference", $fDiff)
                    Until $count = 0
                Else
                    MsgBox(0, 'Stop', 'Stopping Bot')
                EndIf

            ; Stop The Bot
            Case $msg = $Button2
                MsgBox(0, 'Stop', 'Stopping Bot')
                $count = 0

            ; Close The Bot
            Case $msg = $Button3
                MsgBox(0, 'Close', 'Closing Bot')
                Exit
        EndSelect
    WEnd
EndFunc

How could I fix this?

Body:
As per AutoIt Wiki - Interrupting a running function:

AutoIt queues function calls in both OnEvent and MessageLoop modes. This means that it waits until a function is finished and the code is back in your idle While...WEnd loop before running the next.

Thus Sleep() delays processing of GUI messages. A workaround would be to contain Sleep() within a function that can be interrupted. Example:

Func _SleepInterrupted(ByRef $bStateInterrupt, Const $iTimeSleep, Const $iTimeInterrupt = 500)
    Local Const $iParts     = Ceiling($iTimeSleep / $iTimeInterrupt)
    Local Const $iRemainder = $iTimeSleep - ($iTimeInterrupt * Floor($iTimeSleep / $iTimeInterrupt))
    Local       $iCurrent   = $iTimeInterrupt
    Local       $iReturn    = 0

    For $i1 = 1 To $iParts

        If $bStateInterrupt Then
            $iReturn = 1
            ExitLoop 1
        EndIf

        If $i1 = $iParts And $iRemainder Then $iCurrent = $iRemainder
        Sleep($iCurrent)

    Next

    Return $iReturn
EndFunc

If (anywhere in the process) $bStateInterrupt evaluates to True the function will return 1 immediately (disregarding time left). It returns 0 if uninterrupted.

$iTimeSleep defines total duration (in ms) for Sleep().

$iTimeInterrupt defines delay (in ms) between periodic checks.

Breaking up total time enables OnEvent- and MessageLoop events to be processed after each segment (every 0.5 seconds if $iTimeInterrupt = 500). Visual (simplified) explanation:


问:
Can you color individual items in a data validation drop-down list in excel?
It's as simple as this. Say I want to color "COPT" and "RAT GCU" Yellow can I color just those?

I tried conditional formatting tricks and they all work after the drop down item is selected.

I want the colors to be loaded only to certain list items to appear as soon as I click the drop-down arrow.

I'm not sure if this can be done but...

Additionally would anyone know the syntax to click a button to set the value of the list back to displaying "Please select"???? I already have a reset button that unfilters everything. So if I tie it to that button I think it'd work like a charm. I just don't know how to go about selecting the listbox as it's a data validation one and I can't seem to figure out how to define/declare the listbox and can't find it's name anywhere.

答: There is no way to color items in the DV list. If you want the cell to show "Please Select" when no choice was made, all you can do is enter that literal text into the cell. An empty cell will remain empty.</p>


问:
Postgres query is not using index
I am facing very strange behavior of postgres query. I am having a table "p_MyTable" which is a partition of another table. "p_MyTable" has around 600 million records and has index ,

```<code>CREATE INDEX idx_p_MyTable_id ON MySchema.p_MyTable USING btree(IndColumn);
</code>```

When I execute the below query it runs in no time and gives result very fast. This is the query and explain plan.

```<code>    explain select max(IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"Result  (cost=4.85..4.86 rows=1 width=0)"
"  InitPlan 1 (returns $0)"
"    ->  Limit  (cost=0.57..4.85 rows=1 width=8)"
"          ->  Index Scan Backward using idx_p_MyTable_id on p_MyTable ms  (cost=0.57..727648341.49 rows=169996075 width=8)"
"                Index Cond: (IndColumn IS NOT NULL)"
"                Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_96 = 'EFG'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
</code>```

It works for aggregate function "min" as well in same way. But when I try for other functions , the explain plan changes and query does not execute in many minutes.

```<code>    explain select count(IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"Aggregate  (cost=53319339.50..53319339.51 rows=1 width=8)"
"  ->  Bitmap Heap Scan on p_MyTable ms  (cost=11209851.27..52894349.31 rows=169996075 width=8)"
"        Recheck Cond: (ent_attr_96 = 'EFG'::text)"
"        Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
"        ->  Bitmap Index Scan on p_MyTable_comp  (cost=0.00..11167352.25 rows=509988224 width=0)"
"              Index Cond: (ent_attr_96 = 'EFG'::text)"

explain select distinct (IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"HashAggregate  (cost=53319339.50..53319339.71 rows=21 width=8)"
"  Group Key: IndColumn"
"  ->  Bitmap Heap Scan on p_MyTable ms  (cost=11209851.27..52894349.31 rows=169996075 width=8)"
"        Recheck Cond: (ent_attr_96 = 'EFG'::text)"
"        Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
"        ->  Bitmap Index Scan on p_MyTable_comp  (cost=0.00..11167352.25 rows=509988224 width=0)"
"              Index Cond: (ent_attr_96 = 'EFG'::text)"

explain select avg (IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"Aggregate  (cost=53319339.50..53319339.51 rows=1 width=8)"
"  ->  Bitmap Heap Scan on p_MyTable ms  (cost=11209851.27..52894349.31 rows=169996075 width=8)"
"        Recheck Cond: (ent_attr_96 = 'EFG'::text)"
"        Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
"        ->  Bitmap Index Scan on p_MyTable_comp  (cost=0.00..11167352.25 rows=509988224 width=0)"
"              Index Cond: (ent_attr_96 = 'EFG'::text)"
</code>```

Please explain me, why the explain changes completely as I think if max/min are using index properly then it should work for other functions as well.

Thanks in advance.

答:
indexes are (mostly) used for either "where" conditions, or to help sorting ("order by").
(well indexes can be used for lots of other things, but for this case it will help to limit it to those cases)

The "max(IndColumn)" is misleading, because the query is rewritten as:

```<code>select IndColumn
from MySchema.p_MyTable ms
where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date
AND IndColumn is not null
ORDER by IndColumn desc
LIMIT 1
</code>```

So the index is used for "AND IndColumn is not null ORDER by IndColumn desc".

For your other queries you would need indexes for the columns in "where",
Something like

```<code>CREATE INDEX idx_p_foo ON MySchema.p_MyTable USING btree(ent_attr_96, ent_attr_97, ent_attr_98);
</code>```

might help.
Assuming that you have many queries that use those 3 columns.

You can also add the date. Though I am not sure this will help much, since it only is an end date, with no begin given.
So not sure if the query planer will use the date in the index. And if it does, the question is how many rows are filtered by the date, is it worth increasing the index size?

Title: Postgres query is not using index

Body:
I am facing very strange behavior of postgres query. I am having a table "p_MyTable" which is a partition of another table. "p_MyTable" has around 600 million records and has index ,

CREATE INDEX idx_p_MyTable_id ON MySchema.p_MyTable USING btree(IndColumn);

When I execute the below query it runs in no time and gives result very fast. This is the query and explain plan.

    explain select max(IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"Result  (cost=4.85..4.86 rows=1 width=0)"
"  InitPlan 1 (returns $0)"
"    ->  Limit  (cost=0.57..4.85 rows=1 width=8)"
"          ->  Index Scan Backward using idx_p_MyTable_id on p_MyTable ms  (cost=0.57..727648341.49 rows=169996075 width=8)"
"                Index Cond: (IndColumn IS NOT NULL)"
"                Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_96 = 'EFG'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"

It works for aggregate function "min" as well in same way. But when I try for other functions , the explain plan changes and query does not execute in many minutes.

    explain select count(IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"Aggregate  (cost=53319339.50..53319339.51 rows=1 width=8)"
"  ->  Bitmap Heap Scan on p_MyTable ms  (cost=11209851.27..52894349.31 rows=169996075 width=8)"
"        Recheck Cond: (ent_attr_96 = 'EFG'::text)"
"        Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
"        ->  Bitmap Index Scan on p_MyTable_comp  (cost=0.00..11167352.25 rows=509988224 width=0)"
"              Index Cond: (ent_attr_96 = 'EFG'::text)"

explain select distinct (IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"HashAggregate  (cost=53319339.50..53319339.71 rows=21 width=8)"
"  Group Key: IndColumn"
"  ->  Bitmap Heap Scan on p_MyTable ms  (cost=11209851.27..52894349.31 rows=169996075 width=8)"
"        Recheck Cond: (ent_attr_96 = 'EFG'::text)"
"        Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
"        ->  Bitmap Index Scan on p_MyTable_comp  (cost=0.00..11167352.25 rows=509988224 width=0)"
"              Index Cond: (ent_attr_96 = 'EFG'::text)"

explain select avg (IndColumn) from MySchema.p_MyTable ms where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date

"Aggregate  (cost=53319339.50..53319339.51 rows=1 width=8)"
"  ->  Bitmap Heap Scan on p_MyTable ms  (cost=11209851.27..52894349.31 rows=169996075 width=8)"
"        Recheck Cond: (ent_attr_96 = 'EFG'::text)"
"        Filter: ((ent_attr_97 = 'ABC'::text) AND (ent_attr_98 = 'HIJ'::text) AND ((ent_date_2)::date <= '2017-06-01'::date))"
"        ->  Bitmap Index Scan on p_MyTable_comp  (cost=0.00..11167352.25 rows=509988224 width=0)"
"              Index Cond: (ent_attr_96 = 'EFG'::text)"

Please explain me, why the explain changes completely as I think if max/min are using index properly then it should work for other functions as well.

Thanks in advance.

Body:
indexes are (mostly) used for either "where" conditions, or to help sorting ("order by").
(well indexes can be used for lots of other things, but for this case it will help to limit it to those cases)

The "max(IndColumn)" is misleading, because the query is rewritten as:

select IndColumn
from MySchema.p_MyTable ms
where ent_attr_97='ABC' and ent_attr_96='EFG' and ent_attr_98='HIJ'
and ent_date_2::date <= '2017-06-01 00:00:00'::date
AND IndColumn is not null
ORDER by IndColumn desc
LIMIT 1

So the index is used for "AND IndColumn is not null ORDER by IndColumn desc".

For your other queries you would need indexes for the columns in "where",
Something like

CREATE INDEX idx_p_foo ON MySchema.p_MyTable USING btree(ent_attr_96, ent_attr_97, ent_attr_98);

might help.
Assuming that you have many queries that use those 3 columns.

You can also add the date. Though I am not sure this will help much, since it only is an end date, with no begin given.
So not sure if the query planer will use the date in the index. And if it does, the question is how many rows are filtered by the date, is it worth increasing the index size?


问:
swiftyjson - Call can throw, but it is marked with 'try' and the error is not handled
I am trying to use swiftyjson and I am getting an Error:

Call can throw, but it is marked with 'try' and the error is not
  handled.

I have validated that my source JSON is good. I've been searching and cannot find a solution to this problem

```<code>import Foundation

class lenderDetails
{

func loadLender()
{

    let lenders = ""

    let url = URL(string: lenders)!
    let session =  URLSession.shared.dataTask(with: url)
    {
        (data, response, error) in

        guard let data = data else
        {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }

    session.resume()
}
}
</code>```

Thank you for all the help!

答:
The SwiftyJSON initializer throws, the declaration is

```<code>public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws
</code>```

You have three options:

Use a do - catch block and handle the error (the recommended one).

```<code>do {
   let json = try JSON(data: data)
   print(json)
} catch {
   print(error)
   // or display a dialog
}
</code>```

Ignore the error and optional bind the result (useful if the error does not matter).

```<code>if let json = try? JSON(data: data) {
   print(json)
}
</code>```

Force unwrap the result

```<code>let json = try! JSON(data: data)
print(json)
</code>```

Use this option only if it's guaranteed that the attempt will never fail (not in this case!). Try! can be used for example in FileManager if a directory is one of the default directories the framework creates anyway.

For more information please read Swift Language Guide - Error Handling

Body:
I am trying to use swiftyjson and I am getting an Error:

Call can throw, but it is marked with 'try' and the error is not
  handled.

I have validated that my source JSON is good. I've been searching and cannot find a solution to this problem

import Foundation

class lenderDetails
{

func loadLender()
{

    let lenders = ""

    let url = URL(string: lenders)!
    let session =  URLSession.shared.dataTask(with: url)
    {
        (data, response, error) in

        guard let data = data else
        {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }

    session.resume()
}
}

Thank you for all the help!

Body:
The SwiftyJSON initializer throws, the declaration is

public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws

You have three options:

Use a do - catch block and handle the error (the recommended one).

do {
   let json = try JSON(data: data)
   print(json)
} catch {
   print(error)
   // or display a dialog
}

Ignore the error and optional bind the result (useful if the error does not matter).

if let json = try? JSON(data: data) {
   print(json)
}

Force unwrap the result

let json = try! JSON(data: data)
print(json)

Use this option only if it's guaranteed that the attempt will never fail (not in this case!). Try! can be used for example in FileManager if a directory is one of the default directories the framework creates anyway.

For more information please read Swift Language Guide - Error Handling


问:
Existing process in a function
Is it possible or does it make sense to exit a node process in a function as I have here:

```<code>export function extractOptions(options){
  for (let option of options) {
    if(!option || option.length < 1){
      logMissing(option[0][0])
      process.exit(1)
      return []
    }
  }

  return options
}
</code>```

My test doesn't get back a [] if the if statement finds that there is no option or option length is 0.

答:
If you exit the process, your processing stops immediately.  You won't return a return value, b/c there's nothing running to return it to.  </p>

<p>If you exit the process with a non-false/null value (like process.exit(1)) you not only exit immediately, but the OS reports that an error has happened.  </p>

Title: Existing process in a function

Body:
Is it possible or does it make sense to exit a node process in a function as I have here:

export function extractOptions(options){
  for (let option of options) {
    if(!option || option.length < 1){
      logMissing(option[0][0])
      process.exit(1)
      return []
    }
  }

  return options
}

My test doesn't get back a [] if the if statement finds that there is no option or option length is 0.

Body:
If you exit the process, your processing stops immediately.  You won't return a return value, b/c there's nothing running to return it to.

If you exit the process with a non-false/null value (like process.exit(1)) you not only exit immediately, but the OS reports that an error has happened.


问:
RabbitMQ C# API Event based Message Consumption
```<code>while (true)
{
    BasicDeliverEventArgs e = (BasicDeliverEventArgs)Consumer.Queue.Dequeue();
    IBasicProperties properties = e.BasicProperties;
    byte[] body = e.Body;
    Console.WriteLine("Recieved Message : " + Encoding.UTF8.GetString(body));
    ch.BasicAck(e.DeliveryTag, false);
}
</code>```

This is what we do when we Retrieve Message by subscription..We use While Loop because we want Consumer to listen Continously..what if i want to make this even based..that is when a new message arrives in the queue at that time only Consumer should Consume the message..or on any such similar event..

答: use the RabbitMQ.Client.Events.EventingBasicConsumer for a eventing consumer instead of a blocking one.

Body:
while (true)
{
    BasicDeliverEventArgs e = (BasicDeliverEventArgs)Consumer.Queue.Dequeue();
    IBasicProperties properties = e.BasicProperties;
    byte[] body = e.Body;
    Console.WriteLine("Recieved Message : " + Encoding.UTF8.GetString(body));
    ch.BasicAck(e.DeliveryTag, false);
}

This is what we do when we Retrieve Message by subscription..We use While Loop because we want Consumer to listen Continously..what if i want to make this even based..that is when a new message arrives in the queue at that time only Consumer should Consume the message..or on any such similar event..


问:
Convert a scala Set of Strings to a Set of Long
how can I convert a Scala set of strings

```<code>val s = Set("1","2","3")
</code>```

to a set of long?

```<code>Set(1, 2, 3)
</code>```

Thanks!

答:
```<code>val s = Set("1","2","3")
val longs = s.map(_.toLong)
</code>```

Body:
how can I convert a Scala set of strings

val s = Set("1","2","3")

to a set of long?

Set(1, 2, 3)

Thanks!


问:
Selenium Grid: install chrome extensions on session
I need to use one chrome extension from Chrome Store in my test on Selenium Grid in Chrome browser, but I have some troubles :(

I tried to go to extension URL in browser (https://chrome.google.com/webstore/detail/...) and press key Install, but I can't confirm install in popup browser window

I tried to download crx extension file, but then i open it in browser I saw confirm windows and do not understand how to confirm installation

I tried to use this method - https://developer.chrome.com/extensions/external_extensions add JSON file and run browser - don't work, but I try it on Mac, not Linux

webdriver.remote can use only FireFox options (seleniumhq.github.io/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html)

If I use Selenium Grid I can't change Chrome browser start settings, can't add any keys :(

Maybe you know another method to install the extension on Selenium Grid browser session?

答:
You can use ChromeOptions.

```<code>ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
ChromeDriver driver = new ChromeDriver(options);
</code>```

Alternatively, you can add the options to an already existing DesiredCapabilities object.

```<code>// Add ChromeDriver-specific capabilities through ChromeOptions.
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
</code>```

You could also use a remote web driver:

```<code>DesiredCapabilities capability = DesiredCapabilities.chrome();
// above code goes here...
WebDriver driver = new RemoteWebDriver(new URL(hubUrl), capability);
</code>```

Body:
You can use ChromeOptions.

ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
ChromeDriver driver = new ChromeDriver(options);

Alternatively, you can add the options to an already existing DesiredCapabilities object.

// Add ChromeDriver-specific capabilities through ChromeOptions.
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

You could also use a remote web driver:

DesiredCapabilities capability = DesiredCapabilities.chrome();
// above code goes here...
WebDriver driver = new RemoteWebDriver(new URL(hubUrl), capability);


问:
Issue with AngularJS promises within a factory
I have an angularjs factory like this:

```<code>'use strict';

angular.module('frontRplApp')
    .factory('paymentService', function ($rootScope, $http, config, tools) {
        var urlBase = config.baseUrl;
        var paymentService = {

            response: {},

            create: function () {

                var args = {};

                return $http.post(urlBase + 'api/investor/payment/create', args);
            }
    });
</code>```

And I intend to use it inside a controller like this (the important issue is being to do something different if all went well or if there was an error)

```<code>$scope.order = function () {
            console.log('PaymentCashCtrl.order');
            $scope.disabledButtons.submitCashOrder = true;

            paymentService.create()
                    .then(
                            function (response) {
                                // do something with response

                            }, function (error) {
                                // do something with an error
                        }));
        };
</code>```

However my issue is that Id like to update some of the paymentService fields as the response of the $http.post is resolved and then return the promise so that the function(response) and function(error) callbacks in the controller keep working.

I tried with something like:

```<code>return $http.post(urlBase + 'api/investor/payment/create', args)
                        .then(function(response){
                            console.log(response);
                            this.response = response;
                            return response;
                        });
</code>```

But it doesnt work since the function(error) handler in the controller is never called.

I want to use my handlers in the controller but also make some updates when the $http.post response is resolved.

Thanks.

答:
Use $q

Change your factory code to this:

```<code>angular.module('frontRplApp')
    .factory('paymentService', function ($rootScope, $http, config, tools, $q) {
        var urlBase = config.baseUrl;
        var paymentService = {

            response: {},

            create: function () {
                var deferred = $q.defer();
                var args = {};

                $http.post(urlBase + 'api/investor/payment/create', args)
                .then(function(response){
                        console.log(response);
                        paymentService.response = response;
                        deferred.resolve(response);
                    }, function (error) {
                         deferred.reject(error);
                    });
                return deferred.promise;
            }
         };

      return paymentService;
    });
</code>```

Body:
I have an angularjs factory like this:

'use strict';

angular.module('frontRplApp')
    .factory('paymentService', function ($rootScope, $http, config, tools) {
        var urlBase = config.baseUrl;
        var paymentService = {

            response: {},

            create: function () {

                var args = {};

                return $http.post(urlBase + 'api/investor/payment/create', args);
            }
    });

And I intend to use it inside a controller like this (the important issue is being to do something different if all went well or if there was an error)

$scope.order = function () {
            console.log('PaymentCashCtrl.order');
            $scope.disabledButtons.submitCashOrder = true;

            paymentService.create()
                    .then(
                            function (response) {
                                // do something with response

                            }, function (error) {
                                // do something with an error
                        }));
        };

However my issue is that Id like to update some of the paymentService fields as the response of the $http.post is resolved and then return the promise so that the function(response) and function(error) callbacks in the controller keep working.

I tried with something like:

return $http.post(urlBase + 'api/investor/payment/create', args)
                        .then(function(response){
                            console.log(response);
                            this.response = response;
                            return response;
                        });

But it doesnt work since the function(error) handler in the controller is never called.

I want to use my handlers in the controller but also make some updates when the $http.post response is resolved.

Thanks.

Body:
Use $q

Change your factory code to this:

angular.module('frontRplApp')
    .factory('paymentService', function ($rootScope, $http, config, tools, $q) {
        var urlBase = config.baseUrl;
        var paymentService = {

            response: {},

            create: function () {
                var deferred = $q.defer();
                var args = {};

                $http.post(urlBase + 'api/investor/payment/create', args)
                .then(function(response){
                        console.log(response);
                        paymentService.response = response;
                        deferred.resolve(response);
                    }, function (error) {
                         deferred.reject(error);
                    });
                return deferred.promise;
            }
         };

      return paymentService;
    });


问:
Unknown plugin "transform-runtime" specified in "Users\\PhpstormProjects\\easy-essay\\.babelrc
I have download a github repository.

in the file called .babelrc.json, I have this:

```<code>{
  "presets": [
    "es2015",
    "stage-0"
  ],
  "plugins": [
    "transform-runtime",
    "add-module-exports",
    "transform-decorators-legacy"
  ]
}
</code>```

When I run gulp dev,  I get the following error:

ReferenceError: Unknown plugin "transform-runtime" specified in
  "C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\.babelrc" at
  0, attempted to resolve relative to "C:\Users\ \Tolotra
  Samuel\PhpstormProjects\easy-essay"
      at C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:180:17
      at Array.map (native)
      at Function.normalisePlugins (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:158:20)
      at OptionManager.mergeOptions (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:234:36)
      at OptionManager.init (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
      at compile (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-register\lib\node.js:103:45)
      at loader (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-register\lib\node.js:144:14)
      at Object.require.extensions.(anonymous function) [as .js] (C:\Users\Tolotra
  Samuel\PhpstormProjects\easy-essay\node_modules\babel-register\lib\node.js:154:7)
      at Module.load (module.js:488:32)
      at tryModuleLoad (module.js:447:12)

As mentionned in the readme file, I already ran npm install  and bower install.
What am I missing?

答:
```<code>yarn add babel-plugin-transform-runtime
</code>```

solved for me, what about for you?

or npm or bower.
But don't forget to refer to babel-plugin mentioned above. Its a lib from babel.
Looks like its a bug refered to install babel globally =)

prob you got an error refering to es2015 after so try this >

```<code>yarn add babel-plugin-transform-runtime babel-preset-es2015 babel-preset-stage-2 --dev
</code>```

Body:
I have download a github repository.

in the file called .babelrc.json, I have this:

{
  "presets": [
    "es2015",
    "stage-0"
  ],
  "plugins": [
    "transform-runtime",
    "add-module-exports",
    "transform-decorators-legacy"
  ]
}

When I run gulp dev,  I get the following error:

ReferenceError: Unknown plugin "transform-runtime" specified in
  "C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\.babelrc" at
  0, attempted to resolve relative to "C:\Users\ \Tolotra
  Samuel\PhpstormProjects\easy-essay"
      at C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:180:17
      at Array.map (native)
      at Function.normalisePlugins (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:158:20)
      at OptionManager.mergeOptions (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:234:36)
      at OptionManager.init (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
      at compile (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-register\lib\node.js:103:45)
      at loader (C:\Users\Tolotra Samuel\PhpstormProjects\easy-essay\node_modules\babel-register\lib\node.js:144:14)
      at Object.require.extensions.(anonymous function) [as .js] (C:\Users\Tolotra
  Samuel\PhpstormProjects\easy-essay\node_modules\babel-register\lib\node.js:154:7)
      at Module.load (module.js:488:32)
      at tryModuleLoad (module.js:447:12)

As mentionned in the readme file, I already ran npm install  and bower install.
What am I missing?

Body:
yarn add babel-plugin-transform-runtime

solved for me, what about for you?

or npm or bower.
But don't forget to refer to babel-plugin mentioned above. Its a lib from babel.
Looks like its a bug refered to install babel globally =)

prob you got an error refering to es2015 after so try this >

yarn add babel-plugin-transform-runtime babel-preset-es2015 babel-preset-stage-2 --dev


问:
C - a NON INT function example?
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

```<code>int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);
</code>```

I want a STRING example. I attempted to modify the above .. but I FAILED.

```<code>char cube(char n){
return n;
}

char *o;
o = cube("string");
</code>```

答:
Try this:</p>

```<code>#include <stdio.h>

char* getstr(const char* str){
     return str;
}

int main(void){
     char* mem; //string buffer
     mem=getstr("hello, world\n"); //save returned string
     printf(mem); //print string buffer
     return 0; //end program
}
</code>```

Title: C - a NON INT function example?

Body:
Unfortunately all of the  " C function examples " I come across are about "int"s (numbers).

I need a STRING example of a function.

This is a INT example:  ( works )

int cube(int n){
return n*n*n;
}

int o=1;
o = cube(2);

I want a STRING example. I attempted to modify the above .. but I FAILED.

char cube(char n){
return n;
}

char *o;
o = cube("string");

Body:
Try this:

#include <stdio.h>

char* getstr(const char* str){
     return str;
}

int main(void){
     char* mem; //string buffer
     mem=getstr("hello, world\n"); //save returned string
     printf(mem); //print string buffer
     return 0; //end program
}


问:
Calling an .exe without the extension, but with -i
I'm working on integrating the functions of a batch file into a larger PowerShell file (that does other things too) so I can eventually get rid of some smaller batch files.

I came across a line that looks like this:

```<code>if exist "C:\path\thing.exe"
("C:\path\thing" -i "C:\otherpath\something.dll")
</code>```

What is it referencing in the second line when it says the .exe name but with no file extension?

EDIT: I ran a /? on the .exe, I think this might be relevant:

```<code>/i <assembly_path> [ /r <...> ] [ /f ]
    Installs an assembly to the global assembly cache. <assembly_path> is the
    name of the file that contains the assembly manifest.
    Example: /i myDll.dll /r FILEPATH c:\projects\myapp.exe "My App"
</code>```

So I guess the -i is running the .exe using the .dll file as some kind of config file?

答:
On Windows, you can run executable files (with .exe suffix) without the extension from the command line.

So this is perfectly valid:

```<code>"C:\path\thing" -i "C:\otherpath\something.dll"
</code>```

In this command, -i is an argument to the executable. It is probable that the correct syntax is -i path\to\a\file.dll so the dll is used by the executable. It's difficult to say more since your question is very generic

To understand, try to run xcopy in CMD or PowerShell:

```<code>xcopy /?
</code>```

In this example, xcopy is the executable, corresponding to C:\System32\xcopy.exe and /? is an argument to the command, explaining all possible arguments supported by xcopy.

Actually, this works too:

```<code>C:\Windows\System32\xcopy.exe /?
</code>```

but since C:\Windows\System32 is listed in the %Path% environment variable, you can call xcopy directly without specifying its folder.

Body:
I'm working on integrating the functions of a batch file into a larger PowerShell file (that does other things too) so I can eventually get rid of some smaller batch files.

I came across a line that looks like this:

if exist "C:\path\thing.exe"
("C:\path\thing" -i "C:\otherpath\something.dll")

What is it referencing in the second line when it says the .exe name but with no file extension?

EDIT: I ran a /? on the .exe, I think this might be relevant:

/i <assembly_path> [ /r <...> ] [ /f ]
    Installs an assembly to the global assembly cache. <assembly_path> is the
    name of the file that contains the assembly manifest.
    Example: /i myDll.dll /r FILEPATH c:\projects\myapp.exe "My App"

So I guess the -i is running the .exe using the .dll file as some kind of config file?

Body:
On Windows, you can run executable files (with .exe suffix) without the extension from the command line.

So this is perfectly valid:

"C:\path\thing" -i "C:\otherpath\something.dll"

In this command, -i is an argument to the executable. It is probable that the correct syntax is -i path\to\a\file.dll so the dll is used by the executable. It's difficult to say more since your question is very generic

To understand, try to run xcopy in CMD or PowerShell:

xcopy /?

In this example, xcopy is the executable, corresponding to C:\System32\xcopy.exe and /? is an argument to the command, explaining all possible arguments supported by xcopy.

Actually, this works too:

C:\Windows\System32\xcopy.exe /?

but since C:\Windows\System32 is listed in the %Path% environment variable, you can call xcopy directly without specifying its folder.


问:
Rails find all order, found 0 results expected 2
I'm having trouble sorting my table based on the votes column, votes is a multivalued attribute so I use count and try to sort it based on that. here is the code

```<code>@topics = Topic.find(:all,:order=>'@topic.votes.count DESC')
</code>```

Rails returns an error that says

```<code>ActiveRecord::RecordNotFound in TopicsController#index
Couldn't find all Topics with 'id': (all, {:order=>"@topic.votes.count DESC"}) (found 0 results, but was looking for 2)
</code>```

Just starting out with rails and still confused with some things, your help will be much appreciated.

答:
Thanks to ahmed and snehal, I was able to find out the answer I'm looking for, which is</p>

```<code>Topic.left_outer_joins(:votes).group('topics.id').order('count(topics.id) DESC')
</code>```

Body:
I'm having trouble sorting my table based on the votes column, votes is a multivalued attribute so I use count and try to sort it based on that. here is the code

@topics = Topic.find(:all,:order=>'@topic.votes.count DESC')

Rails returns an error that says

ActiveRecord::RecordNotFound in TopicsController#index
Couldn't find all Topics with 'id': (all, {:order=>"@topic.votes.count DESC"}) (found 0 results, but was looking for 2)

Just starting out with rails and still confused with some things, your help will be much appreciated.

Body:
Thanks to ahmed and snehal, I was able to find out the answer I'm looking for, which is

Topic.left_outer_joins(:votes).group('topics.id').order('count(topics.id) DESC')


答:
in the factory, you need to return the functions paymentService object. also, don't resolve the promise inside the factory. resolve it in the controller.

```<code>.factory('paymentService', function($rootScope, $http, config, tools) {
    var urlBase = config.baseUrl;
    var paymentService = {

        response: {},

        create: function() {

            var args = {};

            return $http.post(urlBase + 'api/investor/payment/create', args);
        }
    }

    return paymentService;
});

$scope.order = function() {
    console.log('PaymentCashCtrl.order');
    $scope.disabledButtons.submitCashOrder = true;

    paymentService.create()
        .then(
            function(response) {
                // do something with response

            },
            function(error) {
                // do something with an error
            }));
};
</code>```

Title: Issue with AngularJS promises within a factory

Body:
in the factory, you need to return the functions paymentService object. also, don't resolve the promise inside the factory. resolve it in the controller.

.factory('paymentService', function($rootScope, $http, config, tools) {
    var urlBase = config.baseUrl;
    var paymentService = {

        response: {},

        create: function() {

            var args = {};

            return $http.post(urlBase + 'api/investor/payment/create', args);
        }
    }

    return paymentService;
});

$scope.order = function() {
    console.log('PaymentCashCtrl.order');
    $scope.disabledButtons.submitCashOrder = true;

    paymentService.create()
        .then(
            function(response) {
                // do something with response

            },
            function(error) {
                // do something with an error
            }));
};