问:
Leaky bucket problem help?
I'm trying to review for my final and I'm going over example problems given to me by my professor. Can anyone explain to me the concept of how leaky bucket works. Also Here's a review problem my professor gave to me about leaky buckets.

A leaky bucket is at the host network interface. The data rate in the network is 2 Mbyte/s and the data rate from the application to the bucket is 2m5 Mbyte/s

A.) Suppose the host has 250 Mbytes to send onto the network and it sends the data in one burst. What should the minimum capacity of the bucket (in byte) in order that no data is lost?

B.) Suppose the capacity of the bucket is 100M bytes. What is the longest burst time from the host in order that no data is lost?

答:
Interesting problem - here's my attempt at solving A (no gurantees it's right though!)

So rate in = 2.5, rate out = 2.0, where the rate is in Mbyte/s.

So in 1 second, the bucket will contain 2.5 - 2.0 = 0.5 Mbyte.

1) If the host sends 250 Mbytes. This will take 100 seconds to transfer into the bucket at 2.5 Mbytes/s.
2) If the bucket drains at 2.0 Mbytes/s then it will have drained 100 * 2 = 200 Mbytes.

So I think you need a bucket which is 50 Mbytes capacity.

Title: Leaky bucket problem help?


来源: stackexchange

问:
Add new label and numericupdown while program running
I have a textbox and a button in my windows form app. When user press button, text in the textbox will be added to groupbox as a label and one numericupdown will be added. I want to put them a text to each other: Label - NumUpDown.

The problem is when button pressed, label and numupdown added to the same location so that I can't see one of them. In Python, there is a grid option which allows me to place the objects with column and row.

Also, I want to make it infinitely - at least more than one - but after first adding, I can't add a new one. How can I fix those problems?

答:
```<code>tableLayoutPanel1.Controls.Add(new Label() { Text = (textbox1.Text).ToString()}, 0, 0);
tableLayoutPanel1.Controls.Add(new NumericUpDown() { Width = 50, Value = 1 }, 1, 0);
</code>```

ContentLicense: CC BY-SA 3.0


问:
what are classes, enumerations, Interfaces, Attributes?
I am developing a unity game. I just still don't understand details about classes, enumerations, Interfaces and Attributes? How do each of these work? What is the difference between my classes (that I have to create) and unity scripting api classes (that already exist)? </p>

答:
Classes are a blueprint that define behaviour. If you want your game to have any kind of behaviour it will be defined in a class. You would for example create a "Player.cs" class which would define how the player behaves.

I could go through each one but the question is too broad and it would be more beneficial if you looked for some material about the basics of c#, object oriented programming and Unity.

Unity has video tutorials on the fundamentals of these topics here => Link.

I hope you find them useful.


问:
WPF Menu Item check mark is blacked in Windows 10
I created a small menu bar with some checked menu items. It is blacked out in Windows 10 but displayed fine in Windows 7

XAML

```<code><Window x:Class="CheckMenuTickinWin10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CheckMenuTickinWin10"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ToolBar>
            <Menu>
                <MenuItem Header="menu">
                    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True"/>
                    <MenuItem Header="Sub" IsCheckable="True" IsChecked="False"/>
                    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True"/>
                </MenuItem>
            </Menu>
        </ToolBar>
    </StackPanel>
</Window>
</code>```

What should I do in Windows 10 to make the check mark visible?

答:
This background is defined in the default ControlTemplate of the menu item. A template defines the look of a control, if you don't define a template for the control, it will pick up the default template.

The good news is that you are free to edit the ControlTemplate to customize the control as whatever you like. The not so good news is that you have to be comfortable with a bunch of XAML code (hundreds of lines for a single template).

First find the "default" ControlTemplate of the MenuItem in Visual Studio.

In the VS designer, right click the SubMenuItem, and choose "Edit Template" -> "Edit a Copy" from the dropdown menu. This will automatically copy the default template of the SubMenuItem to a style name "MenuItemStyle1" as defined in the window's Resource dictionary.

Remove the black background from the template.

Expand MenuItemStyle1, find the following line that defines the black border.

```<code><Border x:Name="GlyphPanel" BorderBrush="#80DADADA" BorderThickness="1" Background="#FF212121" Height="20" Margin="0,1" Visibility="Hidden" Width="20">
</code>```

