问:
How to set or get parameter to DLL library in C#?
I have C++ library (32bit), which I would like to load and use in C#. The DLL is working (open connection, close connection and another methods without parameters). The problem is with unexpected results of all methods of C++ library with have parameters. For example:

C++ library methods specification:

```<code>unsigned int WINAPI acqStatus (WORD& stat, WORD& err);
unsigned int WINAPI getStatus (double& time, TCHAR* data);
</code>```

C# source code (extern methods):

```<code>    [DllImport("DllName.dll")]
    public static extern uint acqStatus(ref ushort stat, ref uint err);

    [DllImport("DllName.dll")]
    public static extern uint getStatus(ref double time, ref StringBuilder data);
</code>```

C# first method example (returns bad value, or Im doying mistake to convert IntPtr to integer):

```<code>        ushort stat = 0;
        uint err = 0;

        TCPInterface.acqStatus(ref stat, ref err);

        // Result of stat is: 0x0003 or 0x0004
        // bad value 3 (expected is 0), bad value 4 (expected is 1)
</code>```

Same situation I have with another method, with returns TCHAR*. Result is string (array of bytes). I dont know, how I get the string from data variable.

```<code>        double time;
        StringBuilder data = new StringBuilder();

        getStatus(out time, out data);

        // Exception:
        An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll

        Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
</code>```

I'm using 64bit Windows 7 and Visual Studio 2015. I sets my C# project to x86.

I tried to:

Marshal.Copy(...) or Marshal.ReadByte(...) Returns following exception:
An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Tried to run on x86 Windows 7: DLL result was the same (bad result).

Tried to change the IntPtr to byte[] I gets same exception like in Marshal.Copy()

Tried to change out with ref // not helped

Example 1 updated:

```<code>    [DllImport("DllName.dll")]
    public static unsafe extern int acqStatus(ref ushort* stat, ref uint* err);

        // Elsewhere in source code in unsafe method
        ushort* stat = 0;
        uint* err = 0;

        TCPInterface.acqStatus(ref stat, ref err);

        // I have following exception:
        An unhandled exception of type 'System.AccessViolationException' occurred in WindowsFormsApplication1.exe
        Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
</code>```

答:
That's because ToInt32() and ToString() don't work as you expect. These methods returns the memory address of the pointer, not the retrieved value.

For the first signature, change it to:

```<code>[DllImport("DllName.dll")]
// WORD C++ is equivalent to ushort in C#
public static extern uint acqStatus(ref ushort stat, ref ushort err);
</code>```

For the second it's a little bit more complicated without the exact implementation but a good try will be :

```<code>[DllImport("DllName.dll", CharSet = CharSet.Auto)]
public static extern uint getStatus(ref double time, StringBuilder data);
</code>```

Body:
I have C++ library (32bit), which I would like to load and use in C#. The DLL is working (open connection, close connection and another methods without parameters). The problem is with unexpected results of all methods of C++ library with have parameters. For example:

C++ library methods specification:

unsigned int WINAPI acqStatus (WORD& stat, WORD& err);
unsigned int WINAPI getStatus (double& time, TCHAR* data);

C# source code (extern methods):

    [DllImport("DllName.dll")]
    public static extern uint acqStatus(ref ushort stat, ref uint err);

    [DllImport("DllName.dll")]
    public static extern uint getStatus(ref double time, ref StringBuilder data);

C# first method example (returns bad value, or Im doying mistake to convert IntPtr to integer):

        ushort stat = 0;
        uint err = 0;

        TCPInterface.acqStatus(ref stat, ref err);

        // Result of stat is: 0x0003 or 0x0004
        // bad value 3 (expected is 0), bad value 4 (expected is 1)

Same situation I have with another method, with returns TCHAR*. Result is string (array of bytes). I dont know, how I get the string from data variable.

        double time;
        StringBuilder data = new StringBuilder();

        getStatus(out time, out data);

        // Exception:
        An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll

        Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I'm using 64bit Windows 7 and Visual Studio 2015. I sets my C# project to x86.

I tried to:

Marshal.Copy(...) or Marshal.ReadByte(...) Returns following exception:
An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Tried to run on x86 Windows 7: DLL result was the same (bad result).

Tried to change the IntPtr to byte[] I gets same exception like in Marshal.Copy()

Tried to change out with ref // not helped

Example 1 updated:

    [DllImport("DllName.dll")]
    public static unsafe extern int acqStatus(ref ushort* stat, ref uint* err);

        // Elsewhere in source code in unsafe method
        ushort* stat = 0;
        uint* err = 0;

        TCPInterface.acqStatus(ref stat, ref err);

        // I have following exception:
        An unhandled exception of type 'System.AccessViolationException' occurred in WindowsFormsApplication1.exe
        Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Body:
That's because ToInt32() and ToString() don't work as you expect. These methods returns the memory address of the pointer, not the retrieved value.

For the first signature, change it to:

[DllImport("DllName.dll")]
// WORD C++ is equivalent to ushort in C#
public static extern uint acqStatus(ref ushort stat, ref ushort err);

For the second it's a little bit more complicated without the exact implementation but a good try will be :

[DllImport("DllName.dll", CharSet = CharSet.Auto)]
public static extern uint getStatus(ref double time, StringBuilder data);


来源: stackexchange

问:
Spread Syntax with Map and Filter
I found this interesting problem and wanted to share with you guys.
The question is :

```<code>[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]
</code>```

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there

答: this part [-1,0,1].map((x)=> x+1) results in this list [0,1,2] then this part [0,1,...[-1,0,1].map((x)=> x+1)] results in [0,1,1,2] which after the filter part drops the 0 so it results into [1,1,2], finally the last element of the list is 7. So, altogether the result is [1,1,2,7]

ContentLicense: CC BY-SA 4.0

Title: Spread Syntax with Map and Filter

Body:
I found this interesting problem and wanted to share with you guys.
The question is :

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there

ContentLicense: CC BY-SA 3.0


问:
Shorten Dynamic SQL Query For Loop
I have a function that builds an sql query and then inserts it into the client-side light sql.

I think im using to many for loops, how would i make this shorter?

```<code>function insert(dataBase,table,row){
    var j = 0;

    var sqlQueryArray = [];

    sqlQueryArray[j++] = 'INSERT INTO ';
    sqlQueryArray[j++] = table
    sqlQueryArray[j++] = ' ('

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = row[i].id + ',';
    };

    sqlQueryArray[j++] = row[(row.length - 1)].id + '';
    sqlQueryArray[j++] = ')'
    var sqlQueryString = ' VALUES ';

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = '?, ';
    };

    sqlQueryArray[j++] = '?';
    sqlQueryArray[j++] = ');'

    for (var i = 0; i < sqlQueryArray.length; i++){
        sqlQueryString += sqlQueryArray[i];
    }
    var rowArray = []
    for (var i = row.length - 1; i >= 0; i--){
        rowArray[i] = row[i].val;
    };

    dataBase.openDatabase.transaction(
        function (transaction) {
            transaction.executeSql(sqlQueryString,
                rowArray,
                dataBase.nullSQLHandler, dataBase.QueryError);
        }
    );
}
</code>```

答:
Assuming you're using a relatively recent browser, you could do something like this:

```<code>var insertStatement =
   'INSERT INTO ' + table +
   ' (' + rows.map(function (row) { return row.id; }).join(', ') + ')' +
   ' VALUES (' + rows.map(function () { return '?'; }).join(', ') + ')';
</code>```

Whether you should or not is left as an exercise for the reader :)

Edit: I just noticed in a comment to another answer that you are sending this to the server for execution. You should definitely not do that, since a user could easily submit their own SQL and wreak all kinds of havoc on your database. You shouldn't trust any data received over the network.

ContentLicense: CC BY-SA 2.5

Title: Shorten Dynamic SQL Query For Loop

Body:
I have a function that builds an sql query and then inserts it into the client-side light sql.

I think im using to many for loops, how would i make this shorter?

function insert(dataBase,table,row){
    var j = 0;

    var sqlQueryArray = [];

    sqlQueryArray[j++] = 'INSERT INTO ';
    sqlQueryArray[j++] = table
    sqlQueryArray[j++] = ' ('

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = row[i].id + ',';
    };

    sqlQueryArray[j++] = row[(row.length - 1)].id + '';
    sqlQueryArray[j++] = ')'
    var sqlQueryString = ' VALUES ';

    for (var i = row.length - 2; i >= 0; i--){
        sqlQueryArray[j++] = '?, ';
    };

    sqlQueryArray[j++] = '?';
    sqlQueryArray[j++] = ');'

    for (var i = 0; i < sqlQueryArray.length; i++){
        sqlQueryString += sqlQueryArray[i];
    }
    var rowArray = []
    for (var i = row.length - 1; i >= 0; i--){
        rowArray[i] = row[i].val;
    };

    dataBase.openDatabase.transaction(
        function (transaction) {
            transaction.executeSql(sqlQueryString,
                rowArray,
                dataBase.nullSQLHandler, dataBase.QueryError);
        }
    );
}

Body:
Assuming you're using a relatively recent browser, you could do something like this:

var insertStatement =
   'INSERT INTO ' + table +
   ' (' + rows.map(function (row) { return row.id; }).join(', ') + ')' +
   ' VALUES (' + rows.map(function () { return '?'; }).join(', ') + ')';

Whether you should or not is left as an exercise for the reader :)

Edit: I just noticed in a comment to another answer that you are sending this to the server for execution. You should definitely not do that, since a user could easily submit their own SQL and wreak all kinds of havoc on your database. You shouldn't trust any data received over the network.


问:
How to send base64 encoded image string into JSON object in javascript?
I wanted to convert a image file into JSON object in javascript.
So I have converted image into a string using base64 encoding.
How to convert this string to JSON object?</p>

答: I would create a new Image() and set the src to the image.  Then onload of the image, draw it to a canvas (which can be in memory, doesn't need to be in the DOM), and from there use toDataURL().  See this page for more details: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL</p>


问:
Substring with large text file in java
I have a text file(253 MB Size) and I write this code:

```<code>    String content = new Scanner(new File ("C:\\Users\\user1\\IdeaProjects\\untitled\\file")).useDelimiter("\\Z").next();

    System.out.println(content.substring(19,26));
</code>```

but I get this error:

```<code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at java.nio.HeapCharBuffer.<init>(HeapCharBuffer.java:57)
at java.nio.CharBuffer.allocate(CharBuffer.java:335)
at java.util.Scanner.makeSpace(Scanner.java:840)
at java.util.Scanner.readInput(Scanner.java:795)
at java.util.Scanner.next(Scanner.java:1369)
</code>```

for use substring function in large file, What can I do ...
please help me...

答:
It seems terribly ineffective to read the whole file, if you need only a 7-letter substring. It really depends on your file structure, but if you're certain that all you need are bytes from positions 19..26 then you could simply read those bytes using RandomAccessFile, e.g.:

```<code>RandomAccessFile raf = new RandomAccessFile(new File("..."), "r"); // "r" means 'open the file for reading'
raf.seek(19L); // or other position depending on your file structure
byte[] b = new byte[7]; // choose how big the byte-buffer should be - how long is the substring
raf.read(b); // read from file into the buffer
System.out.println(new String(b)); // create a String from the byte-buffer
</code>```

Of course, you should choose a proper charset encoding when creating the String, depending on your input file, e.g. new String(b, "UTF-8")

Title: Substring with large text file in java

Body:
I have a text file(253 MB Size) and I write this code:

    String content = new Scanner(new File ("C:\\Users\\user1\\IdeaProjects\\untitled\\file")).useDelimiter("\\Z").next();

    System.out.println(content.substring(19,26));

but I get this error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at java.nio.HeapCharBuffer.<init>(HeapCharBuffer.java:57)
at java.nio.CharBuffer.allocate(CharBuffer.java:335)
at java.util.Scanner.makeSpace(Scanner.java:840)
at java.util.Scanner.readInput(Scanner.java:795)
at java.util.Scanner.next(Scanner.java:1369)

for use substring function in large file, What can I do ...
please help me...

Body:
It seems terribly ineffective to read the whole file, if you need only a 7-letter substring. It really depends on your file structure, but if you're certain that all you need are bytes from positions 19..26 then you could simply read those bytes using RandomAccessFile, e.g.:

RandomAccessFile raf = new RandomAccessFile(new File("..."), "r"); // "r" means 'open the file for reading'
raf.seek(19L); // or other position depending on your file structure
byte[] b = new byte[7]; // choose how big the byte-buffer should be - how long is the substring
raf.read(b); // read from file into the buffer
System.out.println(new String(b)); // create a String from the byte-buffer

Of course, you should choose a proper charset encoding when creating the String, depending on your input file, e.g. new String(b, "UTF-8")


问:
Python Requests: Allow more retries
I have a website that has two servers - one is dedicated to client-facing web services, and the other is a beefier data processing server.

I currently have a process in which the web server contacts the data server for multiple requests that typically look like this:

```<code>payload = {'req_type':'data_processing', 'sub_type':'data_crunch', 'id_num':12345}
r = requests.get('https://data.mywebsite.com/_api_route', params = payload)
</code>```

...which has been running like clockwork for the better part of the past year.  However, after creating a pandas-heavy function on the data server, I've been getting the following error (which I can't imagine has anything to do with pandas, but thought I'd throw it out there anyway):

```<code>HTTPSConnectionPool(host='data.mywebsite.com', port=443):
    Max retries exceeded with url: /_api_route?......
    (Caused by <class 'httplib.BadStatusLine'>: '')
</code>```

Both servers are running ubuntu, with python, and the Requests library to handle communication between the servers.

There is a similar question here:
Max retries exceeded with URL, but the OP is asking about contacting a server over which he has no control - I can code both sides, so I'm hoping I can change something on my data server, but am not sure what it would be.

答:
The solution would be, if you're not already, to use a container such as uWSGI or gunicorn to handle concurrency and, once again if you're not already, use Nginx or Apache to host the server. I've used uWSGI a fair amount and it's configuration is very straight forward. To create more processes to handle requests, you just need to set processes = 2 in your .ini file. You can also use Nginx or Apache to spawn processes, but uWSGI is built specifically for python and works wonderfully with Flask. I would advise you implement this is your haven't already, and then observe memory and processor usage as you increment the number processes until you find a good number that your server can handle.

EDIT: Just as a P.S. I run a Flask app on an Nginx server using uWSGI with fairly bare bones hardware (just 2.5Ghz dual core) and with 16 processes, I average about 40% cpu usage.

Title: Python Requests: Allow more retries

Body:
I have a website that has two servers - one is dedicated to client-facing web services, and the other is a beefier data processing server.

I currently have a process in which the web server contacts the data server for multiple requests that typically look like this:

payload = {'req_type':'data_processing', 'sub_type':'data_crunch', 'id_num':12345}
r = requests.get('https://data.mywebsite.com/_api_route', params = payload)

...which has been running like clockwork for the better part of the past year.  However, after creating a pandas-heavy function on the data server, I've been getting the following error (which I can't imagine has anything to do with pandas, but thought I'd throw it out there anyway):

HTTPSConnectionPool(host='data.mywebsite.com', port=443):
    Max retries exceeded with url: /_api_route?......
    (Caused by <class 'httplib.BadStatusLine'>: '')

Both servers are running ubuntu, with python, and the Requests library to handle communication between the servers.

There is a similar question here:
Max retries exceeded with URL, but the OP is asking about contacting a server over which he has no control - I can code both sides, so I'm hoping I can change something on my data server, but am not sure what it would be.


问:
No instance for (Show a) arising
ghci is giving me the error "No instance for (Show a) arising from use of 'commaSeperated'"

What im trying to do is define a show for my data Set that uses curly braces instead of square. What am I doing wrong here?

```<code>data Set a = Set [a]

instance Show (Set a) where
    show (Set a) = "{" ++ init (commaSeparated a) ++ "}"

commaSeparated :: Show a => [a] -> [Char]
commaSeparated [] = ""
commaSeparated (x:xs) = show x ++ "," ++ commaSeparated xs
</code>```

答: Your instance declaration does not have a context. Rewrite it as instance Show a => Show (Set a).

Title: No instance for (Show a) arising

Body:
ghci is giving me the error "No instance for (Show a) arising from use of 'commaSeperated'"

What im trying to do is define a show for my data Set that uses curly braces instead of square. What am I doing wrong here?

data Set a = Set [a]

instance Show (Set a) where
    show (Set a) = "{" ++ init (commaSeparated a) ++ "}"

commaSeparated :: Show a => [a] -> [Char]
commaSeparated [] = ""
commaSeparated (x:xs) = show x ++ "," ++ commaSeparated xs


问:
Bind bool to visibility property
I've searched this question a lot. But, it seems no solutions are working for me. I don't get any errors but I've added a breakpoint to my IValueConverter. The breakpoint does not ever get triggered. Why is it not using my converter? All I want to do is use view model strategy for visibility binding of a UI element (in this case a checkbox). Any help is appreciated.

IValueConverter:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace Test_Tool.Common
{
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language) => (bool)value ^ (parameter as string ?? string.Empty).Equals("Reverse") ? Visibility.Visible : Visibility.Collapsed;

        public object ConvertBack(object value, Type targetType, object parameter, string language) => (Visibility)value == Visibility.Visible ^ (parameter as string ?? string.Empty).Equals("Reverse");
    }
}
</code>```

XAML:

```<code><Page
    x:Class="Test_Tool.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test_Tool"
    xmlns:converter="using:Test_Tool.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.Resources>
            <converter:BooleanToVisibilityConverter x:Key="cvt" />
        </Grid.Resources>
        <Pivot x:Name="rootPivot" Title="Test Tool" >
            <PivotItem Header="Test Selection">
                <StackPanel>
                    <CheckBox x:Name="dppCheckBox" Content="DPP" Margin="5,8,5,5" Visibility="{Binding IsDirect, Converter={StaticResource cvt}}" />
                </StackPanel>
            </PivotItem>
        </Pivot>
    </Grid>