Change the Background color from "#FF212121" to "#FFEEF5FD", and save the change. (#FFEEF5FD is the hightlight color of the border, it is also the color of the light background of the menu, you can find this color in the default template.)

Then apply this new template to all 3 menu items.

```<code><MenuItem Header="menu">
    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True" Style="{DynamicResource MenuItemStyle1}" />
    <MenuItem Header="Sub" IsCheckable="True" IsChecked="False" Style="{DynamicResource MenuItemStyle1}" />
    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True" Style="{DynamicResource MenuItemStyle1}" />
</MenuItem>
</code>```

Body:
I created a small menu bar with some checked menu items. It is blacked out in Windows 10 but displayed fine in Windows 7

XAML

<Window x:Class="CheckMenuTickinWin10.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CheckMenuTickinWin10"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ToolBar>
            <Menu>
                <MenuItem Header="menu">
                    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True"/>
                    <MenuItem Header="Sub" IsCheckable="True" IsChecked="False"/>
                    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True"/>
                </MenuItem>
            </Menu>
        </ToolBar>
    </StackPanel>
</Window>

What should I do in Windows 10 to make the check mark visible?

Body:
This background is defined in the default ControlTemplate of the menu item. A template defines the look of a control, if you don't define a template for the control, it will pick up the default template.

The good news is that you are free to edit the ControlTemplate to customize the control as whatever you like. The not so good news is that you have to be comfortable with a bunch of XAML code (hundreds of lines for a single template).

First find the "default" ControlTemplate of the MenuItem in Visual Studio.

In the VS designer, right click the SubMenuItem, and choose "Edit Template" -> "Edit a Copy" from the dropdown menu. This will automatically copy the default template of the SubMenuItem to a style name "MenuItemStyle1" as defined in the window's Resource dictionary.

Remove the black background from the template.

Expand MenuItemStyle1, find the following line that defines the black border.

<Border x:Name="GlyphPanel" BorderBrush="#80DADADA" BorderThickness="1" Background="#FF212121" Height="20" Margin="0,1" Visibility="Hidden" Width="20">

Change the Background color from "#FF212121" to "#FFEEF5FD", and save the change. (#FFEEF5FD is the hightlight color of the border, it is also the color of the light background of the menu, you can find this color in the default template.)

Then apply this new template to all 3 menu items.

<MenuItem Header="menu">
    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True" Style="{DynamicResource MenuItemStyle1}" />
    <MenuItem Header="Sub" IsCheckable="True" IsChecked="False" Style="{DynamicResource MenuItemStyle1}" />
    <MenuItem Header="Sub" IsCheckable="True" IsChecked="True" Style="{DynamicResource MenuItemStyle1}" />
</MenuItem>


问:
Locking a file when using multiprocessing and multithreading - Python
I have a main.py file. This file uses multiprocessing to execute another file called function.py. The second one use threading to apply a function, f, to every component of a numpy array. function.py reads (only once in all the process) a file, file.txt, to read some data for f and then to clear it (write a empty file). Do I need to lock the file, file.txt, in function.py to avoid problems of having N processes, created from main.py executing function.py and reading and writing in file.txt? If so, how can it be done?

Finally I get it with a semaphore.

答:
Yes, in some way it has to be locked.
Having several processes reading a file is no problem as long as they are only reading it. As soon as something writes to the file you have to be sure that the reads and writes occur in the desired order.

Locking could be done by using a lockfile that is atomically created. After a process successfully creates the lockfile, it gains access to the text file. After the process is done with the text file, it deletes the lockfile. This assures that only one process can access the text file at a given time.


问:
Pandas: Manipulating another column's values based on other column values
I have another basic question. So I have a dataframe like so:
cols = a,b,c,d,e which contains integers.

I want column e's value to equal 1 if columns b and c or columns a, b and c = 1.
Although d's column does not matter in this computation, it matters somewhere else so I cannot drop it.

How would I do that on pandas?

Body:
Use .loc:

df.loc[df['a']==df['b']==df['c']==1,'e']=1


问:
Storing Url into Firebase -Xamarin
I am able to store my images into my database. In my image table, i want the url itself but when i save the image i get this kind of url(i can't tell if it is a url or not) which looks like "md59ff87d3098d3e76b10bcffd04c4d249f.Image@429ed2f8" but i want something like firebase.com/pet.jpg so i can call it back into my imageview. The problem seems to be in my OnSuccess(). How do i get this done please?

```<code>protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {

                uri = data.Data;

                try
                {

                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    imageViewDrop.SetImageBitmap(bitmap);

                }
                catch (FileNotFoundException e)
                {

                    e.StackTrace.ToString();
                }

                catch (IOException e)
                {
                    e.StackTrace.ToString();
                }

                if (uri != null)
                {
                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();

                    StorageReference image = storageRef.Child(FB_STORAGE_PATH +System.DateTime.Today + "." + GetImageExt(uri));

                    image.PutFile(uri).AddOnSuccessListener(this).AddOnFailureListener(this);

                    image.PutFile(uri).AddOnProgressListener(this);

               }

            }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

            ImageUpload uploads = new ImageUpload(uri.ToString());

            string uploadId = mDatabaseImage.Push().Key;
            mDatabaseImage.Child(user.Uid).Child(phId).Child(uploadId).SetValue(uploads.ToString());

        }
</code>```

update

```<code>  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {
                uri = data.Data;

                for (int i = 0; i < 5; i++){

                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();
                    StorageReference oneRef = storageRef.Child("one " + i + "png.");
                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    MemoryStream stream = new MemoryStream();
                    bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                    byte[] myData = stream.ToArray();

                    uploadTask = oneRef.PutBytes(myData);
                    uploadTask.AddOnSuccessListener(this);
                    uploadTask.AddOnFailureListener(this);
                }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            var url = snapshot.Storage.Path;
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }

        public void OnFailure(Java.Lang.Exception e)
        {
            pd.Dismiss();

            Toast.MakeText(this, e.Message, ToastLength.Short).Show();

        }
</code>```

答:
but i want something like firebase.com/pet.jpg so i can call it back into my imageview.

From your code I think you're uploading your images to Firebase Storage and then you can save the path of this image to your Firebase Database for example like this:

```<code>public class MyActivity : Activity, IOnSuccessListener, IOnFailureListener, IValueEventListener
{
    private DatabaseReference dbRef;
    private StorageReference imagesRef;
    private int count;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.layout2);

        FirebaseAuth mAuth = FirebaseAuth.Instance;
        FirebaseUser user = mAuth.CurrentUser;
        if (user == null)
        {
            var result = mAuth.SignInAnonymously();
        }

        FirebaseDatabase database = FirebaseDatabase.Instance;
        dbRef = database.GetReference("mygallery");

        FirebaseStorage storage = FirebaseStorage.Instance;
        //create child reference
        StorageReference storageRef = storage.Reference;
        imagesRef = storageRef.Child("images");

        Button btn = FindViewById<Button>(Resource.Id.createdb);
        btn.Click += Btn_Click;
    }

    private void Btn_Click(object sender, EventArgs e)
    {
        //upload to firebase storage
        for (int i = 0; i < 5; i++)
        {
            StorageReference oneRef = imagesRef.Child("one" + i + ".png");
            Bitmap bitmap = BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.one);
            MemoryStream stream = new MemoryStream();
            bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
            byte[] data = stream.ToArray();

            UploadTask uploadtask = oneRef.PutBytes(data);
            uploadtask.AddOnSuccessListener(this);
            uploadtask.AddOnFailureListener(this);
        }
    }

    public void OnFailure(Java.Lang.Exception e)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "Failed:" + e.ToString());
        Toast.MakeText(Application.Context, "Failed", ToastLength.Short);
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "success!");
        Toast.MakeText(this, "Success", ToastLength.Short);

        //retrieve url and name of uploaded image and insert to database
        var snapshot = result as SnapshotBase;
        var name = snapshot.Storage.Name;
        var uri = snapshot.Storage.Path;
        dbRef.Child(count.ToString()).Child("name").SetValue(name);
        dbRef.Child(count.ToString()).Child("imageurl").SetValue(uri);
        count++;
    }

    public void OnCancelled(DatabaseError error)
    {
        Log.WriteLine(LogPriority.Debug, "database", "Cancelled:" + error.ToString());
        Toast.MakeText(Application.Context, "Failed", ToastLength.Short);
    }

    public void OnDataChange(DataSnapshot snapshot)
    {
        Toast.MakeText(Application.Context, "Success", ToastLength.Short);
    }
}
</code>```

Here is the screen shot of my firebase storage and database:

Title: Storing Url into Firebase -Xamarin

Body:
I am able to store my images into my database. In my image table, i want the url itself but when i save the image i get this kind of url(i can't tell if it is a url or not) which looks like "md59ff87d3098d3e76b10bcffd04c4d249f.Image@429ed2f8" but i want something like firebase.com/pet.jpg so i can call it back into my imageview. The problem seems to be in my OnSuccess(). How do i get this done please?

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {

                uri = data.Data;

                try
                {

                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    imageViewDrop.SetImageBitmap(bitmap);

                }
                catch (FileNotFoundException e)
                {

                    e.StackTrace.ToString();
                }

                catch (IOException e)
                {
                    e.StackTrace.ToString();
                }

                if (uri != null)
                {
                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();

                    StorageReference image = storageRef.Child(FB_STORAGE_PATH +System.DateTime.Today + "." + GetImageExt(uri));

                    image.PutFile(uri).AddOnSuccessListener(this).AddOnFailureListener(this);

                    image.PutFile(uri).AddOnProgressListener(this);

               }

            }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

            ImageUpload uploads = new ImageUpload(uri.ToString());

            string uploadId = mDatabaseImage.Push().Key;
            mDatabaseImage.Child(user.Uid).Child(phId).Child(uploadId).SetValue(uploads.ToString());

        }

update

  protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE_REQUEST && resultCode == Result.Ok && data != null && data.Data != null)
            {
                uri = data.Data;

                for (int i = 0; i < 5; i++){

                    pd = new ProgressDialog(this);
                    pd.SetTitle("Uploading Profile Picture");
                    pd.Show();
                    StorageReference oneRef = storageRef.Child("one " + i + "png.");
                    Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
                    MemoryStream stream = new MemoryStream();
                    bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
                    byte[] myData = stream.ToArray();

                    uploadTask = oneRef.PutBytes(myData);
                    uploadTask.AddOnSuccessListener(this);
                    uploadTask.AddOnFailureListener(this);
                }
        }

        public string GetImageExt(Android.Net.Uri uri)
        {

            ContentResolver contentresolver = ContentResolver;
            MimeTypeMap mime = MimeTypeMap.Singleton;
            return mime.GetExtensionFromMimeType(contentresolver.GetType(uri));

        }

        public void OnSuccess(Java.Lang.Object result)
        {
             pd.Dismiss();
            string uploadId = mDatabaseImage.Push().Key;
            var snapshot = result as SnapshotBase;
            var url = snapshot.Storage.Path;
            mDatabaseImage.Child(count.ToString()).Child(user.Uid).Child(phId).Child(uploadId).SetValue(new PeaceHeroImage(url).ToMap());

            Toast.MakeText(this, "Image Uploaded Successfully", ToastLength.Short).Show();

        }

        public void OnFailure(Java.Lang.Exception e)
        {
            pd.Dismiss();

            Toast.MakeText(this, e.Message, ToastLength.Short).Show();

        }

Body:
but i want something like firebase.com/pet.jpg so i can call it back into my imageview.

From your code I think you're uploading your images to Firebase Storage and then you can save the path of this image to your Firebase Database for example like this:

public class MyActivity : Activity, IOnSuccessListener, IOnFailureListener, IValueEventListener
{
    private DatabaseReference dbRef;
    private StorageReference imagesRef;
    private int count;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        // Create your application here
        SetContentView(Resource.Layout.layout2);

        FirebaseAuth mAuth = FirebaseAuth.Instance;
        FirebaseUser user = mAuth.CurrentUser;
        if (user == null)
        {
            var result = mAuth.SignInAnonymously();
        }

        FirebaseDatabase database = FirebaseDatabase.Instance;
        dbRef = database.GetReference("mygallery");

        FirebaseStorage storage = FirebaseStorage.Instance;
        //create child reference
        StorageReference storageRef = storage.Reference;
        imagesRef = storageRef.Child("images");

        Button btn = FindViewById<Button>(Resource.Id.createdb);
        btn.Click += Btn_Click;
    }

    private void Btn_Click(object sender, EventArgs e)
    {
        //upload to firebase storage
        for (int i = 0; i < 5; i++)
        {
            StorageReference oneRef = imagesRef.Child("one" + i + ".png");
            Bitmap bitmap = BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.one);
            MemoryStream stream = new MemoryStream();
            bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
            byte[] data = stream.ToArray();

            UploadTask uploadtask = oneRef.PutBytes(data);
            uploadtask.AddOnSuccessListener(this);
            uploadtask.AddOnFailureListener(this);
        }
    }

    public void OnFailure(Java.Lang.Exception e)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "Failed:" + e.ToString());
        Toast.MakeText(Application.Context, "Failed", ToastLength.Short);
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        Log.WriteLine(LogPriority.Debug, "storage", "success!");
        Toast.MakeText(this, "Success", ToastLength.Short);

        //retrieve url and name of uploaded image and insert to database
        var snapshot = result as SnapshotBase;
        var name = snapshot.Storage.Name;
        var uri = snapshot.Storage.Path;
        dbRef.Child(count.ToString()).Child("name").SetValue(name);
        dbRef.Child(count.ToString()).Child("imageurl").SetValue(uri);
        count++;
    }

    public void OnCancelled(DatabaseError error)
    {
        Log.WriteLine(LogPriority.Debug, "database", "Cancelled:" + error.ToString());
        Toast.MakeText(Application.Context, "Failed", ToastLength.Short);
    }

    public void OnDataChange(DataSnapshot snapshot)
    {
        Toast.MakeText(Application.Context, "Success", ToastLength.Short);
    }
}

Here is the screen shot of my firebase storage and database:


问:
How to Exit windows phone 7 app?

Possible Duplicates:

  Windows Phone 7 close application

  Close a WP7 application programatically?

  Is there a way to programmatically quit my App? (Windows Phone 7)

Hi All,
       Is there any way to exit application in windows phone 7. My problem with EULA.xaml and MainPage.xaml is solved but have to exit my app on MainPage.xaml in either of the cases.
Thanks in advance.

答:
There is no standard API to do this in WP7-Silverlight. The trick is that you can throw an un-handled exception and that can cause the app to break and go to start menu of WindowsPhone.

```<code>public class ExitException :Exception {}
</code>```

and throw this where ever you want to quit.

```<code>throw new ExitException();
</code>```

Title: How to Exit windows phone 7 app?

Body:
There is no standard API to do this in WP7-Silverlight. The trick is that you can throw an un-handled exception and that can cause the app to break and go to start menu of WindowsPhone.

public class ExitException :Exception {}

and throw this where ever you want to quit.

throw new ExitException();

ContentLicense: CC BY-SA 2.5


问:
Qt stylesheet and QString::arg()
To keep a Stylesheet dynamic regarding DPI settings, I want to set certain parts of it from code.

This works:

```<code>my_label->setStyleSheet( QString( "font-size: 30px;" ) );
</code>```

Yet, this doesn't:

```<code>my_label->setStyleSheet( QString( "font-size: %1px;" ).arg( 30 ) );
</code>```

Can anyone enlighten me, why this is? Running Qt 5.7.

答:
Conver the number to a string, QString::number:

```<code>my_label->setStyleSheet(QString("QLabel{font-size: %1 px;}").arg(QString::number(30));
</code>```

Or try it by using QFont, use this generic function for this purpose:

```<code>void updateFontSize(QLabel* label, int fontSize) {
    QFont font = label->font();
    if (font.pointSize() != fontSize) {
        font.setPointSize(fontSize);
        label->setFont(font);
    }
}
</code>```

Title: Qt stylesheet and QString::arg()

Body:
To keep a Stylesheet dynamic regarding DPI settings, I want to set certain parts of it from code.

This works:

my_label->setStyleSheet( QString( "font-size: 30px;" ) );

Yet, this doesn't:

my_label->setStyleSheet( QString( "font-size: %1px;" ).arg( 30 ) );

Can anyone enlighten me, why this is? Running Qt 5.7.

Body:
Conver the number to a string, QString::number:

my_label->setStyleSheet(QString("QLabel{font-size: %1 px;}").arg(QString::number(30));

Or try it by using QFont, use this generic function for this purpose:

void updateFontSize(QLabel* label, int fontSize) {
    QFont font = label->font();
    if (font.pointSize() != fontSize) {
        font.setPointSize(fontSize);
        label->setFont(font);
    }
}


问:
Why won't the variable echo?
I have a success page that displays some variables after a succesful transaction with Paypal (IPN).

It's all working great but I just can't figure out why the $email variable does not echo out. Is there something wrong with the query? I have triple checked all the column names.

I get this output:

```<code>OK
price-1.89

Notice: Undefined variable: payer_email in success.php on line 34
Email-
</code>```

Success.php

```<code> <?php
        include 'dbConfig.php';

        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        //Get payment information from PayPal
        $item_number= mysqli_real_escape_string($db, $_POST['item_number']);
        $txn_id= mysqli_real_escape_string($db, $_POST['txn_id']);
        $payment_gross= mysqli_real_escape_string($db, $_POST['payment_gross']);

        //Get product price from database
        $productResult = $db->query("SELECT price FROM products WHERE id = '".$item_number."'");
        $productRow = $productResult->fetch_assoc();
        $productPrice = $productRow['price'];

        if(!empty($txn_id) && $payment_gross == $productPrice){

          //Check if payment data exists with the same TXN ID.
            $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");

           if($prevPaymentResult->num_rows > 0){

            //Get Email
            $result = $db->query("SELECT payer_email FROM payments WHERE txn_id = '".$txn_id."'");
        $row = $result->fetch_assoc();
        $email=$row['payer_email'];
           }
                echo "OK</br>";
                echo "Price-".$payment_gross."</br>";
                echo "Email-".$email."</br>";

            }else{

              echo '<h1>Error</h1>';
        }
        ?>
</code>```

答:
On your code :

```<code>if (!empty($txn_id) && $payment_gross == $productPrice)
    {

    // Check if payment data exists with the same TXN ID.

    $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '" . $txn_id . "'");
    if ($prevPaymentResult->num_rows > 0)
        {

        // Get Email

        $result = $db->query("SELECT payer_email FROM payments WHERE txn_id = '" . $txn_id . "'");
        $row = $result->fetch_assoc();
        $email = $row['payer_email'];
        }

    echo "OK</br>";
    echo "Price-" . $payment_gross . "</br>";
    echo "Email-" . $email . "</br>";
    }
  else
    {
    echo '<h1>Error</h1>';
    }
</code>```

if ($prevPaymentResult->num_rows > 0) The only thing that could imply this behaviour is that this condition is not met, hence why the line :

$email = $row['payer_email']; is never processed.

Title: Why won't the variable echo?

Body:
I have a success page that displays some variables after a succesful transaction with Paypal (IPN).

It's all working great but I just can't figure out why the $email variable does not echo out. Is there something wrong with the query? I have triple checked all the column names.

I get this output:

OK
price-1.89

Notice: Undefined variable: payer_email in success.php on line 34
Email-

Success.php

 <?php
        include 'dbConfig.php';

        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        //Get payment information from PayPal
        $item_number= mysqli_real_escape_string($db, $_POST['item_number']);
        $txn_id= mysqli_real_escape_string($db, $_POST['txn_id']);
        $payment_gross= mysqli_real_escape_string($db, $_POST['payment_gross']);

        //Get product price from database
        $productResult = $db->query("SELECT price FROM products WHERE id = '".$item_number."'");
        $productRow = $productResult->fetch_assoc();
        $productPrice = $productRow['price'];

        if(!empty($txn_id) && $payment_gross == $productPrice){

          //Check if payment data exists with the same TXN ID.
            $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");

           if($prevPaymentResult->num_rows > 0){

            //Get Email
            $result = $db->query("SELECT payer_email FROM payments WHERE txn_id = '".$txn_id."'");
        $row = $result->fetch_assoc();
        $email=$row['payer_email'];
           }
                echo "OK
";
                echo "Price-".$payment_gross."
";
                echo "Email-".$email."
";

            }else{

              echo '
Error
';
        }
        ?>

Body:
On your code :

if (!empty($txn_id) && $payment_gross == $productPrice)
    {

    // Check if payment data exists with the same TXN ID.

    $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '" . $txn_id . "'");
    if ($prevPaymentResult->num_rows > 0)
        {

        // Get Email

        $result = $db->query("SELECT payer_email FROM payments WHERE txn_id = '" . $txn_id . "'");
        $row = $result->fetch_assoc();
        $email = $row['payer_email'];
        }

    echo "OK</br>";
    echo "Price-" . $payment_gross . "</br>";
    echo "Email-" . $email . "</br>";
    }
  else
    {
    echo '<h1>Error</h1>';
    }

if ($prevPaymentResult->num_rows > 0) The only thing that could imply this behaviour is that this condition is not met, hence why the line :

$email = $row['payer_email']; is never processed.


问:
Creating Directories using NPM Module fs-extra
I need some help.

I need to be able to create a directory structure which looks like the following:

```<code>parent
  child1
    folder1
    folder2
  child2
    folder1
    folder2
</code>```

I'm currently using fs-extra (npm module). My issue is that the folder structure needs to be read from a .JSON file. When running say buildDir.js, it should read the .JSON file and create the above structure under a dist (distribution) folder. My current .JSON files looks like:

```<code>{
    "directories": [
        {
            "type": "folder",
            "name": "parent",
            "path": "parent/child1"
        },
        ...
    ]
}
</code>```

p.s I'm quite new to Javascript so my code my be a little sparse in places.
Any help would be great.

答:
```<code>var parsedJson = JSON.parse(fs.readFileSync("directories.json", "UTF-8"));
parsedJson.directories.forEach(function(value){
    if(value.type == "folder"){
        fs.mkdirSync(value.path);
    }
});
console.log("It worked!");
</code>```

Body:
I need some help.

I need to be able to create a directory structure which looks like the following:

parent
  child1
    folder1
    folder2
  child2
    folder1
    folder2

I'm currently using fs-extra (npm module). My issue is that the folder structure needs to be read from a .JSON file. When running say buildDir.js, it should read the .JSON file and create the above structure under a dist (distribution) folder. My current .JSON files looks like:

{
    "directories": [
        {
            "type": "folder",
            "name": "parent",
            "path": "parent/child1"
        },
        ...
    ]
}

p.s I'm quite new to Javascript so my code my be a little sparse in places.
Any help would be great.


问:
JPA: ORDER BY before GROUP BY in JPARepository
This is the mysql query that I've:

```<code>SELECT * FROM (SELECT vev.* FROM vital_entry ve
INNER JOIN vital_entry_values vev ON ve.vital_entry_id=vev.vital_entry_id
WHERE ve.account_id=146
ORDER BY date_entered DESC) t1
GROUP BY vital_id ;
</code>```

How do I do this in JPA?? I tried:

```<code>@Query("SELECT t1 FROM (SELECT ve FROM VitalEntry ve " +
            "INNER JOIN ve.vitalEntryValues vev " +
            "WHERE ve.accountId=:accountId " +
            "ORDER BY ve.dateEntered DESC) t1")
List<VitalEntry> getRecentVitalValues(@Param("accountId") int accountId);
</code>```

But IntelIj shows error expected identifer, got '('

答:
Use native query instead:</p>

```<code>@Query("SELECT * FROM (SELECT ve.* FROM vital_entry ve INNER JOIN vital_entry_values vev ON ve.vital_entry_id=vev.vital_entry_id WHERE ve.account_id=:accountId ORDER BY date_entered DESC) t1 GROUP BY vital_id", nativeQuery=true)
List<VitalEntry> getRecentVitalValues(@Param("accountId") int accountId);
</code>```

Body:
This is the mysql query that I've:

SELECT * FROM (SELECT vev.* FROM vital_entry ve
INNER JOIN vital_entry_values vev ON ve.vital_entry_id=vev.vital_entry_id
WHERE ve.account_id=146
ORDER BY date_entered DESC) t1
GROUP BY vital_id ;

How do I do this in JPA?? I tried:

@Query("SELECT t1 FROM (SELECT ve FROM VitalEntry ve " +
            "INNER JOIN ve.vitalEntryValues vev " +
            "WHERE ve.accountId=:accountId " +
            "ORDER BY ve.dateEntered DESC) t1")
List<VitalEntry> getRecentVitalValues(@Param("accountId") int accountId);

But IntelIj shows error expected identifer, got '('

Body:
Use native query instead:

@Query("SELECT * FROM (SELECT ve.* FROM vital_entry ve INNER JOIN vital_entry_values vev ON ve.vital_entry_id=vev.vital_entry_id WHERE ve.account_id=:accountId ORDER BY date_entered DESC) t1 GROUP BY vital_id", nativeQuery=true)
List<VitalEntry> getRecentVitalValues(@Param("accountId") int accountId);


问:
C# Trying to find the RobloxPlayerBeta
Here is my code: I am trying to find the roblox PlayerBeta but its not working
I am not the best in coding but I found out how to find it but cant implent it right into the code

( EDIT ) The program works if I use the PID but that changes everytime I open up a new RobloxPlayerBeta ! so I cannot use that

```<code>    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Memory;
    using System.Diagnostics;

    namespace ForceField
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            Mem MemLib = new Mem();

            private void button1_Click(object sender, EventArgs e)
            {

                if (System.Diagnostics.Process.GetProcesses().Any((p) =>                                                                                p.ProcessName.Contains("RobloxPlayerBeta")))
        {
            int robloxPid = System.Diagnostics.Process.GetProcessesByName("RobloxPlayerBeta").FirstOrDefault().Id;
        }
        Console.WriteLine(robloxPid);
        MemLib.writeMemory("0x184C3A98", "string", "PlsNoBan       ");
        Console.WriteLine(MemLib.readString("0x184C3A98"));

    }
}
</code>```

}