</Page>
</code>```

ViewModel:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Test_Tool.ViewModels
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        //Localized private vars
        private bool _isDirect;

        //Public vars for bindings
        public bool IsDirect
        {
            get
            {
                return _isDirect;
            }
            set
            {
                _isDirect = value;
                OnPropertyChanged();
            }
        }

        public MainPageViewModel()
        {
            //Any Initialization
            IsDirect = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName]string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

MainPage:

```<code>using DM_API_Test_Tool.ViewModels;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace Test_Tool
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPageViewModel ViewModel { get; set; }
        public MainPage()
        {
            this.InitializeComponent();
            this.ViewModel = new MainPageViewModel();
        }

    }
}
</code>```

答:
Try this

```<code>namespace Test_Tool.ViewModels
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        private bool _isDirect = false;
        public bool IsDirect
        {
            get
            {
                return _isDirect;
            }
            set
            {
                set { SetField(ref _isDirect, value, "isDirect"); }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
        protected bool SetField<T>(ref T field, T value, string propertyName)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}
</code>```

this should work now.

However I prefer the BindableBase method more (save the content below in a new class and call it something like BindableBase.cs)

```<code>using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Mvvm
{
    public abstract class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
        {
            if (object.Equals(storage, value)) return false;

            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var eventHandler = this.PropertyChanged;
            if (eventHandler != null)
            {
                eventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
</code>```

and then your ViewModel would be reduced to

```<code>using Mvvm;

namespace Test_Tool
{
    public class MainPageViewModel : BindableBase
    {
        private bool _isDirect = false;
        public bool IsDirect
        {
            get { return _isDirect; }
            set { SetProperty(ref _isDirect, value); }
        }
    }
}
</code>```

and one last thing: In your MainPage.xaml you want to bind to rootPivot, so you call

```<code>rootPivot.DataContext = null;
rootPivot.DataContext = new MainPageViewModel();
</code>```

or something like that.

Title: Bind bool to visibility property

Body:
I've searched this question a lot. But, it seems no solutions are working for me. I don't get any errors but I've added a breakpoint to my IValueConverter. The breakpoint does not ever get triggered. Why is it not using my converter? All I want to do is use view model strategy for visibility binding of a UI element (in this case a checkbox). Any help is appreciated.

IValueConverter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace Test_Tool.Common
{
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language) => (bool)value ^ (parameter as string ?? string.Empty).Equals("Reverse") ? Visibility.Visible : Visibility.Collapsed;

        public object ConvertBack(object value, Type targetType, object parameter, string language) => (Visibility)value == Visibility.Visible ^ (parameter as string ?? string.Empty).Equals("Reverse");
    }
}

XAML:

<Page
    x:Class="Test_Tool.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test_Tool"
    xmlns:converter="using:Test_Tool.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.Resources>
            <converter:BooleanToVisibilityConverter x:Key="cvt" />
        </Grid.Resources>
        <Pivot x:Name="rootPivot" Title="Test Tool" >
            <PivotItem Header="Test Selection">
                <StackPanel>
                    <CheckBox x:Name="dppCheckBox" Content="DPP" Margin="5,8,5,5" Visibility="{Binding IsDirect, Converter={StaticResource cvt}}" />
                </StackPanel>
            </PivotItem>
        </Pivot>
    </Grid>
</Page>

ViewModel:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Test_Tool.ViewModels
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        //Localized private vars
        private bool _isDirect;

        //Public vars for bindings
        public bool IsDirect
        {
            get
            {
                return _isDirect;
            }
            set
            {
                _isDirect = value;
                OnPropertyChanged();
            }
        }

        public MainPageViewModel()
        {
            //Any Initialization
            IsDirect = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName]string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainPage:

using DM_API_Test_Tool.ViewModels;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace Test_Tool
{
    ///
    /// An empty page that can be used on its own or navigated to within a Frame.
    ///
    public sealed partial class MainPage : Page
    {
        public MainPageViewModel ViewModel { get; set; }
        public MainPage()
        {
            this.InitializeComponent();
            this.ViewModel = new MainPageViewModel();
        }

    }
}

Body:
Try this

namespace Test_Tool.ViewModels
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        private bool _isDirect = false;
        public bool IsDirect
        {
            get
            {
                return _isDirect;
            }
            set
            {
                set { SetField(ref _isDirect, value, "isDirect"); }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
        protected bool SetField<T>(ref T field, T value, string propertyName)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}

this should work now.

However I prefer the BindableBase method more (save the content below in a new class and call it something like BindableBase.cs)

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Mvvm
{
    public abstract class BindableBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
        {
            if (object.Equals(storage, value)) return false;

            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var eventHandler = this.PropertyChanged;
            if (eventHandler != null)
            {
                eventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

and then your ViewModel would be reduced to

using Mvvm;

namespace Test_Tool
{
    public class MainPageViewModel : BindableBase
    {
        private bool _isDirect = false;
        public bool IsDirect
        {
            get { return _isDirect; }
            set { SetProperty(ref _isDirect, value); }
        }
    }
}

and one last thing: In your MainPage.xaml you want to bind to rootPivot, so you call

rootPivot.DataContext = null;
rootPivot.DataContext = new MainPageViewModel();

or something like that.


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
Answering your two subquestions there.

I've sometimes subclassed SGMLParser (included in the core Python distribution) and must say it's straight forward.

I don't think HTML lends itself to "well defined" regular expressions since it's not a regular language.

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

OwnerDisplayName: PEZ


问:
How can we know the exact number of the hardware performance counters built-in CPU?
After I have done several reading on Hardware Performance Counter, I can claim that all of the Intel processors have supported with Hardware Performance Counter. So, In order to access these additional hardware registers ,i.e. hardware performance counters, I have used PAPI infrastructure frequently used to access and configure these counters.

When I used papi_avail utility program to  report information about number hardware counters, unexpected value was viewed, i.e. with respect to Fig, number hardware counters : 0. Could it be?

With respect to my processors model (Intel core i7), I think this is incorrect value.

I really appreciate any help you can provide.

答: Take a look at Chapters 18 "Performance Monitoring" and 19 "Performance-Monitoring Events" portion of the Intel® 64 and IA-32 Architectures Software Developer Manuals volume 3B (latest version here).


问:
How to compare 2 vectors and create a separate vector based on the comparison
i'm looking at creating an algorithm that will compare 2 vectors (v1,v2), and create a new vector v3 that will hold the values not shared between v1 and v2.

```<code>#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int args[])
{
vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
vector<int> v2 = { 1,2,6 };
vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

return 0;
}
</code>```

The vectors will always be sorted.

答:
Sorry to trouble  and add new answer here. NathanOliver has given precise answer.
 But for fun if I had to write my own function to implement this, I tried it on arrays instead of vector, (for changing code for vector will be trivial task).

Adding my code snippet here.

```<code>#include<iostream>

using namespace std;

int arr1[]={2,3,6,10};
int arr2[]={3,5,7,9,10};

int result[10];
int result_size=0;

void getUncommonValues(int *arr1, int size1, int *arr2, int size2){
    if ( (size1 == 0) && (size2 == 0) )
        return;

    if( size1 == 0){
        result_size=size2;
        for (int i=0; i < size2; i++)
            result[i] = arr2[i];
    }

    if (size2 == 0){
        result_size=size1;
        for (int i=0; i < size1; i++)
            result[i] = arr1[i];
    }

    int i1=0, i2=0;
    while (size1 > i1){
        if ( arr1[i1] < arr2[i2]){
            result[result_size++] = arr1[i1++];
        } else{
            if ( arr2[i2] < arr1[i1] )
                result[result_size++] = arr2[i2++];
            else{
                i1++; i2++;
            }
        }
        if ( i2 == size2 ){
            for ( ; i1 < size1; i1++)
                result[result_size++] = arr1[i1];
        }
    }

    for ( ; i2 < size2 ; i2++){
        result[result_size++] = arr2[i2];
    }
}

int main(){
    getUncommonValues(arr1,sizeof(arr1)/sizeof(int), arr2,sizeof(arr2)/sizeof(int));
    for (int i =0; i<result_size; i++)
        cout << result[i] <<" ,";

    cout << endl;
    return 0;
}
</code>```

Note : here the result is stored in global array and has fixed size.
   This can be resolved in vector directly.

Body:
i'm looking at creating an algorithm that will compare 2 vectors (v1,v2), and create a new vector v3 that will hold the values not shared between v1 and v2.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int args[])
{
vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
vector<int> v2 = { 1,2,6 };
vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

return 0;
}

The vectors will always be sorted.

Body:
Sorry to trouble  and add new answer here. NathanOliver has given precise answer.
 But for fun if I had to write my own function to implement this, I tried it on arrays instead of vector, (for changing code for vector will be trivial task).

Adding my code snippet here.

#include<iostream>

using namespace std;

int arr1[]={2,3,6,10};
int arr2[]={3,5,7,9,10};

int result[10];
int result_size=0;

void getUncommonValues(int *arr1, int size1, int *arr2, int size2){
    if ( (size1 == 0) && (size2 == 0) )
        return;

    if( size1 == 0){
        result_size=size2;
        for (int i=0; i < size2; i++)
            result[i] = arr2[i];
    }

    if (size2 == 0){
        result_size=size1;
        for (int i=0; i < size1; i++)
            result[i] = arr1[i];
    }

    int i1=0, i2=0;
    while (size1 > i1){
        if ( arr1[i1] < arr2[i2]){
            result[result_size++] = arr1[i1++];
        } else{
            if ( arr2[i2] < arr1[i1] )
                result[result_size++] = arr2[i2++];
            else{
                i1++; i2++;
            }
        }
        if ( i2 == size2 ){
            for ( ; i1 < size1; i1++)
                result[result_size++] = arr1[i1];
        }
    }

    for ( ; i2 < size2 ; i2++){
        result[result_size++] = arr2[i2];
    }
}

int main(){
    getUncommonValues(arr1,sizeof(arr1)/sizeof(int), arr2,sizeof(arr2)/sizeof(int));
    for (int i =0; i<result_size; i++)
        cout << result[i] <<" ,";

    cout << endl;
    return 0;
}

Note : here the result is stored in global array and has fixed size.
   This can be resolved in vector directly.


问:
show message if listview is empty react native
If List View is empty, I would like to show the header(Which is happening) and also show a alternate Text saying "List is Empty".

I tried doing getRowCount(), which returns 0. But how can I insert the text in the same view.

`

```<code><Image source={require('./img/background.png')}  style={GlobalStyles.bgImageContainer}>

            <ListView style={{margin: 5}}
                      initialListSize={10}
                      dataSource={this.state.familydataSource}
                      renderRow={this.renderRow}
                      renderSeparator={::this._renderSeparator}
                      renderSectionHeader={this.renderFamilySectionHeader}
                      enableEmptySections={true}
            />

            <ListView style={{margin: 5}}
                      dataSource={this.state.friendsdataSource}
                      renderRow={this.renderRow}
                      renderSeparator={::this._renderSeparator}
                      renderSectionHeader={this.renderFriendsSectionHeader}
                      enableEmptySections={true}
            />

        </Image>
</code>```

`

答:
I initially misunderstood what you meant by header, thinking it was a component separate from the ListView. To show a separate message in addition to the ListView (instead of as a replacement to it), I would use the flex style to determine whether the ListView should take up the full height or just a percentage. In that later case you can render your message below the ListView so that both appear.

You can separate the rendering of the ListView and message into two functions like so:

```<code>_renderMessage() {
    return (
        <View style={{ flex:0.5 }}>
            <Text>List is Empty</Text>
        </View>
    )
}

render() {
    const listViewProportion = this.state.dataSource.getRowCount() == 0 ? 0.5 : 1
    return (
        <View style={{ flex:1 }}>
            <ListView
                style={{ flex: listViewProportion }}
                ...
            />
            {if (listViewProportion != 1) {
                this._renderMessage()
            }}
        </View>
    )
}
</code>```

Body:
If List View is empty, I would like to show the header(Which is happening) and also show a alternate Text saying "List is Empty".

I tried doing getRowCount(), which returns 0. But how can I insert the text in the same view.

`

<Image source={require('./img/background.png')}  style={GlobalStyles.bgImageContainer}>

            <ListView style={{margin: 5}}
                      initialListSize={10}
                      dataSource={this.state.familydataSource}
                      renderRow={this.renderRow}
                      renderSeparator={::this._renderSeparator}
                      renderSectionHeader={this.renderFamilySectionHeader}
                      enableEmptySections={true}
            />

            <ListView style={{margin: 5}}
                      dataSource={this.state.friendsdataSource}
                      renderRow={this.renderRow}
                      renderSeparator={::this._renderSeparator}
                      renderSectionHeader={this.renderFriendsSectionHeader}
                      enableEmptySections={true}
            />

        </Image>

`

Body:
I initially misunderstood what you meant by header, thinking it was a component separate from the ListView. To show a separate message in addition to the ListView (instead of as a replacement to it), I would use the flex style to determine whether the ListView should take up the full height or just a percentage. In that later case you can render your message below the ListView so that both appear.

You can separate the rendering of the ListView and message into two functions like so:

_renderMessage() {
    return (
        <View style={{ flex:0.5 }}>
            <Text>List is Empty</Text>
        </View>
    )
}

render() {
    const listViewProportion = this.state.dataSource.getRowCount() == 0 ? 0.5 : 1
    return (
        <View style={{ flex:1 }}>
            <ListView
                style={{ flex: listViewProportion }}
                ...
            />
            {if (listViewProportion != 1) {
                this._renderMessage()
            }}
        </View>
    )
}


问:
How to get all custom post types in wordpress?
I am trying to make a shortcode for Visual Composer. I have to get all the custom post types as dropdown. I am using the get_post_types() function, but it returns an empty array.

Here is my code:

```<code> /*Post type shortcode*/
 add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );
</code>```

}

I have also tried to get it in the functions.php but result is same.

I also used add_action('init',"function_name');, it works within the hook but not outside of the hook.

Can any one help me please?

答:
Try with admin_init hook, which runs after init:

```<code>/*Post type shortcode*/
add_action( 'admin_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );

}
</code>```

Body:
I am trying to make a shortcode for Visual Composer. I have to get all the custom post types as dropdown. I am using the get_post_types() function, but it returns an empty array.

Here is my code:

 /*Post type shortcode*/
 add_action( 'vc_before_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );

}

I have also tried to get it in the functions.php but result is same.

I also used add_action('init',"function_name');, it works within the hook but not outside of the hook.

Can any one help me please?

Body:
Try with admin_init hook, which runs after init:

/*Post type shortcode*/
add_action( 'admin_init', 'post_type_shortcode');
function post_type_shortcode(){
$args = array( 'public' => true, '_builtin' => false );
$output = 'names'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
vc_map( array(
    "name" => __( "Display Post Type", "saue" ),
    "description" => "Display post type",
    "base" => "display_post_type",
    "class" => "",
    "category" => __( "Saue Theme", "saue"),
    "params" => array(
        array(
            "type"          => "dropdown",
                    //"holder"        => "div",
            "heading"       => __( "Post Type", "saue" ),
            "admin_label" => true,
            "param_name"    => "post_type",
            "value"         => $custom_post_types,
            ),
        )
    ) );

}


问:
String in list, into a function
```<code>myList = ['100', 'sin(x)', '0', '1']
</code>```

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

```<code>myList[1].replace("'", "")
</code>```

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

```<code>from math import sin
def f(x):
    return myList[1]
</code>```

Thus f(x) will give the computed value of sin(x) from this list.

答:
Sin function is part of math library, you can get it like:

```<code>import math
getattr(math, 'sin')
</code>```

That is same for all non-builtin libraries. Just split the string to get function name:

```<code>function_name = myList[1].split('(')[0]
function = getattr(math, function_name)
function(value for x)
</code>```

For builtin functions like round:

```<code>getattr(globals()['__builtins__'], 'round')
</code>```

Title: String in list, into a function

Body:
myList = ['100', 'sin(x)', '0', '1']

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

myList[1].replace("'", "")

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

from math import sin
def f(x):
    return myList[1]

Thus f(x) will give the computed value of sin(x) from this list.

Body:
Sin function is part of math library, you can get it like:

import math
getattr(math, 'sin')

That is same for all non-builtin libraries. Just split the string to get function name:

function_name = myList[1].split('(')[0]
function = getattr(math, function_name)
function(value for x)

For builtin functions like round:

getattr(globals()['__builtins__'], 'round')


问:
Evaluate string from user to comma separated words string
Let's say I have a string given by user in the following form:

```<code>"single, single, double word, single  word, also      single"
</code>```

How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator and replaced with ',', and each single is replaced with %20 ? So the result would be:

```<code>"single,single,double%20word,single,word,also,single"
</code>```

? can I do it in one step ?

答:
This does what you ask:

```<code>def repl(m):
  if m.group(0) == ' ':
    return '%20'
  else:
    return ','

re.sub(',? +', repl, "single, single, double word, single  word, also      single")
</code>```

However, if your goal is to end up with proper URL escaping I'd advise that you actually use a library function designed to do that. eg: urllib.quote

Body:
Let's say I have a string given by user in the following form:

"single, single, double word, single  word, also      single"

How I can parse this string to obtain string of comma separated words, where each not single whitespace is treated as a separator and replaced with ',', and each single is replaced with %20 ? So the result would be:

"single,single,double%20word,single,word,also,single"

? can I do it in one step ?

Body:
This does what you ask:

def repl(m):
  if m.group(0) == ' ':
    return '%20'
  else:
    return ','

re.sub(',? +', repl, "single, single, double word, single  word, also      single")

However, if your goal is to end up with proper URL escaping I'd advise that you actually use a library function designed to do that. eg: urllib.quote


问:
Ionic 2 loadingController cssClass not working
I want my loadingController wrapper to be shown with a customized css style but the css's rules doesn't apply to the element (the loadingController wrapper).

I have this in my component:

```<code>ionViewDidLoad() {
    let loader = this.loadingController.create({
        spinner: 'bubbles',
        content: 'getting data...',
        cssClass: 'loadingwrapper'
    });
    loader.present().then(() => {
        //some stuff
        ...
        loader.dismiss();
    });
}
</code>```

and this in my css file:

```<code>.loadingwrapper{
    width: 77% !important;
    height: 15% !important;
    color: black !important;
    font-size: 1.25em !important;
    background-color: aliceblue !important;
    border-radius: 10px !important;
}
</code>```

In spite of doing this (I've even tried whithout "!important"), the changes (none of them) doesn't apply to the loading wrapper and it shows a bit awful.

答:
Not sure where you are applying the css but if you are applying the css in the page component file you going to have a hard time, because the loading controller sits outside the page selector. So if your page component name is Foobar and you have a .scss file foobar.scss

```<code>page-foobar{
    .loadingwrapper{
        // not going to work
    }
}
</code>```

you can either add it globally to your app/app.scss file or ( i think this will work )

```<code>.md,.ios,.wp{
    page-foobar{
       .loadingwrapper{
        // styles!
       }
    }
}
</code>```

Body:
I want my loadingController wrapper to be shown with a customized css style but the css's rules doesn't apply to the element (the loadingController wrapper).

I have this in my component:

ionViewDidLoad() {
    let loader = this.loadingController.create({
        spinner: 'bubbles',
        content: 'getting data...',
        cssClass: 'loadingwrapper'
    });
    loader.present().then(() => {
        //some stuff
        ...
        loader.dismiss();
    });
}

and this in my css file:

.loadingwrapper{
    width: 77% !important;
    height: 15% !important;
    color: black !important;
    font-size: 1.25em !important;
    background-color: aliceblue !important;
    border-radius: 10px !important;
}

In spite of doing this (I've even tried whithout "!important"), the changes (none of them) doesn't apply to the loading wrapper and it shows a bit awful.

Body:
Not sure where you are applying the css but if you are applying the css in the page component file you going to have a hard time, because the loading controller sits outside the page selector. So if your page component name is Foobar and you have a .scss file foobar.scss

page-foobar{
    .loadingwrapper{
        // not going to work
    }
}

you can either add it globally to your app/app.scss file or ( i think this will work )

.md,.ios,.wp{
    page-foobar{
       .loadingwrapper{
        // styles!
       }
    }
}


Title: Spread Syntax with Map and Filter

Body:
I found this interesting problem and wanted to share with you guys.
The question is :

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there

Body:
[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x),7] broken down:

[-1,0,1].map((x)=> x+1) // [0,1,2]

[0,1,...[-1,0,1].map((x)=> x+1)] // [0,1,0,1,2]

[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x) // [1,1,2]

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x),7] // [1,1,2,7]


问:
Merging data frames on a specific key in R/Stripping asterisks from Column
Hey guys I need help merging in R and here is a reproducible sample of my code which I will explain.

My issue I'm running into is certain guys in the fixedstats df are hall of famers and therefor they have asterisks in their name. I want to clean that so I can join them to the draft database and grab their draft year. When I do so with the code I'm running into an error that gives me:

Error in order(Player = list("Tariq Abdul-Wahad", "Shareef Abdur-Rahim",  :
  unimplemented type 'list' in 'orderVector1'

How do you guys recommend I go about stripping the asterisks from the columns in order to properly join the two data frames on the Player Key? Thanks in Advance.

Code:

```<code>library(htmltab)
library(sqldf)
library(plyr)
library(readr)

stats0 <- ""
draftbank0 <- ""

for (i in 20003:2017){

  url <- paste0("http://www.basketball-reference.com/leagues/NBA_",i,"_advanced.html")
  stats <- htmltab(doc = url, which = 1, header = 1, stringsasfactors = FALSE)
  stats$year <- i

  stats0 <- rbind(stats0,stats)

  stats0[rowSums(is.na(stats0)) != ncol(stats0),]

}

colnames(stats0) <- c("Rank",
                  "Player",
                  "Pos",
                  "Age",
                  "Tm",
                  "G",
                  "MP",
                  "PER",
                  "TSp",
                  "ThreePAr",
                  "FTr",
                  "ORBp",
                  "DRBp",
                  "TRBp",
                  "ASTp",
                  "STLp",
                  "BLKp",
                  "TOVp",
                  "USGp",
                  "Null", #comment out null if needed
                  "OWS",
                  "DWS",
                  "WS",
                  "WS48",
                  "Null2", #comment out null if needed
                  "OBPM",
                  "DBPM",
                  "BPM",
                  "VORP",
                  "Year")

fixedstats <- sqldf("SELECT Rank, Player, Pos, Age, Tm, G, MP, PER, TSp, ThreePAr, FTr, ORBp, DRBp, TRBp, ASTp, STLp, BLKp, TOVp,
                USGp, OWS, DWS, WS, WS48, OBPM, DBPM, BPM, VORP, Year FROM stats0 WHERE player != 'Player'")

fixedstats <- fixedstats[-1,]

for (i in 1980:2016){

  url2 <- paste0("http://www.draftexpress.com/nba-mock-history/",i,"/all/all/")
  draftbank <- htmltab(doc = url2, which = 1, header = 1, stringsasfactors = FALSE)

  draftbank0 <- rbind(draftbank0,draftbank)

}

colnames(draftbank0) <- c("Draft_Year",
                      "Pick",
                      "Null1",
                      "Player",
                      "Null2",
                      "Position",
                      "Age",
                      "Height",
                      "Weight",
                      "Wingspan",
                      "Points",
                      "Rebounds",
                      "Assists",
                      "PER",
                      "Null3",
                      "League",
                      "EWA")

draftbankfinal <- sqldf("SELECT Player, Position, Age, Height, Wingspan, Draft_Year FROM draftbank0")

draftbankfinal <- draftbank0[-1,]

#Multiple drafts appendix getting rid of guys with similar names
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Corey Brewer" &  draftbankfinal$Draft_Year==1998),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Patrick Ewing" & draftbankfinal$Draft_Year==1985),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Charles Smith" & draftbankfinal$Draft_Year==1988),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Ray McCallum" & draftbankfinal$Draft_Year==1983),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="James Anderson" & draftbankfinal$Draft_Year==1985),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Ken Johnson" & draftbankfinal$Draft_Year==1985),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Dee Brown" & draftbankfinal$Draft_Year==1990),]

fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[*]", replacement = "")
fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[']", replacement = "")

fixedstats$Player <- ifelse(fixedstats$Player == 'Jermaine ONeal', 'Jermaine O\'Neal', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'J.J Obrien', 'J.J O\'Brien', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'Johnny OBryant', 'Johnny O\'Bryant', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'Patrick OBryant', 'Patrick O\'Bryant', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'Shaquille ONeal', 'Shaquille O\'Neal', fixedstats$Player)

fixedstats$Player <- as.vector(fixedstats$Player)
draftbankfinal$Player <- as.vector(draftbankfinal$Player)

df <- merge(x = fixedstats, y = draftbankfinal, by = "Player", all.x = TRUE)
df2 <- df[c(1,3:5,22,28:29,32:35)]
</code>```

答:
So if anyone is curious and runs into this issue in the future, the answer is I used lapply (returning as list) instead of using vapply (returning as vector) so

```<code>fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[*]", replacement = "")
fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[']", replacement = "")

fixedstats$Player <- as.vector(fixedstats$Player)
draftbankfinal$Player <- as.vector(draftbankfinal$Player)
</code>```

should actually be

```<code>fixedstats$Player <- vapply(fixedstats$Player, sub, pattern = "[*]", replacement = "",character(1))
fixedstats$Player <- vapply(fixedstats$Player, sub, pattern = "[']", replacement = "",character(1))
</code>```

Body:
Hey guys I need help merging in R and here is a reproducible sample of my code which I will explain.

My issue I'm running into is certain guys in the fixedstats df are hall of famers and therefor they have asterisks in their name. I want to clean that so I can join them to the draft database and grab their draft year. When I do so with the code I'm running into an error that gives me:

Error in order(Player = list("Tariq Abdul-Wahad", "Shareef Abdur-Rahim",  :
  unimplemented type 'list' in 'orderVector1'

How do you guys recommend I go about stripping the asterisks from the columns in order to properly join the two data frames on the Player Key? Thanks in Advance.

Code:

library(htmltab)
library(sqldf)
library(plyr)
library(readr)

stats0 <- ""
draftbank0 <- ""

for (i in 20003:2017){

  url <- paste0("http://www.basketball-reference.com/leagues/NBA_",i,"_advanced.html")
  stats <- htmltab(doc = url, which = 1, header = 1, stringsasfactors = FALSE)
  stats$year <- i

  stats0 <- rbind(stats0,stats)

  stats0[rowSums(is.na(stats0)) != ncol(stats0),]

}

colnames(stats0) <- c("Rank",
                  "Player",
                  "Pos",
                  "Age",
                  "Tm",
                  "G",
                  "MP",
                  "PER",
                  "TSp",
                  "ThreePAr",
                  "FTr",
                  "ORBp",
                  "DRBp",
                  "TRBp",
                  "ASTp",
                  "STLp",
                  "BLKp",
                  "TOVp",
                  "USGp",
                  "Null", #comment out null if needed
                  "OWS",
                  "DWS",
                  "WS",
                  "WS48",
                  "Null2", #comment out null if needed
                  "OBPM",
                  "DBPM",
                  "BPM",
                  "VORP",
                  "Year")

fixedstats <- sqldf("SELECT Rank, Player, Pos, Age, Tm, G, MP, PER, TSp, ThreePAr, FTr, ORBp, DRBp, TRBp, ASTp, STLp, BLKp, TOVp,
                USGp, OWS, DWS, WS, WS48, OBPM, DBPM, BPM, VORP, Year FROM stats0 WHERE player != 'Player'")

fixedstats <- fixedstats[-1,]

for (i in 1980:2016){

  url2 <- paste0("http://www.draftexpress.com/nba-mock-history/",i,"/all/all/")
  draftbank <- htmltab(doc = url2, which = 1, header = 1, stringsasfactors = FALSE)

  draftbank0 <- rbind(draftbank0,draftbank)

}

colnames(draftbank0) <- c("Draft_Year",
                      "Pick",
                      "Null1",
                      "Player",
                      "Null2",
                      "Position",
                      "Age",
                      "Height",
                      "Weight",
                      "Wingspan",
                      "Points",
                      "Rebounds",
                      "Assists",
                      "PER",
                      "Null3",
                      "League",
                      "EWA")

draftbankfinal <- sqldf("SELECT Player, Position, Age, Height, Wingspan, Draft_Year FROM draftbank0")

draftbankfinal <- draftbank0[-1,]

#Multiple drafts appendix getting rid of guys with similar names
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Corey Brewer" &  draftbankfinal$Draft_Year==1998),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Patrick Ewing" & draftbankfinal$Draft_Year==1985),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Charles Smith" & draftbankfinal$Draft_Year==1988),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Ray McCallum" & draftbankfinal$Draft_Year==1983),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="James Anderson" & draftbankfinal$Draft_Year==1985),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Ken Johnson" & draftbankfinal$Draft_Year==1985),]
draftbankfinal<-draftbankfinal[!(draftbankfinal$Player=="Dee Brown" & draftbankfinal$Draft_Year==1990),]

fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[*]", replacement = "")
fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[']", replacement = "")

fixedstats$Player <- ifelse(fixedstats$Player == 'Jermaine ONeal', 'Jermaine O\'Neal', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'J.J Obrien', 'J.J O\'Brien', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'Johnny OBryant', 'Johnny O\'Bryant', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'Patrick OBryant', 'Patrick O\'Bryant', fixedstats$Player)
fixedstats$Player <- ifelse(fixedstats$Player == 'Shaquille ONeal', 'Shaquille O\'Neal', fixedstats$Player)

fixedstats$Player <- as.vector(fixedstats$Player)
draftbankfinal$Player <- as.vector(draftbankfinal$Player)

df <- merge(x = fixedstats, y = draftbankfinal, by = "Player", all.x = TRUE)
df2 <- df[c(1,3:5,22,28:29,32:35)]

Body:
So if anyone is curious and runs into this issue in the future, the answer is I used lapply (returning as list) instead of using vapply (returning as vector) so

fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[*]", replacement = "")
fixedstats$Player <- lapply(fixedstats$Player, sub, pattern = "[']", replacement = "")

fixedstats$Player <- as.vector(fixedstats$Player)
draftbankfinal$Player <- as.vector(draftbankfinal$Player)

should actually be

fixedstats$Player <- vapply(fixedstats$Player, sub, pattern = "[*]", replacement = "",character(1))
fixedstats$Player <- vapply(fixedstats$Player, sub, pattern = "[']", replacement = "",character(1))


问:
HTML Element not centering even it has a width, and is a block
I searched for a long while, but all of them said to give a width, make display block, and set text-align.
I maked this for welcome card.
It also worked for the first card too.
But it doesn't work for second card Icon and text.

First one works, but second doesn't:

```<code>    <div class="mdl-grid" id="sub-content">
<!--First Card-->
    <div class="mdl-cell mdl-cell--4-col main-card-medium mdl-shadow--2dp">
        <i class="sub-icon material-icons slideanim">book</i>
        <div class="mdl-card__title slideanim">
            <h2 class="mdl-card__title-text subcontent-title">All-Inclusive</h2>
        </div>
        <div class="mdl-card__supporting-text subcontent-title slideanim">
            This app contains all info about Champions, Summoners, Items, Runes and Masteries.
        </div>
    </div>
<!--Second Card-->
    <div class="mdl-cell mdl-cell--4-col main-card-medium mdl-shadow--2dp">
        <i class="sub-icon material-icons slideanim">wifi_perm</i>
        <div class="mdl-card__title slideanim">
            <h2 class="mdl-card__title-text subcontent-title">Test Your Ping</h2>
        </div>
        <div class="mdl-card__supporting-text subcontent-title slideanim">
            You can check your ping for all servers.
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.main-card-medium {
    width: 25%;
    display: block;
}

.mdl-cell--4-col {
    margin: auto;
}

.sub-icon {
    font-size: 100px;
    margin: 30px 0px;
    color: #3f51b5;
    width: 100%;
    display: inline-block;
    text-align: center;
}

.sub-content {
    background: #3E4EB8;
}

.subcontent-title {
    width: 100%;
    text-align: center;
    display: block;
}

.mdl-cell--12-col {
    height: 100%;
    width: 100%;
    text-align: center;
}
</code>```

EDIT: Updated fiddle with both suggestions: https://jsfiddle.net/2kz7tbnu/1/

答: As @Lemnis said, It is only problem for wifi-perm icon. I changed it to wifi and it worked. And about the secondary text, I changed width to 90% and now it's aligned. Thanks all!

Body:
I searched for a long while, but all of them said to give a width, make display block, and set text-align.
I maked this for welcome card.
It also worked for the first card too.
But it doesn't work for second card Icon and text.

First one works, but second doesn't:

        book

All-Inclusive

            This app contains all info about Champions, Summoners, Items, Runes and Masteries.

        wifi_perm

Test Your Ping

            You can check your ping for all servers.

CSS:

.main-card-medium {
    width: 25%;
    display: block;
}

.mdl-cell--4-col {
    margin: auto;
}

.sub-icon {
    font-size: 100px;
    margin: 30px 0px;
    color: #3f51b5;
    width: 100%;
    display: inline-block;
    text-align: center;
}

.sub-content {
    background: #3E4EB8;
}

.subcontent-title {
    width: 100%;
    text-align: center;
    display: block;
}

.mdl-cell--12-col {
    height: 100%;
    width: 100%;
    text-align: center;
}

EDIT: Updated fiddle with both suggestions: https://jsfiddle.net/2kz7tbnu/1/


问:
Why does "undefined method" on null:String in Rails?
As i'm trying to show a specific data from has_many relation on a iteration

Why Rails shows undefined method  for Null:String and how do I fix it?

NoMethodError (undefined method `rated' for "shop_date is not
  null":String)

```<code># controller Cast
def cast
  @products = Product.all
  @rating  = Product.joins(:shops).where(:shops => ('shop_date is not null').rated.average(:b_rating) || 0 )
end

# Model Shop
belongs_to :product

attr_accessible   :b_rating,:product_id

scope :by_participant, -> {  where('shop_date is not null').order('shop_date desc') }

scope :rated, -> {  where('b_rating is not null') }

def self.average_rating
  by_participant.rated.average(:b_rating) || 0
end

# Model Product
Has_many :shops
</code>```

答:
I suppose, simplest way is to user group by query:

```<code># controller
@products = Product.all
products_ids = @products.collect(&:id)
@ratings =
  Shop.where(product_id: products_ids).
    where('shop_date is not null').rated.
    group(:product_id).
    average(:b_rating)

# view
<% @products.each do |product| %>
  Rating: <%= @ratings[product.id] || 0 %>
<% end %>
</code>```

Body:
As i'm trying to show a specific data from has_many relation on a iteration

Why Rails shows undefined method  for Null:String and how do I fix it?

NoMethodError (undefined method `rated' for "shop_date is not
  null":String)

# controller Cast
def cast
  @products = Product.all
  @rating  = Product.joins(:shops).where(:shops => ('shop_date is not null').rated.average(:b_rating) || 0 )
end

# Model Shop
belongs_to :product

attr_accessible   :b_rating,:product_id

scope :by_participant, -> {  where('shop_date is not null').order('shop_date desc') }

scope :rated, -> {  where('b_rating is not null') }

def self.average_rating
  by_participant.rated.average(:b_rating) || 0
end

# Model Product
Has_many :shops

Body:
I suppose, simplest way is to user group by query:

# controller
@products = Product.all
products_ids = @products.collect(&:id)
@ratings =
  Shop.where(product_id: products_ids).
    where('shop_date is not null').rated.
    group(:product_id).
    average(:b_rating)

# view
<% @products.each do |product| %>
  Rating: <%= @ratings[product.id] || 0 %>
<% end %>


问:
Example of code which incorrectly tries to re-seat a reference
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

```<code>CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();
</code>```

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

答:
You can't write portable C++ code to reseat a reference... the compiler tracks where the reference refers to and doesn't allow it to be changed.  It's a kind of alias for whatever it refers to, and in some cases the reference value may be incorporated directly into the code at compile time.  On some implementations where a particular reference happens to be stored in the form of a pointer, and happens to be looked up at run time, you may be able to use a reinterpret cast to overwrite it with a pointer to another object, but the behaviour is totally undefined and unreliable.  For what little it's worth (nothing practically, but perhaps a smidge in assisting understanding of likely implementation), that might look something like:</p>

```<code>struct X
{
    Y& y_;
    X(Y& y) : y_(y) { }
};

...
X x(y1);
*reinterpret_cast<Y**>(&x) = &y2;
</code>```

Body:
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

Body:
You can't write portable C++ code to reseat a reference... the compiler tracks where the reference refers to and doesn't allow it to be changed.  It's a kind of alias for whatever it refers to, and in some cases the reference value may be incorporated directly into the code at compile time.  On some implementations where a particular reference happens to be stored in the form of a pointer, and happens to be looked up at run time, you may be able to use a reinterpret cast to overwrite it with a pointer to another object, but the behaviour is totally undefined and unreliable.  For what little it's worth (nothing practically, but perhaps a smidge in assisting understanding of likely implementation), that might look something like:

struct X
{
    Y& y_;
    X(Y& y) : y_(y) { }
};

...
X x(y1);
*reinterpret_cast<Y**>(&x) = &y2;


问:
background color of parent matching height of child with negative top and bottom margins
Attached is an image of the desired affect I am going for. I am trying to do this with negative margins. I need the child element to expand past the parent element on the top and bottom. The issue is the background color of the parent element is matching the height of the child element. This is a responsive site and I will not be able to use absolute positioning of the child element as the height of the child (and therefore parent element) will be variable. Any help would be greatly appreciated

Following is my code...

body {
  background-color:#DBD9DB;
}

#headerImage {
  margin: 0;
}

#headerImage img {
  display: block;
  margin: 0 auto;
}

#parent {
 background-color: #fff4d7;
}

#child {
 background:none #FFF;
 margin:-46px auto -38px;
 position:relative;
 text-align:center;
 width:80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="headerImage">
    <img src="http://fpoimg.com/300x250?text=Preview" width="300" height="250" />
  </div>
  <div id="parent">
    <div id="child">
      <h1>Title</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti. Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.</p>
    </div>
  </div>
</body></code>```

答:
You can use :after and :before pseudo-elements in the #parent id to change the background-color and then use negative margin in #child.

Check this snippet out:

body {
    background-color:#DBD9DB;
}

#headerImage {
    margin: 0;
}

#headerImage img {
    display: block;
    margin: 0 auto;
}

#parent {
    background-color: #fff4d7;

}
#parent:before, #parent:after{
    content: " ";
    display: block;
    height: 50px;
    background-color: blue;
}