答:
Omg I am stupid.. xD </p>

<p>I needed to do MemLib.OpenGameProcess(robloxPid) </p>

Title: C# Trying to find the RobloxPlayerBeta

Body:
Here is my code: I am trying to find the roblox PlayerBeta but its not working
I am not the best in coding but I found out how to find it but cant implent it right into the code

( EDIT ) The program works if I use the PID but that changes everytime I open up a new RobloxPlayerBeta ! so I cannot use that

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Memory;
    using System.Diagnostics;

    namespace ForceField
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            Mem MemLib = new Mem();

            private void button1_Click(object sender, EventArgs e)
            {

                if (System.Diagnostics.Process.GetProcesses().Any((p) =>                                                                                p.ProcessName.Contains("RobloxPlayerBeta")))
        {
            int robloxPid = System.Diagnostics.Process.GetProcessesByName("RobloxPlayerBeta").FirstOrDefault().Id;
        }
        Console.WriteLine(robloxPid);
        MemLib.writeMemory("0x184C3A98", "string", "PlsNoBan       ");
        Console.WriteLine(MemLib.readString("0x184C3A98"));

    }
}

}

Body:
Omg I am stupid.. xD

I needed to do MemLib.OpenGameProcess(robloxPid)


问:
How to make a straighttable evaluate unique ids from previous months and not include the same ids the next month in Qlikview
Let's say that I have the following table

```<code>    Name    Tattoo  Month  Team
    Bob     No      Jan    Team1
    Kelly   No      Jan    Team1
    Andrew  Yes     Jan    Team1
    Bob     No      Feb    Team1
    Kelly   No      Feb    Team1
    Andrew  Yes     Feb    Team1
</code>```

And the resulting straighttable that I want to create is this

```<code>Month    Tattoos_Team_1
Jan      1
Feb      0
</code>```

In other words, if a person already had a tattoo the previous month, I don't want that same person to be included in the next month in the straighttable.

This is what my script code currently looks like:

```<code>Table1:
LOAD Distinct Name,
     Tattoo,
     if(Tattoo='Yes','TYes')as YesTattoo,
     Month,
     Team,
     if(Team='Team1','Team 1') as Team_1,
     if(Team='Team2','Team 2') as Team_2,
     if(Team='Team3','Team 3') as Team_3
FROM
[Bok1.xlsx]
(ooxml, embedded labels);
</code>```

And in my straighttable i've set Month as dimension and Count(Distinct {<YesTattoo>}Team_1) as expression.

Any help is appreciated!

答:
Assuming people is not erasing their tattoos and that you will show your months in ascendent order, you can simply subtract the tattoos of the previous month:</p>

```<code>Count(Distinct {<YesTattoo>}Team_1) - above([Tattoos_Team_1])
</code>```

Body:
Let's say that I have the following table

    Name    Tattoo  Month  Team
    Bob     No      Jan    Team1
    Kelly   No      Jan    Team1
    Andrew  Yes     Jan    Team1
    Bob     No      Feb    Team1
    Kelly   No      Feb    Team1
    Andrew  Yes     Feb    Team1

And the resulting straighttable that I want to create is this

Month    Tattoos_Team_1
Jan      1
Feb      0

In other words, if a person already had a tattoo the previous month, I don't want that same person to be included in the next month in the straighttable.

This is what my script code currently looks like:

Table1:
LOAD Distinct Name,
     Tattoo,
     if(Tattoo='Yes','TYes')as YesTattoo,
     Month,
     Team,
     if(Team='Team1','Team 1') as Team_1,
     if(Team='Team2','Team 2') as Team_2,
     if(Team='Team3','Team 3') as Team_3
FROM
[Bok1.xlsx]
(ooxml, embedded labels);

And in my straighttable i've set Month as dimension and Count(Distinct {<YesTattoo>}Team_1) as expression.

Any help is appreciated!

Body:
Assuming people is not erasing their tattoos and that you will show your months in ascendent order, you can simply subtract the tattoos of the previous month:

Count(Distinct {<YesTattoo>}Team_1) - above([Tattoos_Team_1])


问:
Call to undefined method CI_DB_mysqli_result::fetch_assoc() in CodeIgniter
I have following function

```<code>function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->fetch_assoc();  //Line 55
                break;
            default:
                if($result->num_rows > 0){
                    while($row = $result->fetch_assoc()){
                        $data[] = $row;
                    }
                }
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}
</code>```

When this method is executed following error is returned

Type: Error

Message: Call to undefined method CI_DB_mysqli_result::fetch_assoc()

Line Number: 55

I can't understand why the error is being shown. Please help!!!

答:
You can try this solution for your problem :</p>

```<code>function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->row();  // CodeIgniter return single row
                break;
            default:
                if($result->num_rows > 0){
                    $data = $result->result(); // CodeIgniter return result object and you can set result_array() get array list
                }
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}
</code>```

Body:
I have following function

function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->fetch_assoc();  //Line 55
                break;
            default:
                if($result->num_rows > 0){
                    while($row = $result->fetch_assoc()){
                        $data[] = $row;
                    }
                }
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}

When this method is executed following error is returned

Type: Error

Message: Call to undefined method CI_DB_mysqli_result::fetch_assoc()

Line Number: 55

I can't understand why the error is being shown. Please help!!!

Body:
You can try this solution for your problem :

function getQuery($sql,$returnType = ''){
    $data = array();
    $result = $this->db->query($sql);
    if($result){
        switch($returnType){
            case 'count':
                $data = $result->num_rows;
                break;
            case 'single':
                $data = $result->row();  // CodeIgniter return single row
                break;
            default:
                if($result->num_rows > 0){
                    $data = $result->result(); // CodeIgniter return result object and you can set result_array() get array list
                }
        }
    }
    if(!empty($data)) {
        return $data;
    }
    return false;
}


问:
AppCode Interface Builder
Are there any plugins for AppCode so that I can edit and design the user interface like the Interface Builder in Xcode?

I prefer AppCode because it's customizable but it appears to me that it doesn't have its own Interface Builder.

答:
No. JetBrains previously shipped a UI Designer plugin, but have stopped developing it.

For many projects you will be using AppCode in parallel with Xcode. Use each for its strengths: eg. AppCode for writing code, refactoring and debugging, Xcode for Interface Builder and Core Data models. There is an AppCode command Open Project in Xcode, for which you can easily add a keybinding in Prefs -> Keymap

There's no real disadvantage to using AppCode with Xcode as in order to build macOS/iOS projects you need Xcode installed anyway.

ContentLicense: CC BY-SA 4.0

Title: AppCode Interface Builder


问:
Rotation of Matrix in Space Results in Moving and do not Rotate to Place on Matlab
Matrix contains the point cloud of surface of ellipsoid. Need to rotate that matrix and centroid should not move anywhere.

Centroid of ellipsoid is at [xc1,yc1,zc1]

Rotation should be in such manner that new location of point [xp1,yp1,zp1] should be at reference point [rx,ry,rz]. Radius of point and reference are equal. Whole matrix will rotate by following the only that point.

To do this task, I have tried to find projections of line from [xc1,yc1,zc1] to [xp1,yp1,zp1] on xy,yz and xz planes and find the angles. This part done as shown here. Then repeated same procedure for the line between [xc1,yc1,zc1] and [rx,ry,rz].

```<code>iniV = [xc1 - xp1,yc1 - yp1,zc1 - zp1];
nextV = [xc1 - xr,yc1 - yr,zc1 - zr];

%Projected angles for point
[zRotIni, yRotIni, xRotIni] = projectionAngle(iniV);
%Projected angles for refence
[zRotNext, yRotNext, xRotNext] = projectionAngle(nextV);
</code>```

I assumed that the difference of angles of point and reference will give me the information how much needed to rotate around each axis. i.e: Angle on yz plane will give the how much needed to rotate around x axis.

```<code>xRotAngle = xRotNext - xRotIni;
yRotAngle = yRotNext - yRotIni;
zRotAngle = zRotNext - zRotIni;
</code>```

By using Matlab's functions rotation of matrix done as shown below

```<code>rX = rotx(xRotAngle);
rY = roty(yRotAngle);
rZ = rotz(zRotAngle);

%vertexT is point cloud matrix
vertexRotT = rX * vertexT; %rotate around x axis
%After rotating around x, rotate around y axis
vertexRotT = rY * vertexRotT;
vertexRotT = rZ * vertexRotT;
</code>```

The result is shown on below figure.

Blue ellipsoid is the original

Blue line is point's vector

Red line is showing the reference line

After rotation, blue and red line should on each other. However whole ellipsoid moved to new place which's centroid coordinate is at [xc2,yc2,zc2] and point is at [xp2,yp2,zp2].

As a result, rotation assumption not worked and shape moved to somewhere .However the centroid always should be pinned at [xc1,yc1,zc1]

答:
Move the matrix to the origin [0, 0, 0]

Perform the rotations

Move the matrix back to its initial centre location [xc1,yc1,zc1]

Body:
Matrix contains the point cloud of surface of ellipsoid. Need to rotate that matrix and centroid should not move anywhere.

Centroid of ellipsoid is at [xc1,yc1,zc1]

Rotation should be in such manner that new location of point [xp1,yp1,zp1] should be at reference point [rx,ry,rz]. Radius of point and reference are equal. Whole matrix will rotate by following the only that point.

To do this task, I have tried to find projections of line from [xc1,yc1,zc1] to [xp1,yp1,zp1] on xy,yz and xz planes and find the angles. This part done as shown here. Then repeated same procedure for the line between [xc1,yc1,zc1] and [rx,ry,rz].

iniV = [xc1 - xp1,yc1 - yp1,zc1 - zp1];
nextV = [xc1 - xr,yc1 - yr,zc1 - zr];

%Projected angles for point
[zRotIni, yRotIni, xRotIni] = projectionAngle(iniV);
%Projected angles for refence
[zRotNext, yRotNext, xRotNext] = projectionAngle(nextV);

I assumed that the difference of angles of point and reference will give me the information how much needed to rotate around each axis. i.e: Angle on yz plane will give the how much needed to rotate around x axis.

xRotAngle = xRotNext - xRotIni;
yRotAngle = yRotNext - yRotIni;
zRotAngle = zRotNext - zRotIni;

By using Matlab's functions rotation of matrix done as shown below

rX = rotx(xRotAngle);
rY = roty(yRotAngle);
rZ = rotz(zRotAngle);

%vertexT is point cloud matrix
vertexRotT = rX * vertexT; %rotate around x axis
%After rotating around x, rotate around y axis
vertexRotT = rY * vertexRotT;
vertexRotT = rZ * vertexRotT;

The result is shown on below figure.

Blue ellipsoid is the original

Blue line is point's vector

Red line is showing the reference line

After rotation, blue and red line should on each other. However whole ellipsoid moved to new place which's centroid coordinate is at [xc2,yc2,zc2] and point is at [xp2,yp2,zp2].

As a result, rotation assumption not worked and shape moved to somewhere .However the centroid always should be pinned at [xc1,yc1,zc1]


问:
How to convert pdf file to excel in c#
I want to extract some data like " email addresses " .. from table which are in PDF file and use this email addresses which I extract to send email to those people.

What I have found so far through searching the web:

I have to convert the PDF file to Excel to read the data easily and use them as I want.

I find some free dll like itextsharp or PDFsharp.

But I didn't find any snippet code help to do this in C#. is there any solution ?

答:
Using bytescout PDF Extractor SDK we can be able to extract the whole page to csv as below.</p>

```<code>CSVExtractor extractor = new CSVExtractor();
extractor.RegistrationName = "demo";
extractor.RegistrationKey = "demo";

TableDetector tdetector = new TableDetector();
tdetector.RegistrationKey = "demo";
tdetector.RegistrationName = "demo";

// Load the document
extractor.LoadDocumentFromFile("C:\\sample.pdf");
tdetector.LoadDocumentFromFile("C:\\sample.pdf");

int pageCount = tdetector.GetPageCount();

for (int i = 1; i <= pageCount; i++)
{
    int j = 1;

        do
        {
                extractor.SetExtractionArea(tdetector.GetPageRect_Left(i),
                tdetector.GetPageRect_Top(i),
                tdetector.GetPageRect_Width(i),
                tdetector.GetPageRect_Height(i)
            );

            // and finally save the table into CSV file
            extractor.SavePageCSVToFile(i, "C:\\page-" + i + "-table-" + j + ".csv");
            j++;
        } while (tdetector.FindNextTable()); // search next table
}
</code>```

Title: How to convert pdf file to excel in c#

Body:
Using bytescout PDF Extractor SDK we can be able to extract the whole page to csv as below.

CSVExtractor extractor = new CSVExtractor();
extractor.RegistrationName = "demo";
extractor.RegistrationKey = "demo";

TableDetector tdetector = new TableDetector();
tdetector.RegistrationKey = "demo";
tdetector.RegistrationName = "demo";

// Load the document
extractor.LoadDocumentFromFile("C:\\sample.pdf");
tdetector.LoadDocumentFromFile("C:\\sample.pdf");

int pageCount = tdetector.GetPageCount();

for (int i = 1; i <= pageCount; i++)
{
    int j = 1;

        do
        {
                extractor.SetExtractionArea(tdetector.GetPageRect_Left(i),
                tdetector.GetPageRect_Top(i),
                tdetector.GetPageRect_Width(i),
                tdetector.GetPageRect_Height(i)
            );

            // and finally save the table into CSV file
            extractor.SavePageCSVToFile(i, "C:\\page-" + i + "-table-" + j + ".csv");
            j++;
        } while (tdetector.FindNextTable()); // search next table
}


问:
Laravel constraining eager loading not working
I am making a query where I would like to check the relationship that I have set up like this:

Content model:

```<code>public function contentType()
{
    return $this->belongsTo('App\ContentType', 'ct_id');
}
</code>```

ContentType

```<code>public function contents()
{
    return $this->hasMany('App\Content', 'ct_id');
}
</code>```

And, then I have tried to do a query like this:

```<code>$content = Content::where('slug', $arguments['slug'])
                ->with(['contentType' => function ($query) {
                    $query->where('slug', 'post');
                }])->get();

return $content;
</code>```

Where I wanted to get $content from the Db, that has the contentType of slug post, and I am getting the content from the table, but after testing it, I am getting the same record every time no matter what I put as a slug for contentType. I only have one record in the Db, that is why I am getting the same record, but I should even get that one, if it doesn't have the contentType that has a slug different than post. What am I doing wrong?

答:
I was able to achieve what I want with whereHas query:

```<code>$content = Content::whereHas('contentType', function ($query) {
                    $query->whereIn('slug', ['post', 'page']);
                })
                ->where('slug', $arguments['slug'])
                ->with('supplementary')
                ->first();
</code>```

That way I fetch only content that has either post or page as a slug in the  contentType relationship.

Body:
I am making a query where I would like to check the relationship that I have set up like this:

Content model:

public function contentType()
{
    return $this->belongsTo('App\ContentType', 'ct_id');
}

ContentType

public function contents()
{
    return $this->hasMany('App\Content', 'ct_id');
}

And, then I have tried to do a query like this:

$content = Content::where('slug', $arguments['slug'])
                ->with(['contentType' => function ($query) {
                    $query->where('slug', 'post');
                }])->get();

return $content;

Where I wanted to get $content from the Db, that has the contentType of slug post, and I am getting the content from the table, but after testing it, I am getting the same record every time no matter what I put as a slug for contentType. I only have one record in the Db, that is why I am getting the same record, but I should even get that one, if it doesn't have the contentType that has a slug different than post. What am I doing wrong?

Body:
I was able to achieve what I want with whereHas query:

$content = Content::whereHas('contentType', function ($query) {
                    $query->whereIn('slug', ['post', 'page']);
                })
                ->where('slug', $arguments['slug'])
                ->with('supplementary')
                ->first();

That way I fetch only content that has either post or page as a slug in the  contentType relationship.


问:
Is it the efficeint program to rotate array in left direction?
```<code>#include<stdio.h>
#include<stdlib.h>

main()
{
    int i,j,l,m,n;
    j=0;
    printf("\nenter 5 element single dimension array\n");
    printf("enter shift rate\n");
    scanf("%d",&n);

    /* Here we take input from user that by what times user wants to rotate the array in left. */

    int arr[5],arrb[n];
    for(i=0;i<=4;i++){
        scanf("%d",&arr[i]);
    }

    /* Here we have taken another array. */

    for(i=0;i<=4;i++){
        printf("%d",arr[i]);
    }
    for(i=0;i<n;i++){
        arrb[j]=arr[i];
        j++;
        // These loop will shift array element to left by position which's entered by user.
    }
    printf("\n");

    for(i=0;i<=3;i++){
        arr[i]=arr[i+n];
    }
    for(i=0;i<=4;i++){
        if(n==1 && i==4)
            break;
        if(n==2 && i==3)
            break;
        if(n==3 && i==2)
            break;
        printf("%d",arr[i]);
    }

    //To combine these two arrays. Make it look like  single array instead of two
    for(i=0;i<n;i++){
        printf("%d",arrb[i]);
    }
    // Final sorted array will get printed here
}
</code>```

答:
Is it the efficeint program to rotate array in left direction?

Actually, very complicated, and some problems contained:

```<code>for(i = 0; i < n; i++)
{
    arrb[j] = arr[i];
    j++;
}
</code>```

Why not simply:

```<code>for(i = 0; i < n; i++)
{
     arrb[i] = arr[i];
}
</code>```

There is no need for a second variable. Still, if n is greater than five, you get into trouble, as you will access arr out of its bounts (undefined behaviour!). At least, you should check the user input!

```<code>for(i = 0; i <=3 ; i++)
{
    arr[i] = arr[i + n];
}
</code>```

Same problem: last accessible index is 4 (four), so n must not exceed 1, or you again access the array out of bounds...

Those many 'if's within the printing loop for the first array cannot be efficient...

You can have it much, much simpler:

```<code>int arr[5], arrb[5];
//               ^

for(int i = 0; i < 5; ++i)
    arrb[i] = arr[(i + n) % 5];
</code>```

This does not cover negative values of n, though.

```<code>    arrb[i] = arr[(((i + n) % 5) + 5) % 5];
</code>```

would be safe even for negative values... All you need now for the output is:

```<code>for(int i = 0; i < 5; ++i)
    printf("%d ", arrb[i]);
</code>```

There would be one last point uncovered, though: if user enters for n a value greater than INT_MAX - 4, you get a signed integer overflow, which again is undefined behaviour!

We can again cover this by changing the index formula:

```<code>arrb[i] = arr[(5 + i + (n % 5)) % 5];
</code>```

n % 5 is invariant, so we can move it out of the loop:

```<code>n %= 5;
for(int i = 0; i < 5; ++i)
    arrb[i] = arr[(5 + i + n) % 5];
</code>```

Finally, if we make n positive already outside, we can spare the addition in the for loop.

```<code>n = ((n % 5) + 5) % 5;
for(int i = 0; i < 5; ++i)
    arrb[i] = arr[(i + n) % 5]; // my original formula again...
</code>```

Last step is especially worth considering for very long running loops.

Body:
Is it the efficeint program to rotate array in left direction?

Actually, very complicated, and some problems contained:

for(i = 0; i < n; i++)
{
    arrb[j] = arr[i];
    j++;
}

Why not simply:

for(i = 0; i < n; i++)
{
     arrb[i] = arr[i];
}

There is no need for a second variable. Still, if n is greater than five, you get into trouble, as you will access arr out of its bounts (undefined behaviour!). At least, you should check the user input!