#child {
    background:none #FFF;
    position:relative;
    text-align:center;
    width:80%;
    margin: -50px auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="headerImage">
    <img src="http://fpoimg.com/300x250?text=Preview" width="300" height="250" />
  </div>
  <div id="parent">
    <div id="child">
      <h1>Title</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti. Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.</p>
    </div>
  </div>
</body></code>```

Body:
Attached is an image of the desired affect I am going for. I am trying to do this with negative margins. I need the child element to expand past the parent element on the top and bottom. The issue is the background color of the parent element is matching the height of the child element. This is a responsive site and I will not be able to use absolute positioning of the child element as the height of the child (and therefore parent element) will be variable. Any help would be greatly appreciated

Following is my code...

body {
  background-color:#DBD9DB;
}

#headerImage {
  margin: 0;
}

#headerImage img {
  display: block;
  margin: 0 auto;
}

#parent {
 background-color: #fff4d7;
}

#child {
 background:none #FFF;
 margin:-46px auto -38px;
 position:relative;
 text-align:center;
 width:80%;
}

Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti. Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.

Body:
You can use :after and :before pseudo-elements in the #parent id to change the background-color and then use negative margin in #child.

Check this snippet out:

body {
    background-color:#DBD9DB;
}

#headerImage {
    margin: 0;
}

#headerImage img {
    display: block;
    margin: 0 auto;
}

#parent {
    background-color: #fff4d7;

}
#parent:before, #parent:after{
    content: " ";
    display: block;
    height: 50px;
    background-color: blue;
}

#child {
    background:none #FFF;
    position:relative;
    text-align:center;
    width:80%;
    margin: -50px auto;
}

<body>
  <div id="headerImage">
    <img src="http://fpoimg.com/300x250?text=Preview" width="300" height="250" />
  </div>
  <div id="parent">
    <div id="child">
      <h1>Title</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti. Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.</p>
    </div>
  </div>
</body>


问:
Tinymce adding &nbsp
I am tryng to override the default tinymce in peranhacms like suggested here Configure / override Piranha CMS html editor so as not to add &nbsp's to html
I spend already about one hour trying to fix that problem. There is a lot of resources on that problem but cant get it work.

https://wordpress.org/support/topic/correct-way-to-allow-nbsp-entity-in-tinymce

tinyMCE adding p tags and nbsp automatically

http://blog.room34.com/archives/5075

TinyMCE is adding &nbsp instead of the space when using the word paste

Here is how my tinymce.init looks like.

```<code><script type="text/javascript" src="~/res.ashx/areas/manager/content/js/ext/tiny_mce/tinymce.min.js"></script>
<script type="text/javascript">
    tinymce.init({
        mode: 'specific_textareas',
        editor_selector: "editor",
        apply_source_formatting: false,
        cleanup_on_startup: false,
        trim_span_elements: false,
        cleanup: false,
        convert_urls: false,
        force_br_newlines: true,
        force_p_newlines: false,
        remove_linebreaks: false,
        convert_newlines_to_brs: false,
        forced_root_block: '',
        inline_styles : true,
        entity_encoding: 'raw',
        verify_html: false,
        //forced_root_block: false,
        validate_children: false,
        remove_redundant_brs: false,
        fix_table_elements: false,

        entities: '160,nbsp,38,amp,60,lt,62,gt',

        plugins: [
            "autoresize autolink code hr paste piranhaimage link"
        ],
        width: "100%",
        height: "340",
        autoresize_min_height: 340,
        @if (File.Exists(Server.MapPath("~/areas/manager/content/css/editor.css"))) {
        <text>content_css: "@Url.Content("~/areas/manager/content/css/editor.css")",</text>
        }
        toolbar: "bold italic underline | bullist numlist hr | formatselect removeformat | cut copy paste | link piranhaimage | code",
        paste_auto_cleanup_on_paste: false,
        paste_postprocess: function (pl, o) {
            // remove extra line breaks
            o.node.innerHTML = o.node.innerHTML.replace(/ /ig, " ");
            alert("a1");
        },
        cleanup_callback: 'my_cleanup_callback',
    });
    function my_cleanup_callback(type, value) {
        alert("a2");
        switch (type) {
            case 'get_from_editor':
                // Remove   characters
                value = value.replace(/ /ig, ' ');
                alert("a3");
                break;
            case 'insert_to_editor':
            case 'submit_content':
            case 'get_from_editor_dom':
            case 'insert_to_editor_dom':
            case 'setup_content_dom':
            case 'submit_content_dom':
            default:
                break;
        }
        return value;
    }