for(i = 0; i <=3 ; i++)
{
    arr[i] = arr[i + n];
}

Same problem: last accessible index is 4 (four), so n must not exceed 1, or you again access the array out of bounds...

Those many 'if's within the printing loop for the first array cannot be efficient...

You can have it much, much simpler:

int arr[5], arrb[5];
//               ^

for(int i = 0; i < 5; ++i)
    arrb[i] = arr[(i + n) % 5];

This does not cover negative values of n, though.

    arrb[i] = arr[(((i + n) % 5) + 5) % 5];

would be safe even for negative values... All you need now for the output is:

for(int i = 0; i < 5; ++i)
    printf("%d ", arrb[i]);

There would be one last point uncovered, though: if user enters for n a value greater than INT_MAX - 4, you get a signed integer overflow, which again is undefined behaviour!

We can again cover this by changing the index formula:

arrb[i] = arr[(5 + i + (n % 5)) % 5];

n % 5 is invariant, so we can move it out of the loop:

n %= 5;
for(int i = 0; i < 5; ++i)
    arrb[i] = arr[(5 + i + n) % 5];

Finally, if we make n positive already outside, we can spare the addition in the for loop.

n = ((n % 5) + 5) % 5;
for(int i = 0; i < 5; ++i)
    arrb[i] = arr[(i + n) % 5]; // my original formula again...

Last step is especially worth considering for very long running loops.


问:
All the links in the same row
I'm doing a database where it has 2 columns: event_name and event_URL. It doesn't get the name and puts all the urls on the event_URL column. Print: https://prnt.sc/fru1tr

Code:

```<code>import urllib2
from bs4 import BeautifulSoup
import psycopg2

page = urllib2.urlopen('https://www.meetup.com/find/outdoors-adventure/?allMeetups=false&radius=50&userFreeform=London%2C+&mcId=c1012717&change=yes&sort=default')
soup = BeautifulSoup(page, 'lxml')

events = soup.find('ul', class_='j-groupCard-list searchResults tileGrid tileGrid--3col tileGrid_atMedium--2col tileGrid_atSmall--1col')

A = []
B = []

try:
    conn = psycopg2.connect("dbname='meetup' user='postgres' host='localhost' password='root'")
except:
    print 'Unable to connect to the database.'

cur = conn.cursor()

for event in events.findAll('li'):
    text = event.findAll('h3')
    if len(text) != 0:
        A.append(text[0].find(text = True))
    url = event.find('a', href=True)
    if len(url) != 0:
        B.append(url['href'])
    cur.execute("""INSERT INTO outdoors_adventure(event_name,event_url) VALUES(%s,%s)""", (tuple(A),tuple(B)))
    conn.commit()
    del A[:]
    del B[:]
</code>```

答:
If the indentation is right in the posted code, the problem might be in the nested for-loop: for every event, you append the "B" list with all the links on the page. You could try:

```<code>for event in events.findAll('li'):
    text = event.findAll('h3')
    if len(text) != 0:
        A.append(text[0].find(text = True))
for link in events.findAll('li'):
    url = link.find('a', href=True)
    if len(url) != 0:
        B.append(url['href'])
</code>```

Or better, keep the event-name and event-URL search in a single for-loop, fetching first the text and then the url of event

EDIT: You can simplify the name extraction, by using:

```<code>for event in events.findAll('li'):
    text = event.h3.string.strip()
    if len(text) != 0:
        A.append(text)
    url = event.find('a', href=True)
    ...
</code>```

Let me know if that does the trick for you (it does on my side).

EDIT2: The problem might be just the fact that the extracted string starts with tabs (maybe that's why your DB seems "not to show the name" - its there, but you only see the tabs in the preview?). Just use strip() to remove them.

Title: All the links in the same row

Body:
I'm doing a database where it has 2 columns: event_name and event_URL. It doesn't get the name and puts all the urls on the event_URL column. Print: https://prnt.sc/fru1tr

Code:

import urllib2
from bs4 import BeautifulSoup
import psycopg2

page = urllib2.urlopen('https://www.meetup.com/find/outdoors-adventure/?allMeetups=false&radius=50&userFreeform=London%2C+&mcId=c1012717&change=yes&sort=default')
soup = BeautifulSoup(page, 'lxml')

events = soup.find('ul', class_='j-groupCard-list searchResults tileGrid tileGrid--3col tileGrid_atMedium--2col tileGrid_atSmall--1col')

A = []
B = []

try:
    conn = psycopg2.connect("dbname='meetup' user='postgres' host='localhost' password='root'")
except:
    print 'Unable to connect to the database.'

cur = conn.cursor()

for event in events.findAll('li'):
    text = event.findAll('h3')
    if len(text) != 0:
        A.append(text[0].find(text = True))
    url = event.find('a', href=True)
    if len(url) != 0:
        B.append(url['href'])
    cur.execute("""INSERT INTO outdoors_adventure(event_name,event_url) VALUES(%s,%s)""", (tuple(A),tuple(B)))
    conn.commit()
    del A[:]
    del B[:]

Body:
If the indentation is right in the posted code, the problem might be in the nested for-loop: for every event, you append the "B" list with all the links on the page. You could try:

for event in events.findAll('li'):
    text = event.findAll('h3')
    if len(text) != 0:
        A.append(text[0].find(text = True))
for link in events.findAll('li'):
    url = link.find('a', href=True)
    if len(url) != 0:
        B.append(url['href'])

Or better, keep the event-name and event-URL search in a single for-loop, fetching first the text and then the url of event

EDIT: You can simplify the name extraction, by using:

for event in events.findAll('li'):
    text = event.h3.string.strip()
    if len(text) != 0:
        A.append(text)
    url = event.find('a', href=True)
    ...

Let me know if that does the trick for you (it does on my side).

EDIT2: The problem might be just the fact that the extracted string starts with tabs (maybe that's why your DB seems "not to show the name" - its there, but you only see the tabs in the preview?). Just use strip() to remove them.


问:
PL/SQL use a value declared for setting a sequence start
I'm new in PL/SQL in Oracle and what I've tried so far doesn't work

I want to get the max(id) of my table... And then create a SEQUENCE which starts with this maxID+1

```<code>DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  CREATE SEQUENCE "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH maxId CACHE 20 NOORDER NOCYCLE;
END;
/
</code>```

But I can't use CREATE here ...

How can I achieve this ?

答:
Dynamic SQL as follows:

```<code>DECLARE
  maxId NUMBER;
  v_sql varchar(200);
BEGIN
  SELECT max(ID) INTO maxId FROM MyTable;
  v_sql := 'CREATE SEQUENCE SEQ_TABLE  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH '|| to_char(maxId) ||' CACHE 20 NOORDER NOCYCLE';
  execute immediate v_sql;
END;
/
</code>```

All the edits...

Body:
I'm new in PL/SQL in Oracle and what I've tried so far doesn't work

I want to get the max(id) of my table... And then create a SEQUENCE which starts with this maxID+1

DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  CREATE SEQUENCE "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH maxId CACHE 20 NOORDER NOCYCLE;
END;
/

But I can't use CREATE here ...

How can I achieve this ?

Body:
Dynamic SQL as follows:

DECLARE
  maxId NUMBER;
  v_sql varchar(200);
BEGIN
  SELECT max(ID) INTO maxId FROM MyTable;
  v_sql := 'CREATE SEQUENCE SEQ_TABLE  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH '|| to_char(maxId) ||' CACHE 20 NOORDER NOCYCLE';
  execute immediate v_sql;
END;
/

All the edits...


问:
How do I encode HTTP GET query strings in Perl?
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

```<code>use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);
</code>```

答:
Use LWP::UserAgent instead:

```<code>use strict;
use warnings;

use LWP::UserAgent;

my %query_hash = (spam => 'eggs', foo => 'bar baz');

my $ua = LWP::UserAgent->new();
my $resp = $ua->get("http://www.foobar.com", %query_hash);

print $resp->content;
</code>```

It takes care of the encoding for you.

If you want a more generic encoding solution, see HTML::Entities.

EDIT: URI::Escape is a better choice.

OwnerDisplayName: cdleary

Body:
This question is somewhat related to What’s the simplest way to make a HTTP GET request in Perl?.

Before making the request via LWP::Simple I have a hash of query string components that I need to serialize/escape. What's the best way to encode the query string? It should take into account spaces and all the characters that need to be escaped in valid URIs. I figure it's probably in an existing package, but I'm not sure how to go about finding it.

use LWP::Simple;
my $base_uri = 'http://example.com/rest_api/';
my %query_hash = (spam => 'eggs', foo => 'bar baz');
my $query_string = urlencode(query_hash); # Part in question.
my $query_uri = "$base_uri?$query_string";
# http://example.com/rest_api/?spam=eggs&foo=bar+baz
$contents = get($query_uri);

LastEditorDisplayName: cdleary

Body:
Use LWP::UserAgent instead:

use strict;
use warnings;

use LWP::UserAgent;

my %query_hash = (spam => 'eggs', foo => 'bar baz');

my $ua = LWP::UserAgent->new();
my $resp = $ua->get("http://www.foobar.com", %query_hash);

print $resp->content;

It takes care of the encoding for you.

If you want a more generic encoding solution, see HTML::Entities.

EDIT: URI::Escape is a better choice.

OwnerDisplayName: Joe Casadonte


问:
Cycle finding algorithm
I need do find a cycle beginning and ending at given point. It is not guaranteed that it exists.
I use bool[,] points to indicate which point can be in cycle. Poins can be only on grid. points indicates if given point on grid can be in cycle.
I need to find this cycle using as minimum number of points.
One point can be used only once.
Connection can be only vertical or horizontal.

Let this be our points (red is starting point):

removing dead ImageShack links

I realized that I can do this:

```<code>while(numberOfPointsChanged)
{
    //remove points that are alone in row or column
}
</code>```

So i have:

removing dead ImageShack links

Now, I can find the path.

removing dead ImageShack links

But what if there are points that are not deleted by this loop but should not be in path?

I have written code:

```<code>class MyPoint
{
    public int X { get; set; }
    public int Y { get; set; }
    public List<MyPoint> Neighbours = new List<MyPoint>();
    public MyPoint parent = null;
    public bool marked = false;
}

    private static MyPoint LoopSearch2(bool[,] mask, int supIndexStart, int recIndexStart)
    {
        List<MyPoint> points = new List<MyPoint>();

        //here begins translation bool[,] to list of points
        points.Add(new MyPoint { X = recIndexStart, Y = supIndexStart });

        for (int i = 0; i < mask.GetLength(0); i++)
        {
            for (int j = 0; j < mask.GetLength(1); j++)
            {
                if (mask[i, j])
                {
                    points.Add(new MyPoint { X = j, Y = i });
                }
            }
        }

        for (int i = 0; i < points.Count; i++)
        {
            for (int j = 0; j < points.Count; j++)
            {
                if (i != j)
                {
                    if (points[i].X == points[j].X || points[i].Y == points[j].Y)
                    {
                        points[i].Neighbours.Add(points[j]);
                    }
                }
            }
        }
        //end of translating

        List<MyPoint> queue = new List<MyPoint>();
        MyPoint start = (points[0]); //beginning point
        start.marked = true; //it is marked
        MyPoint last=null;   //last point. this will be returned
        queue.Add(points[0]);

        while(queue.Count>0)
        {
            MyPoint current = queue.First(); //taking point from queue
            queue.Remove(current);           //removing it

            foreach(MyPoint neighbour in current.Neighbours) //checking Neighbours
            {
                if (!neighbour.marked) //in neighbour isn't marked adding it to queue
                {
                    neighbour.marked = true;
                    neighbour.parent = current;
                    queue.Add(neighbour);
                }
                //if neighbour is marked checking if it is startig point and if neighbour's parent is current point. if it is not that means that loop already got here so we start searching parents to got to starting point
                else if(!neighbour.Equals(start) && !neighbour.parent.Equals(current))
                {
                    current = neighbour;
                    while(true)
                    {
                        if (current.parent.Equals(start))
                        {
                            last = current;
                            break;
                        }
                        else
                            current = current.parent;

                    }
                    break;
                }
            }
        }

        return last;
    }
</code>```

But it doesn't work. The path it founds contains two points: start and it's first neighbour.

What am I doing wrong?

EDIT:
Forgot to mention... After horizontal connection there has to be vertical, horizontal, vertical and so on...
What is more in each row and column there need to be max two points (two or none) that are in the cycle. But this condition is the same as "The cycle has to be the shortest one".

答:
That is what I have done. I don't know if it is optimised but it does work correctly. I have not done the sorting of the points as @marcog suggested.        </p>

```<code>private static bool LoopSearch2(bool[,] mask, int supIndexStart, int recIndexStart, out List<MyPoint> path)
    {
        List<MyPoint> points = new List<MyPoint>();
        points.Add(new MyPoint { X = recIndexStart, Y = supIndexStart });

        for (int i = 0; i < mask.GetLength(0); i++)
        {
            for (int j = 0; j < mask.GetLength(1); j++)
            {
                if (mask[i, j])
                {
                    points.Add(new MyPoint { X = j, Y = i });
                }
            }
        }

        for (int i = 0; i < points.Count; i++)
        {
            for (int j = 0; j < points.Count; j++)
            {
                if (i != j)
                {
                    if (points[i].X == points[j].X || points[i].Y == points[j].Y)
                    {
                        points[i].Neighbours.Add(points[j]);
                    }
                }
            }
        }

        List<MyPoint> queue = new List<MyPoint>();
        MyPoint start = (points[0]);
        start.marked = true;
        queue.Add(points[0]);

        path = new List<MyPoint>();

        bool found = false;

        while(queue.Count>0)
        {
            MyPoint current = queue.First();
            queue.Remove(current);

            foreach (MyPoint neighbour in current.Neighbours)
            {
                if (!neighbour.marked)
                {
                    neighbour.marked = true;
                    neighbour.parent = current;
                    queue.Add(neighbour);
                }
                else
                {
                    if (neighbour.parent != null && neighbour.parent.Equals(current))
                        continue;

                    if (current.parent == null)
                        continue;

                    bool previousConnectionHorizontal = current.parent.Y == current.Y;
                    bool currentConnectionHorizontal = current.Y == neighbour.Y;

                    if (previousConnectionHorizontal != currentConnectionHorizontal)
                    {
                        MyPoint prev = current;

                        while (true)
                        {
                            path.Add(prev);
                            if (prev.Equals(start))
                                break;
                            prev = prev.parent;
                        }

                        path.Reverse();

                        prev = neighbour;

                        while (true)
                        {
                            if (prev.Equals(start))
                                break;
                            path.Add(prev);
                            prev = prev.parent;
                        }

                        found = true;
                        break;
                    }
                }
                if (found) break;
            }
            if (found) break;
        }

        if (path.Count == 0)
        {
            path = null;
            return false;
        }
        return true;
    }
</code>```

Title: Cycle finding algorithm

Body:
I need do find a cycle beginning and ending at given point. It is not guaranteed that it exists.
I use bool[,] points to indicate which point can be in cycle. Poins can be only on grid. points indicates if given point on grid can be in cycle.
I need to find this cycle using as minimum number of points.
One point can be used only once.
Connection can be only vertical or horizontal.

Let this be our points (red is starting point):

removing dead ImageShack links

I realized that I can do this:

while(numberOfPointsChanged)
{
    //remove points that are alone in row or column
}

So i have:

removing dead ImageShack links

Now, I can find the path.

removing dead ImageShack links

But what if there are points that are not deleted by this loop but should not be in path?

I have written code:

class MyPoint
{
    public int X { get; set; }
    public int Y { get; set; }
    public List<MyPoint> Neighbours = new List<MyPoint>();
    public MyPoint parent = null;
    public bool marked = false;
}

    private static MyPoint LoopSearch2(bool[,] mask, int supIndexStart, int recIndexStart)
    {
        List<MyPoint> points = new List<MyPoint>();

        //here begins translation bool[,] to list of points
        points.Add(new MyPoint { X = recIndexStart, Y = supIndexStart });

        for (int i = 0; i < mask.GetLength(0); i++)
        {
            for (int j = 0; j < mask.GetLength(1); j++)
            {
                if (mask[i, j])
                {
                    points.Add(new MyPoint { X = j, Y = i });
                }
            }
        }

        for (int i = 0; i < points.Count; i++)
        {
            for (int j = 0; j < points.Count; j++)
            {
                if (i != j)
                {
                    if (points[i].X == points[j].X || points[i].Y == points[j].Y)
                    {
                        points[i].Neighbours.Add(points[j]);
                    }
                }
            }
        }
        //end of translating

        List<MyPoint> queue = new List<MyPoint>();
        MyPoint start = (points[0]); //beginning point
        start.marked = true; //it is marked
        MyPoint last=null;   //last point. this will be returned
        queue.Add(points[0]);

        while(queue.Count>0)
        {
            MyPoint current = queue.First(); //taking point from queue
            queue.Remove(current);           //removing it

            foreach(MyPoint neighbour in current.Neighbours) //checking Neighbours
            {
                if (!neighbour.marked) //in neighbour isn't marked adding it to queue
                {
                    neighbour.marked = true;
                    neighbour.parent = current;
                    queue.Add(neighbour);
                }
                //if neighbour is marked checking if it is startig point and if neighbour's parent is current point. if it is not that means that loop already got here so we start searching parents to got to starting point
                else if(!neighbour.Equals(start) && !neighbour.parent.Equals(current))
                {
                    current = neighbour;
                    while(true)
                    {
                        if (current.parent.Equals(start))
                        {
                            last = current;
                            break;
                        }
                        else
                            current = current.parent;

                    }
                    break;
                }
            }
        }

        return last;
    }

But it doesn't work. The path it founds contains two points: start and it's first neighbour.

What am I doing wrong?

EDIT:
Forgot to mention... After horizontal connection there has to be vertical, horizontal, vertical and so on...
What is more in each row and column there need to be max two points (two or none) that are in the cycle. But this condition is the same as "The cycle has to be the shortest one".

Body:
That is what I have done. I don't know if it is optimised but it does work correctly. I have not done the sorting of the points as @marcog suggested.

private static bool LoopSearch2(bool[,] mask, int supIndexStart, int recIndexStart, out List<MyPoint> path)
    {
        List<MyPoint> points = new List<MyPoint>();
        points.Add(new MyPoint { X = recIndexStart, Y = supIndexStart });

        for (int i = 0; i < mask.GetLength(0); i++)
        {
            for (int j = 0; j < mask.GetLength(1); j++)
            {
                if (mask[i, j])
                {
                    points.Add(new MyPoint { X = j, Y = i });
                }
            }
        }

        for (int i = 0; i < points.Count; i++)
        {
            for (int j = 0; j < points.Count; j++)
            {
                if (i != j)
                {
                    if (points[i].X == points[j].X || points[i].Y == points[j].Y)
                    {
                        points[i].Neighbours.Add(points[j]);
                    }
                }
            }
        }

        List<MyPoint> queue = new List<MyPoint>();
        MyPoint start = (points[0]);
        start.marked = true;
        queue.Add(points[0]);

        path = new List<MyPoint>();

        bool found = false;

        while(queue.Count>0)
        {
            MyPoint current = queue.First();
            queue.Remove(current);

            foreach (MyPoint neighbour in current.Neighbours)
            {
                if (!neighbour.marked)
                {
                    neighbour.marked = true;
                    neighbour.parent = current;
                    queue.Add(neighbour);
                }
                else
                {
                    if (neighbour.parent != null && neighbour.parent.Equals(current))
                        continue;

                    if (current.parent == null)
                        continue;

                    bool previousConnectionHorizontal = current.parent.Y == current.Y;
                    bool currentConnectionHorizontal = current.Y == neighbour.Y;

                    if (previousConnectionHorizontal != currentConnectionHorizontal)
                    {
                        MyPoint prev = current;

                        while (true)
                        {
                            path.Add(prev);
                            if (prev.Equals(start))
                                break;
                            prev = prev.parent;
                        }

                        path.Reverse();

                        prev = neighbour;

                        while (true)
                        {
                            if (prev.Equals(start))
                                break;
                            path.Add(prev);
                            prev = prev.parent;
                        }

                        found = true;
                        break;
                    }
                }
                if (found) break;
            }
            if (found) break;
        }

        if (path.Count == 0)
        {
            path = null;
            return false;
        }
        return true;
    }


问:
Where can I download SignalR.Client.20.dll?
I want to make multiplayer game in Unity. So I need  SignalR.Client.20.dll file . Where can I download this?

答:
You can download via nuget package manager.
Link for the nuget manager is https://www.nuget.org/packages/Microsoft.AspNet.SignalR.Client/2.1.2</p>


问:
Jest and Enzyme with React: Mock method with Translate
I am doing some unit tests for a project I'm working on, and I have the following Modal on React. Note that I usually pass t for translation, which I am attempting to do in the test but it's working:

```<code>import React, { Component } from 'react'
import { Modal, Button } from 'react-bootstrap'
import {translate} from 'react-polyglot'

class MessageModal extends Component {
  render () {
    const {messageModal: {message, isOpen}, closeMessageModal, t} = this.props
    return (
      <Modal show={isOpen}>
        <Modal.Body>
          {message ? t(`MESSAGE_MODAL.${message}`) : ''}
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={closeMessageModal}>Close</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default translate()(MessageModal)
</code>```

and the following test:

```<code>import React from 'react'
import MessageModal from './MessageModal'
import { shallow } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'
// import {translate} from 'react-polyglot'

describe('Testing MessageModal', () => {
  const tree = shallow(
    <MessageModal t={jest.fn()} messageModal={{message: 'message', isOpen: true}}/>
  )
  it('Renders correctly', () => {
    expect(shallowToJson(tree.dive().setProps({t: jest.fn()}))).toMatchSnapshot()
  })
})
</code>```

And I'm getting two main errors:
TypeError: t is not a function
and
Warning: Failed context type: The context `t` is marked as required in `_translate`, but its value is `undefined`.

I have tried everything to get this solved but I wasn't able to make it work. If you could help me that'd be great.

答:
What you could do is also exporting the not decorated MessageModal component.

```<code>import React, { Component } from 'react'
import { Modal, Button } from 'react-bootstrap'
import {translate} from 'react-polyglot'

export class MessageModal extends Component {
  render () {
    const {messageModal: {message, isOpen}, closeMessageModal, t} = this.props
    return (
      <Modal show={isOpen}>
        <Modal.Body>
          {message ? t(`MESSAGE_MODAL.${message}`) : ''}
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={closeMessageModal}>Close</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default translate()(MessageModal)
</code>```

This way you can import the not decorated component in your test so you don't have to deal with the higher order component part.

```<code>import { MessageModal } from './MessageModal'
</code>```

Body:
I am doing some unit tests for a project I'm working on, and I have the following Modal on React. Note that I usually pass t for translation, which I am attempting to do in the test but it's working:

import React, { Component } from 'react'
import { Modal, Button } from 'react-bootstrap'
import {translate} from 'react-polyglot'

class MessageModal extends Component {
  render () {
    const {messageModal: {message, isOpen}, closeMessageModal, t} = this.props
    return (
      <Modal show={isOpen}>
        <Modal.Body>
          {message ? t(`MESSAGE_MODAL.${message}`) : ''}
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={closeMessageModal}>Close</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default translate()(MessageModal)

and the following test:

import React from 'react'
import MessageModal from './MessageModal'
import { shallow } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'
// import {translate} from 'react-polyglot'

describe('Testing MessageModal', () => {
  const tree = shallow(
    <MessageModal t={jest.fn()} messageModal={{message: 'message', isOpen: true}}/>
  )
  it('Renders correctly', () => {
    expect(shallowToJson(tree.dive().setProps({t: jest.fn()}))).toMatchSnapshot()
  })
})

And I'm getting two main errors:
TypeError: t is not a function
and
Warning: Failed context type: The context `t` is marked as required in `_translate`, but its value is `undefined`.

I have tried everything to get this solved but I wasn't able to make it work. If you could help me that'd be great.

Body:
What you could do is also exporting the not decorated MessageModal component.

import React, { Component } from 'react'
import { Modal, Button } from 'react-bootstrap'
import {translate} from 'react-polyglot'

export class MessageModal extends Component {
  render () {
    const {messageModal: {message, isOpen}, closeMessageModal, t} = this.props
    return (
      <Modal show={isOpen}>
        <Modal.Body>
          {message ? t(`MESSAGE_MODAL.${message}`) : ''}
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={closeMessageModal}>Close</Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

export default translate()(MessageModal)

This way you can import the not decorated component in your test so you don't have to deal with the higher order component part.

import { MessageModal } from './MessageModal'


问:
Pure CSS tab containers active tab
I've got a problem. I have a pure CSS tab container. But when I click on a tab, it should become active in some way.

I already tried it with a <input type="radio" /> and a
But then the anchor  does not work anymore.

Any ideas?

JSFIDDLE

答:
Since you already using hash # you can use make use of the pseudo class :target.

To show how this works I added extra span to be able to target both the anchor a and the div.

The main 3 things that make this work is the span, the :target ~ ... and #tab1:target ~ ... rules.

Having the span placed before we can use the sibling selector to target 1 or more elements with only 1 hash.

With the :target ~ ... rule we reset the initilly showed tab and its content when a hash exist

Finally we use each #tab1:target ~ ... rule to mark the selected tab and show its content

Also see comment in CSS, which explain the steps used.

ul {
  margin: 0;
  padding: 0;
  width: 100%;
  display: inline-block;
}
ul li {
  list-style: none;
  float: left;
}
ul li a {
  color: #FFF;
  background: #333;
  display: block;
  padding: 10px;
  text-decoration: none;
}
.hideme {
  display: none;
}

.tabcontainer {
  width: 100%;
}
.tabcontainer .tab {
  position: absolute;
  display: none;
}

/* set the first link's background and show its div on page load */
ul li:first-child a,
.tab:first-child {
  background: #638DB2;
  display: block;
}

/* reset the first link's background and hide its div when a hash tag exist */
:target ~ ul [href="#tab1"] {
  background: black;
}
:target ~ .tabcontainer #tab1div {
  display: none;
}

/* set the hashed/targeted link's background and show its div */
#tab1:target ~ ul [href="#tab1"],
#tab1:target ~ .tabcontainer #tab1div {
  background: #638DB2;
  display: block;
}
#tab2:target ~ ul [href="#tab2"],
#tab2:target ~ .tabcontainer #tab2div {
  background: #FF4C43;
  display: block;
}
#tab3:target ~ ul [href="#tab3"],
#tab3:target ~ .tabcontainer #tab3div {
  background: #C1CC14;
  display: block;
}
#tab4:target ~ ul [href="#tab4"],
#tab4:target ~ .tabcontainer #tab4div {
  background: #ADB257;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="tab1" class="hideme"></span>
<span id="tab2" class="hideme"></span>
<span id="tab3" class="hideme"></span>
<span id="tab4" class="hideme"></span>
<ul>
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
  <li>Tab 4</li>
</ul>
<div class="tabcontainer">
  <div id="tab1div" class="tab">
    1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab2div" class="tab">
    2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab3div" class="tab">
    3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab4div" class="tab">
    4 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div></code>```

Title: Pure CSS tab containers active tab

Body:
Since you already using hash # you can use make use of the pseudo class :target.

To show how this works I added extra span to be able to target both the anchor a and the div.

The main 3 things that make this work is the span, the :target ~ ... and #tab1:target ~ ... rules.

Having the span placed before we can use the sibling selector to target 1 or more elements with only 1 hash.

With the :target ~ ... rule we reset the initilly showed tab and its content when a hash exist

Finally we use each #tab1:target ~ ... rule to mark the selected tab and show its content

Also see comment in CSS, which explain the steps used.

ul {
  margin: 0;
  padding: 0;
  width: 100%;
  display: inline-block;
}
ul li {
  list-style: none;
  float: left;
}
ul li a {
  color: #FFF;
  background: #333;
  display: block;
  padding: 10px;
  text-decoration: none;
}
.hideme {
  display: none;
}

.tabcontainer {
  width: 100%;
}
.tabcontainer .tab {
  position: absolute;
  display: none;
}

/* set the first link's background and show its div on page load */
ul li:first-child a,
.tab:first-child {
  background: #638DB2;
  display: block;
}

/* reset the first link's background and hide its div when a hash tag exist */
:target ~ ul [href="#tab1"] {
  background: black;
}
:target ~ .tabcontainer #tab1div {
  display: none;
}

/* set the hashed/targeted link's background and show its div */
#tab1:target ~ ul [href="#tab1"],
#tab1:target ~ .tabcontainer #tab1div {
  background: #638DB2;
  display: block;
}
#tab2:target ~ ul [href="#tab2"],
#tab2:target ~ .tabcontainer #tab2div {
  background: #FF4C43;
  display: block;
}
#tab3:target ~ ul [href="#tab3"],
#tab3:target ~ .tabcontainer #tab3div {
  background: #C1CC14;
  display: block;
}
#tab4:target ~ ul [href="#tab4"],
#tab4:target ~ .tabcontainer #tab4div {
  background: #ADB257;
  display: block;
}

<span id="tab1" class="hideme"></span>
<span id="tab2" class="hideme"></span>
<span id="tab3" class="hideme"></span>
<span id="tab4" class="hideme"></span>
<ul>
  <li><a href="#tab1">Tab 1</a></li>
  <li><a href="#tab2">Tab 2</a></li>
  <li><a href="#tab3">Tab 3</a></li>
  <li><a href="#tab4">Tab 4</a></li>
</ul>
<div class="tabcontainer">
  <div id="tab1div" class="tab">
    1 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab2div" class="tab">
    2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab3div" class="tab">
    3 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
  <div id="tab4div" class="tab">
    4 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div>