</script>
</code>```

here is the example of html I use to paste in to tinyice textarea

```<code><div class="catelog-box">
    <img src="images/dance.png" alt="dine">
    <div class="cat-detail">
    <h2>Dance</h2>
    <p>Dis purus arcu etiam auctor risus aliquam mid turpis eu vel, nunc rhoncus lacus natoque ridiculus...</p>
  </div>
</div>
</code>```

And it is how it is looking in browser source:

I put alerts to check if paste_postprocess and my_cleanup_callback actually firing, but they are not. And I am still have &nbsp in the html.

I was trying to set cleanup: true and paste_auto_cleanup_on_paste: true but it is didnt help to fire paste_postprocess and my_cleanup_callback

How would you fix the &nbsp problem?

答:
I know this is old, but adding this CSS properties to your editor's element can solve the problem. This is not a tinyMCE issue, this is how the editable divs work.

#editor {
    white-space: pre-wrap;
    word-wrap: break-word;
}
```

Cheers

Title: Tinymce adding &nbsp

Body:
I am tryng to override the default tinymce in peranhacms like suggested here Configure / override Piranha CMS html editor so as not to add &nbsp's to html
I spend already about one hour trying to fix that problem. There is a lot of resources on that problem but cant get it work.

https://wordpress.org/support/topic/correct-way-to-allow-nbsp-entity-in-tinymce

tinyMCE adding p tags and nbsp automatically

http://blog.room34.com/archives/5075

TinyMCE is adding &nbsp instead of the space when using the word paste

Here is how my tinymce.init looks like.

here is the example of html I use to paste in to tinyice textarea

Dance

Dis purus arcu etiam auctor risus aliquam mid turpis eu vel, nunc rhoncus lacus natoque ridiculus...

And it is how it is looking in browser source:

I put alerts to check if paste_postprocess and my_cleanup_callback actually firing, but they are not. And I am still have &nbsp in the html.

I was trying to set cleanup: true and paste_auto_cleanup_on_paste: true but it is didnt help to fire paste_postprocess and my_cleanup_callback

How would you fix the &nbsp problem?

Body:
I know this is old, but adding this CSS properties to your editor's element can solve the problem. This is not a tinyMCE issue, this is how the editable divs work.

#editor {
    white-space: pre-wrap;
    word-wrap: break-word;
}

Cheers


问:
Getting XQuery [modify()]: Top-level attribute nodes are not supported error while modifying xml
```<code>DECLARE @mycur CURSOR
DECLARE @id int
DECLARE @ParentNodeName varchar(max)
DECLARE @NodeName varchar(max)
DECLARE @NodeText varchar(max)

SET @mycur = CURSOR
FOR
SELECT * FROM @temp

OPEN @mycur

FETCH NEXT FROM @mycur INTO @id,@ParentNodeName,@NodeName,@NodeText

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @id -- sample statements
PRINT  @ParentNodeName
PRINT  @NodeName
        SET @x.modify
        ('
            insert attribute status {sql:variable("@status")}
            as first
            into (/@ParentNodeName/@NodeName/child::*[position()=sql:variable("@status")])[1]
        ')
FETCH NEXT FROM @mycur INTO  @id,@ParentNodeName,@NodeName,@NodeText
END

DEALLOCATE @mycur
</code>```

Any idea why I am getting this error as query works fine if I manually insert path

答:
The problem is with @ParentNodeName and @NodeName; the @ symbol is used refer to a variable in SQL, but it references an attribute in XML.  The .modify() method is attempting to insert a row at the root with an attribute chain, which is poorly formatted SQL, when it looks like you are trying to build a dynamic XML document.  You'll need to build a dynamic SQL statement which replaces the values of @ParentNodeName and @NodeName with their values from your temp table, something like:

```<code>SET @SQL = '        SET @x.modify
        ('''
            insert attribute status {sql:variable("@status")}
            as first
            into (/@ParentNodeName/@NodeName/child::*[position()=sql:variable("@status")])[1]
        ''')

SET @SQL = REPLACE(@SQL, '@ParentNodeName', @ParentNodeName)
SET @SQL = REPLACE(@SQL, '@NodeName', NodeName)

EXEC (@SQL)
</code>```

untested.

Body:
DECLARE @mycur CURSOR
DECLARE @id int
DECLARE @ParentNodeName varchar(max)
DECLARE @NodeName varchar(max)
DECLARE @NodeText varchar(max)

SET @mycur = CURSOR
FOR
SELECT * FROM @temp

OPEN @mycur

FETCH NEXT FROM @mycur INTO @id,@ParentNodeName,@NodeName,@NodeText

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @id -- sample statements
PRINT  @ParentNodeName
PRINT  @NodeName
        SET @x.modify
        ('
            insert attribute status {sql:variable("@status")}
            as first
            into (/@ParentNodeName/@NodeName/child::*[position()=sql:variable("@status")])[1]
        ')
FETCH NEXT FROM @mycur INTO  @id,@ParentNodeName,@NodeName,@NodeText
END

DEALLOCATE @mycur

Any idea why I am getting this error as query works fine if I manually insert path

Body:
The problem is with @ParentNodeName and @NodeName; the @ symbol is used refer to a variable in SQL, but it references an attribute in XML.  The .modify() method is attempting to insert a row at the root with an attribute chain, which is poorly formatted SQL, when it looks like you are trying to build a dynamic XML document.  You'll need to build a dynamic SQL statement which replaces the values of @ParentNodeName and @NodeName with their values from your temp table, something like:

SET @SQL = '        SET @x.modify
        ('''
            insert attribute status {sql:variable("@status")}
            as first
            into (/@ParentNodeName/@NodeName/child::*[position()=sql:variable("@status")])[1]
        ''')

SET @SQL = REPLACE(@SQL, '@ParentNodeName', @ParentNodeName)
SET @SQL = REPLACE(@SQL, '@NodeName', NodeName)

EXEC (@SQL)

untested.


问:
Translation to Predicate Logic with Lexicon
How would one translate the following statement into predicate logic:

"Even though the examiner hopes all students will satisfy the requirements for grade E or better, somebody will receive a lower grade and be disappointed."

答:
The first step is to define an alphabet. Take the following first-order alphabet with the desired interpretation:

Unary predicates:

S(x): "x is a student"

E(x): "x is an examiner"

G(x): "x is a grade"

D(x): "x is disappointed"

Binary predicates:

R(x, y): "x is a requirement for y"

B(x, y): "x is y or better"

O(x, y): "x receives y"

Ternary predicates:

H(x, y, z): "x hopes that y fulfills z"

e: Constant ("the grade E")

x, y, z, w: Variables

Let's break the original statement in two parts:

S1: "The examiner hopes all students will satisfy the requirements for grade E or better"

S2: "Somebody will receive a lower grade and be disappointed"

And use the defined alphabet to write it in first-order:

S1: ∃x(E(x) ∧ ∀y(S(y) ⇒ ∃z∃w(R(z, e) ∧ B(w, z) ∧ H(x, y, w))))

S2: ∃x∃y(S(x) ∧ G(y) ∧ O(x, y) ∧ ¬B(y, e) ∧ D(x))

Finally we compute the original statement, that is:

S1 ∧ S2

Keep in mind that this is just one of the interpretations that will lead to a correct (satisfying) answer.

I hope it helps


问:
Input string was not in a correct format (double)
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

```<code>double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}
</code>```

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.

答:
The main changes I would make to your code are to

remove the return statement since that will exit our method prematurely

use a List<double> to store your doubles (you don't have to declare a size ahead of time, which is nice because we don't know for sure how many items in the string will successfully convert to a double)

to use the val variable when adding it to the List, since double.TryParse has assigned the value to this variable already.

I also added a check to ensure that the variable numRows is not larger than the string array, because that would cause an exception in our loop:

```<code>// Mock values read from file
var input = new StringBuilder();
input.Append("0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,");
input.Append("1.1389,0.50494,0.24976,0.6598,0.1666,0.24976,497.42,0.73378,");
input.Append("2.6349,0.24976,0.14942,43.37,1.2479,0.21402,0.11998,0.47706,");
input.Append("0.50494,0.60411,1.4582,1.7615,5.9443,0.11788,593.27,0.50591,");
input.Append("0.12804,0.66295,0.14942,94.14,3.8772,0.56393,0.21402,1.741,");
input.Append("1.5225,49.394,0.1853,0.11085,2.042,0.051402,0.12804,114.42,");
input.Append("71.05,1.0097,348690,0.12196,0.39718,0.87804,0.37854,0.25792,");
input.Append("2.2437,2.248,0.001924,8.416,5.1372,82.658,4.4158,7.4277");

string[] values_in_string = inputString.ToString().Split(',');

// Declare values_in_double as a List so we don't have to worry about sizing
List<double> values_in_double = new List<double>();

// We will get errors if numCols is larger than our string array, so to be safe,
// set a variable that is the smallest of either numCols or our string array length
var numIterations = Math.Min(numCols, values_in_string.Length);

for (int x = 0; x < numIterations; x++)
{
    double val;

    // If TryParse succeeds, 'val' will contain the double value, so add it to our List
    if (double.TryParse(values_in_string[x], NumberStyles.Any,
        System.Globalization.CultureInfo.InvariantCulture, out val))
    {
        values_in_double.Add(val);
    }
}
</code>```

There is also a much shorter way to write this code. The line basically says: For each item in values_in_string, Where double.TryParse returns true, Select val (the item as a value) And convert all the val items into a List:

```<code>string[] values_in_string = inputString.ToString().Split(',');
double val = 0;

List<double> values_in_double = values_in_string
    .Where(value => double.TryParse(value, NumberStyles.Any,
        System.Globalization.CultureInfo.InvariantCulture, out val))
    .Select(v => val)
    .ToList();
</code>```

Body:
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.

Body:
The main changes I would make to your code are to

remove the return statement since that will exit our method prematurely

use a List<double> to store your doubles (you don't have to declare a size ahead of time, which is nice because we don't know for sure how many items in the string will successfully convert to a double)

to use the val variable when adding it to the List, since double.TryParse has assigned the value to this variable already.

I also added a check to ensure that the variable numRows is not larger than the string array, because that would cause an exception in our loop:

// Mock values read from file
var input = new StringBuilder();
input.Append("0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,");
input.Append("1.1389,0.50494,0.24976,0.6598,0.1666,0.24976,497.42,0.73378,");
input.Append("2.6349,0.24976,0.14942,43.37,1.2479,0.21402,0.11998,0.47706,");
input.Append("0.50494,0.60411,1.4582,1.7615,5.9443,0.11788,593.27,0.50591,");
input.Append("0.12804,0.66295,0.14942,94.14,3.8772,0.56393,0.21402,1.741,");
input.Append("1.5225,49.394,0.1853,0.11085,2.042,0.051402,0.12804,114.42,");
input.Append("71.05,1.0097,348690,0.12196,0.39718,0.87804,0.37854,0.25792,");
input.Append("2.2437,2.248,0.001924,8.416,5.1372,82.658,4.4158,7.4277");

string[] values_in_string = inputString.ToString().Split(',');

// Declare values_in_double as a List so we don't have to worry about sizing
List<double> values_in_double = new List<double>();

// We will get errors if numCols is larger than our string array, so to be safe,
// set a variable that is the smallest of either numCols or our string array length
var numIterations = Math.Min(numCols, values_in_string.Length);

for (int x = 0; x < numIterations; x++)
{
    double val;

    // If TryParse succeeds, 'val' will contain the double value, so add it to our List
    if (double.TryParse(values_in_string[x], NumberStyles.Any,
        System.Globalization.CultureInfo.InvariantCulture, out val))
    {
        values_in_double.Add(val);
    }
}

There is also a much shorter way to write this code. The line basically says: For each item in values_in_string, Where double.TryParse returns true, Select val (the item as a value) And convert all the val items into a List:

string[] values_in_string = inputString.ToString().Split(',');
double val = 0;

List<double> values_in_double = values_in_string
    .Where(value => double.TryParse(value, NumberStyles.Any,
        System.Globalization.CultureInfo.InvariantCulture, out val))
    .Select(v => val)
    .ToList();