问:
Passing txtBox values between forms
I have always had trouble with this issue, i think i need to learn how it works, i have FormMain (my main form) and a second form (FormAddUrls) when i open form2 (FormAddUrls) i want to pass the multitextbox value back to the main form (FormMain)

I know in VB it's as simple as saying: FormMain.txtBoxUrls.Text = finalOutput; but not as easy in C#.

(form1) - FormMain

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using WraithProjectCreator;
using IronPdf;
using System.Text;

namespace GSAProjectCreator
{
    public partial class FormMain : Form
    {
        private IniParser m_Parser = null;

        public FormMain()
        {
            InitializeComponent();
        }

        private void btnShowUrlsForm_Click(object sender, EventArgs e)
        {
            FormAddUrls fau = new FormAddUrls();
            fau.Show();
        }

     }
}
</code>```

(form2) - FormAddUrls

```<code>using GSAProjectCreator;
using System;
using System.Text;
using System.Windows.Forms;

namespace WraithProjectCreator
{
    public partial class FormAddUrls : Form
    {
        public FormAddUrls()
        {
            InitializeComponent();
        }

        private void btnAddUrls_Click(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            foreach (string line in txtBoxURLsMass.Lines)
            {
                //Helpers.returnMessage(line);
                builder.Append(line + "|");
            }
            builder.Append("}");
            string finalOutput = "";
            if (builder.ToString().Contains("|}")) {
                finalOutput = builder.ToString().Replace("|}", "}");
            }
            //FormMain.txtBoxUrls.Text = finalOutput;
            this.Close();
        }

    }
}
</code>```

I have ommited a lot of form1's code to leave the basic structure, i'm trying to pass back finalOutput from form2 to form1 (the txtBoxUrls.Text) text box, any help would be appreciated.

答:
It depends on how you want to use the main form - you could have a static property which you could set (which would update the text for all main form instances).

If you only have one main form, and have a reference to it when you create the FormAddUrls object then you should just change the constructor to accept a MainForm (or as generic a type as possible), store the reference as a field and update the property on it when the button is clicked:

```<code> public partial class FormAddUrls : Form
 {
     private readonly Form _parentForm;
     public FormAddUrls(MainForm parent)
     {
         _parentForm = parent;
         InitializeComponent();
     }

     private void btnAddUrls_Click(object sender, EventArgs e)
     {
         StringBuilder builder = new StringBuilder();
         builder.Append("{");
         foreach (string line in txtBoxURLsMass.Lines)
         {
             //Helpers.returnMessage(line);
             builder.Append(line + "|");
         }
         builder.Append("}");
         string finalOutput = "";
         if (builder.ToString().Contains("|}")) {
             finalOutput = builder.ToString().Replace("|}", "}");
         }
         if(_parentForm != null)
             _parentForm.txtBoxUrls.Text = finalOutput;
         this.Close();
     }

 }
</code>```

Title: Passing txtBox values between forms

Body:
I have always had trouble with this issue, i think i need to learn how it works, i have FormMain (my main form) and a second form (FormAddUrls) when i open form2 (FormAddUrls) i want to pass the multitextbox value back to the main form (FormMain)

I know in VB it's as simple as saying: FormMain.txtBoxUrls.Text = finalOutput; but not as easy in C#.

(form1) - FormMain

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using WraithProjectCreator;
using IronPdf;
using System.Text;

namespace GSAProjectCreator
{
    public partial class FormMain : Form
    {
        private IniParser m_Parser = null;

        public FormMain()
        {
            InitializeComponent();
        }

        private void btnShowUrlsForm_Click(object sender, EventArgs e)
        {
            FormAddUrls fau = new FormAddUrls();
            fau.Show();
        }

     }
}

(form2) - FormAddUrls

using GSAProjectCreator;
using System;
using System.Text;
using System.Windows.Forms;

namespace WraithProjectCreator
{
    public partial class FormAddUrls : Form
    {
        public FormAddUrls()
        {
            InitializeComponent();
        }

        private void btnAddUrls_Click(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("{");
            foreach (string line in txtBoxURLsMass.Lines)
            {
                //Helpers.returnMessage(line);
                builder.Append(line + "|");
            }
            builder.Append("}");
            string finalOutput = "";
            if (builder.ToString().Contains("|}")) {
                finalOutput = builder.ToString().Replace("|}", "}");
            }
            //FormMain.txtBoxUrls.Text = finalOutput;
            this.Close();
        }

    }
}

I have ommited a lot of form1's code to leave the basic structure, i'm trying to pass back finalOutput from form2 to form1 (the txtBoxUrls.Text) text box, any help would be appreciated.

Body:
It depends on how you want to use the main form - you could have a static property which you could set (which would update the text for all main form instances).

If you only have one main form, and have a reference to it when you create the FormAddUrls object then you should just change the constructor to accept a MainForm (or as generic a type as possible), store the reference as a field and update the property on it when the button is clicked:

 public partial class FormAddUrls : Form
 {
     private readonly Form _parentForm;
     public FormAddUrls(MainForm parent)
     {
         _parentForm = parent;
         InitializeComponent();
     }

     private void btnAddUrls_Click(object sender, EventArgs e)
     {
         StringBuilder builder = new StringBuilder();
         builder.Append("{");
         foreach (string line in txtBoxURLsMass.Lines)
         {
             //Helpers.returnMessage(line);
             builder.Append(line + "|");
         }
         builder.Append("}");
         string finalOutput = "";
         if (builder.ToString().Contains("|}")) {
             finalOutput = builder.ToString().Replace("|}", "}");
         }
         if(_parentForm != null)
             _parentForm.txtBoxUrls.Text = finalOutput;
         this.Close();
     }

 }


来源: stackexchange

问:
Is it safe to send credit card details securely over http POST using swift?
The API that I'm using requires me to send Credit Card Details to complete payment through a HTTP POST request (through swift). Is this safe by any means? And moreover, how do I securely store credit card information for repeated payments?

The credit card holder's name, credit card number, cvc, and date of expiry are all sent over a POST request. Then, the API returns whether the payment was successful, and the last four digits of the credit card number.

Simply put, I'm not entirely familiar with payment security, and would like to know if this is safe, and moreover how to save payment information securely using swift, even if that's possible. I don't think I can use stripe for this process, but I would love to know if that's possible as well.

EDIT:
I have confirmed that the API I'm using does in fact employ an HTTPS connection, and not simply a HTTP server. At this point, I know not to save credit card information locally and that I should retrieve it from a third party service before handling it. Thanks All!

答:
Just append a 's' with your http then it's permissible. http is insecure as already mentioned by @t0mm13b. So it's not safe.

there is a Nice post.

Edited:

Don't be just happy that appending 's' is sufficient though. :)

ContentLicense: CC BY-SA 3.0


问:
How to add even on ActionBarDrawerToggle?
Here is my program, but if I click nav_exit, my program is exiting. It isn't working as it should when I click. Help me please.

1.navigation_menu.xml

```<code><group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_exit"

        android:title="EXIT" />
    <item
        android:id="@+id/nav_gallery"

        android:title="gallery" />

</group>

<item android:title="ssssssss">
    <menu>
        <item
            android:id="@+id/nav_share"

            android:title="share" />
        <item
            android:id="@+id/nav_se2nd"

            android:title="se2nd" />
        <item
            android:id="@+id/nav_send"

            android:title="send" />
    </menu>
</item>
</code>```

2.MainActivity  is not working on click menu.

```<code>package info.mt_online.www.myapplicationv1;
import android.content.Intent;
import android.provider.Settings;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
           int id = item.getItemId();
           if (id == R.id.nav_exit) {
               finish();
               System.exit(0);
               return true;
           }
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

It is not working. Can you please tell me why?

答:
I guess you are trying to exit app using NavigationView menu Item. To do this, you have to implement NavigationItemSelectedListener and in method onNavigationItemSelected() check your desired nav_exit and exit from the application by calling finish().

Add below code in your MainActivity inside onCrate() method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {

    ...........
    .................

    // NavigationView
    NavigationView mNavigationView = (NavigationView) findViewById(R.id.your_navigation_view);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {

            int id = item.getItemId();
            if (id == R.id.nav_exit) {
               finish();
            }

            return true;
        }
    });

}
</code>```

FYI, onOptionsItemSelected() is used for handling Toolbar option MenuItems click events.

Body:
Here is my program, but if I click nav_exit, my program is exiting. It isn't working as it should when I click. Help me please.

1.navigation_menu.xml

<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_exit"

        android:title="EXIT" />
    <item
        android:id="@+id/nav_gallery"

        android:title="gallery" />

</group>

<item android:title="ssssssss">
    <menu>
        <item
            android:id="@+id/nav_share"

            android:title="share" />
        <item
            android:id="@+id/nav_se2nd"

            android:title="se2nd" />
        <item
            android:id="@+id/nav_send"

            android:title="send" />
    </menu>
</item>

2.MainActivity  is not working on click menu.

package info.mt_online.www.myapplicationv1;
import android.content.Intent;
import android.provider.Settings;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawerLayout= (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mToggle.onOptionsItemSelected(item)){
           int id = item.getItemId();
           if (id == R.id.nav_exit) {
               finish();
               System.exit(0);
               return true;
           }
        }
        return super.onOptionsItemSelected(item);
    }
}

It is not working. Can you please tell me why?

Body:
I guess you are trying to exit app using NavigationView menu Item. To do this, you have to implement NavigationItemSelectedListener and in method onNavigationItemSelected() check your desired nav_exit and exit from the application by calling finish().

Add below code in your MainActivity inside onCrate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...........
    .................

    // NavigationView
    NavigationView mNavigationView = (NavigationView) findViewById(R.id.your_navigation_view);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {

            int id = item.getItemId();
            if (id == R.id.nav_exit) {
               finish();
            }

            return true;
        }
    });

}

FYI, onOptionsItemSelected() is used for handling Toolbar option MenuItems click events.


问:
angular 2 deploy on github
How to deploy angular 2 website application on github? I am new to Git and github so just saw the basics on internet and created a repository on github and finally a url was generated in my git bash after running all steps and when I tried to open it Github 404 error pages was showing.

These are the commands which I ran through :

```<code>git remote add origin https://github.com/Muraliduke/MuraliDukeResume.git

git push -u origin master

ng github-pages:deploy
</code>```

Is there any difficulty for single page application to host a website on github? I tried with normal html content and my website on github works fine. But this with ng2 is not working. Just saw on internet that there must be some prefix to be done to support SPA on github but since I am not familiar with github didn't understand it. So kindly suggest me a solution ?

答:
There are a few things :

Deploying to GitHub pages using Angular CLI has been deprecated. Use angular-cli-ghpages

Add the 404.html fix

Ensure you have "turned on" GitHub pages for your gh-pages branch from the repository settings

optionally, add custom domain

This blog has everything you need.

Title: angular 2 deploy on github

Body:
How to deploy angular 2 website application on github? I am new to Git and github so just saw the basics on internet and created a repository on github and finally a url was generated in my git bash after running all steps and when I tried to open it Github 404 error pages was showing.

These are the commands which I ran through :

git remote add origin https://github.com/Muraliduke/MuraliDukeResume.git

git push -u origin master

ng github-pages:deploy

Is there any difficulty for single page application to host a website on github? I tried with normal html content and my website on github works fine. But this with ng2 is not working. Just saw on internet that there must be some prefix to be done to support SPA on github but since I am not familiar with github didn't understand it. So kindly suggest me a solution ?


问:
Strange error with cuda::reprojectImageTo3D and OpenCV 3.0
Hello I am trying to get a Mat with the XYZ cordenates from a disparity map that i have already generated with a cuda::StereoBM object, this is a screenshot of the disparity map I created "disparity map"
but when I add the function cuda::reprojectImageTo3D(d_disp,d_xyz,d_Q,3,Stream); I get an error I can't understand, if I coment this line of code no error is shown but the moment I try to use this function I get the next error window

and the error code is:

OpenCV Error: The function/feature is not implemented (You should explicitly call download method for cuda::GpuMat object) in cv::_InputArray::getMat_, file C:\opencv\sources\modules\core\src\matrix.cpp, line 1211

bellow is my code, note that most of my Mats are declared as global , so their declarations are not in this slot function

```<code>void MainWindow::on_botonMostrarDispSGBMCUDA_clicked()
{

    if(map_l1.empty()&&map_l2.empty()&&map_r1.empty() &&map_r2.empty()){
        FileStorage fs(xmlname,FileStorage::READ);
        fs["map_l1"]>>map_l1;
        fs["map_l2"]>>map_l2;
        fs["map_r1"]>>map_r1;
        fs["map_r2"]>>map_r2;
        fs["Q"] >> Q;
        fs.release();
    }
    Mat img1, img2;
    img1 = imread("C:\\Users\\Diego\\Pictures\\calibstereo\\camleft\\photoleft_1.jpg");
    img2 = imread("C:\\Users\\Diego\\Pictures\\calibstereo\\camright\\photoright_1.jpg");

    cvtColor(img1, frameLGray, CV_BGR2GRAY);
    cvtColor(img2, frameRGray, CV_BGR2GRAY);
    remap(frameLGray,framel_rect,map_l1,map_l2,INTER_LINEAR);
    remap(frameRGray,framer_rect,map_r1,map_r2,INTER_LINEAR);

    bool ok1, ok2, ok3, ok4, ok5, ok6 , ok7,ok8,ok9,ok10 ;
    int preFilterSize = ui->editPrefilterSizeBM->text().toInt(&ok1);
    int prefilterCap = ui->editFilterCapBM->text().toInt(&ok2);
    int blockSize = ui->editBlockSBM->text().toInt(&ok3);
    int minDisp = ui->editMinDispBM->text().toInt(&ok4);
    int numDisp = ui->editNumDispBM->text().toInt(&ok5);
    int texturethresh = ui->editTextureBM->text().toInt(&ok6);
    int uniqueness = ui->editUniquenesBM->text().toInt(&ok7);
    int speckleWindow = ui->editSpeckleWindowBM->text().toInt(&ok8);
    int speckleRange = ui->editSpeckleRangeBM->text().toInt(&ok9);
    int maxDiff = ui->editMaxDiffBM->text().toInt(&ok10);

    if (!ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || !ok9 || !ok10){
        QMessageBox messageBox;
        messageBox.setIconPixmap(QPixmap(":/icon.svg"));
        messageBox.setText("One of your entries is not a valid number.");
        messageBox.setWindowTitle("Error");
        messageBox.exec();
     }

    d_left.upload(framel_rect);
    d_right.upload(framer_rect);
    Ptr<cuda::StereoBM> CUSBM;
    CUSBM = cuda::createStereoBM(64, 5);
    CUSBM->setPreFilterSize(preFilterSize);
    CUSBM->setPreFilterCap(prefilterCap);
    CUSBM->setBlockSize(blockSize);
    CUSBM->setMinDisparity(minDisp);
    CUSBM->setNumDisparities(numDisp);
    CUSBM->setTextureThreshold(texturethresh);
    CUSBM->setUniquenessRatio(uniqueness);
    CUSBM->setSpeckleWindowSize(speckleWindow);
    CUSBM->setSpeckleRange(speckleRange);
    CUSBM->setDisp12MaxDiff(maxDiff);
    cuda::Stream myStream = cuda::Stream::Stream();
    CUSBM->compute(d_left, d_right, d_disp, myStream);
    if(!d_disp.empty()){
        cuda::GpuMat d_xyz(d_disp.size(), CV_32FC4);
        cuda::GpuMat d_Q(4,4,CV_32F);
        d_Q.upload(Q);
        cuda::Stream mySecondStream = cuda::Stream::Stream();
        cuda::reprojectImageTo3D(d_disp,d_xyz,d_Q,3,mySecondStream);
        d_xyz.download(xyz);
    }

    cuda::drawColorDisp(d_disp, d_disp,numDisp);        //64

    d_disp.download(disp);

    namedWindow("left");
    namedWindow("right");
    namedWindow("disp");

    imshow("left", framel_rect);
    imshow("right", framer_rect);
    imshow("disp", disp);
    //imshow("xyz", xyz);
    waitKey(0);
    cv::destroyAllWindows();
}
</code>```

I am using Windows 8.1, QtCreator as my IDE, OpenCV 3.0.0 with cuda 7.0

答: The problem lies in cuda::drawColorDisp(d_disp, d_disp,numDisp);        //64. You are supplying same source and destination GpuMat files, which should not be the case. You may like to have a look here for the detailed constructor arguments for drawColorDisp.

Body:
Hello I am trying to get a Mat with the XYZ cordenates from a disparity map that i have already generated with a cuda::StereoBM object, this is a screenshot of the disparity map I created "disparity map"
but when I add the function cuda::reprojectImageTo3D(d_disp,d_xyz,d_Q,3,Stream); I get an error I can't understand, if I coment this line of code no error is shown but the moment I try to use this function I get the next error window

and the error code is:

OpenCV Error: The function/feature is not implemented (You should explicitly call download method for cuda::GpuMat object) in cv::_InputArray::getMat_, file C:\opencv\sources\modules\core\src\matrix.cpp, line 1211

bellow is my code, note that most of my Mats are declared as global , so their declarations are not in this slot function

void MainWindow::on_botonMostrarDispSGBMCUDA_clicked()
{

    if(map_l1.empty()&&map_l2.empty()&&map_r1.empty() &&map_r2.empty()){
        FileStorage fs(xmlname,FileStorage::READ);
        fs["map_l1"]>>map_l1;
        fs["map_l2"]>>map_l2;
        fs["map_r1"]>>map_r1;
        fs["map_r2"]>>map_r2;
        fs["Q"] >> Q;
        fs.release();
    }
    Mat img1, img2;
    img1 = imread("C:\\Users\\Diego\\Pictures\\calibstereo\\camleft\\photoleft_1.jpg");
    img2 = imread("C:\\Users\\Diego\\Pictures\\calibstereo\\camright\\photoright_1.jpg");

    cvtColor(img1, frameLGray, CV_BGR2GRAY);
    cvtColor(img2, frameRGray, CV_BGR2GRAY);
    remap(frameLGray,framel_rect,map_l1,map_l2,INTER_LINEAR);
    remap(frameRGray,framer_rect,map_r1,map_r2,INTER_LINEAR);

    bool ok1, ok2, ok3, ok4, ok5, ok6 , ok7,ok8,ok9,ok10 ;
    int preFilterSize = ui->editPrefilterSizeBM->text().toInt(&ok1);
    int prefilterCap = ui->editFilterCapBM->text().toInt(&ok2);
    int blockSize = ui->editBlockSBM->text().toInt(&ok3);
    int minDisp = ui->editMinDispBM->text().toInt(&ok4);
    int numDisp = ui->editNumDispBM->text().toInt(&ok5);
    int texturethresh = ui->editTextureBM->text().toInt(&ok6);
    int uniqueness = ui->editUniquenesBM->text().toInt(&ok7);
    int speckleWindow = ui->editSpeckleWindowBM->text().toInt(&ok8);
    int speckleRange = ui->editSpeckleRangeBM->text().toInt(&ok9);
    int maxDiff = ui->editMaxDiffBM->text().toInt(&ok10);

    if (!ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || !ok9 || !ok10){
        QMessageBox messageBox;
        messageBox.setIconPixmap(QPixmap(":/icon.svg"));
        messageBox.setText("One of your entries is not a valid number.");
        messageBox.setWindowTitle("Error");
        messageBox.exec();
     }

    d_left.upload(framel_rect);
    d_right.upload(framer_rect);
    Ptr<cuda::StereoBM> CUSBM;
    CUSBM = cuda::createStereoBM(64, 5);
    CUSBM->setPreFilterSize(preFilterSize);
    CUSBM->setPreFilterCap(prefilterCap);
    CUSBM->setBlockSize(blockSize);
    CUSBM->setMinDisparity(minDisp);
    CUSBM->setNumDisparities(numDisp);
    CUSBM->setTextureThreshold(texturethresh);
    CUSBM->setUniquenessRatio(uniqueness);
    CUSBM->setSpeckleWindowSize(speckleWindow);
    CUSBM->setSpeckleRange(speckleRange);
    CUSBM->setDisp12MaxDiff(maxDiff);
    cuda::Stream myStream = cuda::Stream::Stream();
    CUSBM->compute(d_left, d_right, d_disp, myStream);
    if(!d_disp.empty()){
        cuda::GpuMat d_xyz(d_disp.size(), CV_32FC4);
        cuda::GpuMat d_Q(4,4,CV_32F);
        d_Q.upload(Q);
        cuda::Stream mySecondStream = cuda::Stream::Stream();
        cuda::reprojectImageTo3D(d_disp,d_xyz,d_Q,3,mySecondStream);
        d_xyz.download(xyz);
    }

    cuda::drawColorDisp(d_disp, d_disp,numDisp);        //64

    d_disp.download(disp);

    namedWindow("left");
    namedWindow("right");
    namedWindow("disp");

    imshow("left", framel_rect);
    imshow("right", framer_rect);
    imshow("disp", disp);
    //imshow("xyz", xyz);
    waitKey(0);
    cv::destroyAllWindows();
}

I am using Windows 8.1, QtCreator as my IDE, OpenCV 3.0.0 with cuda 7.0


问:
Construct generic class of concrete class from interface
I have a WCF service which accepts any entity which implements an interface. When it receives one of these entities I would like to publish an event i.e.

```<code>public void Receive(IFruit fruit)
{
      messageHub.Publish(new FruitReceived<IFruit>(fruit));
}
</code>```

However I would like to reify the interface so instead of everything that handles fruit subscribing to the event FruitReceived<IFruit> they can subscribe to only the type they're interested in such as FruitReceived<Apple>.

Currently I can do this through some lengthy reflection:

```<code>var fruitType = fruit.GetType();
var evt = typeof(FruitReceived<>)
    .MakeGenericType(fruitType)
    .GetConstructor(fruitType)
    .Invoke(fruit);
</code>```

This is a bit of a performance hit (even with caching the constructors) and also hard to read.

I was hoping that there's a simpler way to achieve this? I have spent so much time thinking about this solution that it's the only one I can come up with.

For reference the publish method simplifies to something like this:

```<code>public void Publish<TEvent>(TEvent evt)
{
    if(_subscriptions.ContainsKey(typeof(TEvent))
    {
        IEnumerable<IEventHandler<TEvent>> handlers = _subscriptions[typeof(TEvent)];

        foreach(var handler in handlers)
        {
            handler.HandleEvent(evt);
        }
    }
}
</code>```

答:
This can usually be solved with the visitor pattern. But it requires some extensive changes, starting with IFruit:

```<code>interface IFruitVisitor {
    void Visit(Apple apple);
    void Visit(Banana banana);
    // ... you need a method for each fruit
}

interface IFruit {
    Accept(IFruitVisitor visitor);
}
</code>```

Then your fruits must implement that method:

```<code>class Apple : IFruit {
    public void Accept(IFruitVisitor visitor) => visitor.Visit(this);
}
class Banana : IFruit {
    public void Accept(IFruitVisitor visitor) => visitor.Visit(this);
}
</code>```

And you can have a special visitor for your case:

```<code>class CreateFruitReceivedFruitVisitor : IFruitVisitor {
    public object FruitReceived { get; private set; }
    public void Visit(Banana banana) => FruitReceived = new FruitReceived<Banana>(banana);
    public void Visit(Apple apple) => FruitReceived = new FruitReceived<Apple>(apple);
}
</code>```

Then, just use it in your original method:

```<code>public void Receive(IFruit fruit)
{
    var visitor = new CreateFruitReceivedFruitVisitor();
    fruit.Accept(visitor);
    messageHub.Publish(visitor.FruitReceived);
}
</code>```

You need to weight in the benefits and costs of this solution. Even though it can be faster than the reflection version you showed, I believe it's much more unwieldy.

Body:
I have a WCF service which accepts any entity which implements an interface. When it receives one of these entities I would like to publish an event i.e.

public void Receive(IFruit fruit)
{
      messageHub.Publish(new FruitReceived<IFruit>(fruit));
}

However I would like to reify the interface so instead of everything that handles fruit subscribing to the event FruitReceived<IFruit> they can subscribe to only the type they're interested in such as FruitReceived<Apple>.

Currently I can do this through some lengthy reflection:

var fruitType = fruit.GetType();
var evt = typeof(FruitReceived<>)
    .MakeGenericType(fruitType)
    .GetConstructor(fruitType)
    .Invoke(fruit);

This is a bit of a performance hit (even with caching the constructors) and also hard to read.

I was hoping that there's a simpler way to achieve this? I have spent so much time thinking about this solution that it's the only one I can come up with.

For reference the publish method simplifies to something like this:

public void Publish<TEvent>(TEvent evt)
{
    if(_subscriptions.ContainsKey(typeof(TEvent))
    {
        IEnumerable<IEventHandler<TEvent>> handlers = _subscriptions[typeof(TEvent)];

        foreach(var handler in handlers)
        {
            handler.HandleEvent(evt);
        }
    }
}

Body:
This can usually be solved with the visitor pattern. But it requires some extensive changes, starting with IFruit:

interface IFruitVisitor {
    void Visit(Apple apple);
    void Visit(Banana banana);
    // ... you need a method for each fruit
}

interface IFruit {
    Accept(IFruitVisitor visitor);
}

Then your fruits must implement that method:

class Apple : IFruit {
    public void Accept(IFruitVisitor visitor) => visitor.Visit(this);
}
class Banana : IFruit {
    public void Accept(IFruitVisitor visitor) => visitor.Visit(this);
}

And you can have a special visitor for your case:

class CreateFruitReceivedFruitVisitor : IFruitVisitor {
    public object FruitReceived { get; private set; }
    public void Visit(Banana banana) => FruitReceived = new FruitReceived<Banana>(banana);
    public void Visit(Apple apple) => FruitReceived = new FruitReceived<Apple>(apple);
}

Then, just use it in your original method:

public void Receive(IFruit fruit)
{
    var visitor = new CreateFruitReceivedFruitVisitor();
    fruit.Accept(visitor);
    messageHub.Publish(visitor.FruitReceived);
}

You need to weight in the benefits and costs of this solution. Even though it can be faster than the reflection version you showed, I believe it's much more unwieldy.


问:
How do I remove the dots in LineChartView iOS charts
I'm learning ios-charts. I was using the tutorial found here. The first picture shows the result I am getting. How do you remove the blue circle dots so that it only shows a smooth line like what is shown in the second picture?

Here is snippet of the code

```<code>import UIKit
import Charts

class ChartsViewController: UIViewController {

@IBOutlet weak var lineChartView: LineChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]

    setChart(months, values: unitsSold)

}

func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
    }

    let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold")
    let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
    lineChartView.data = lineChartData

}

}
</code>```

答:
```<code>lineChartDataSet.circleRadius = 0
</code>```

Body:
I'm learning ios-charts. I was using the tutorial found here. The first picture shows the result I am getting. How do you remove the blue circle dots so that it only shows a smooth line like what is shown in the second picture?

Here is snippet of the code

import UIKit
import Charts

class ChartsViewController: UIViewController {

@IBOutlet weak var lineChartView: LineChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]

    setChart(months, values: unitsSold)

}

func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
    }

    let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold")
    let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
    lineChartView.data = lineChartData

}

}

Body: lineChartDataSet.circleRadius = 0


问:
Setting private key in certificate hangs windows service
I have application and I have to use a certificate which requires a pin from prompt window.

I have following code.

```<code>SecureString password = GetPassword();
X509Certificate2 certificate = GetCertificate();

var cspParameters = new CspParameters(1,
                                     "ProviderName",
                                     "KeyContainerName",
                                     null,
                                     password);

certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);
</code>```

Everything works fine in console application but when I run that code in windows service or console application started from task scheduler then application freezes on that line.

```<code>certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);
</code>```

No exceptions, no progress.

I'm running windows service with the same credentials as an application.

Windows 10 / Windows Server 2012

Do you have any ideas what is wrong?

答:
Ok, after a break I have found solution.

I had to add impersonation around this line:

```<code>certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);
</code>```

I used the same credentials like in my service and set LogonType as Interactive.

Body:
I have application and I have to use a certificate which requires a pin from prompt window.

I have following code.

SecureString password = GetPassword();
X509Certificate2 certificate = GetCertificate();

var cspParameters = new CspParameters(1,
                                     "ProviderName",
                                     "KeyContainerName",
                                     null,
                                     password);

certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);

Everything works fine in console application but when I run that code in windows service or console application started from task scheduler then application freezes on that line.

certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);

No exceptions, no progress.

I'm running windows service with the same credentials as an application.

Windows 10 / Windows Server 2012

Do you have any ideas what is wrong?

Body:
Ok, after a break I have found solution.

I had to add impersonation around this line:

certificate.PrivateKey = new RSACryptoServiceProvider(cspParameters);

I used the same credentials like in my service and set LogonType as Interactive.


问:
Pandas DataFrame: when using read_csv, rows with blanks are converting entire column to "object" data type
I have a CSV file that looks as follows:

```<code>name,id,weight
a,12345,196.5
b,83748,
 ,83748,200.0
c, ,155.5
</code>```

Note, there are several missing values indicated by a single space.

When I load this CSV file into a Pandas DataFrame and check the data types using dtypes, it says that every column is of type "object". Even after I convert the spaces to NaN, it still says everything is an "object".

How do I get the data types to be read in correctly, despite the spaces? Could this possibly be an issue with the Anaconda platform?

答: When you call read_csv(), make sure you call it with na_values=' ' (or whatever your NaN values actually are).

Body:
I have a CSV file that looks as follows:

name,id,weight
a,12345,196.5
b,83748,
 ,83748,200.0
c, ,155.5

Note, there are several missing values indicated by a single space.

When I load this CSV file into a Pandas DataFrame and check the data types using dtypes, it says that every column is of type "object". Even after I convert the spaces to NaN, it still says everything is an "object".

How do I get the data types to be read in correctly, despite the spaces? Could this possibly be an issue with the Anaconda platform?


问:
How can I properly bind a React component class's event handlers when converting from createClass to the class keyword?
I'm in the midst of preparing our React components for an upgrade to React 16 with the crux of that process being an update of components that use with React.createClass to use the class keyword instead.

I'm running into trouble when it comes to event handlers that invoke class methods as I keep seeing the Can only update a mounted or mounting component error.

A trivial example...

Original component using React.createClass:

```<code>const Foo = React.createClass({
  getInitialState() {
    return { bar: false };
  },

  onClick() {
    this.setState({ bar: !this.state.bar });
  },

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={this.onClick}>CLICK IT</button>
      </div>
    );
  },
});
</code>```

That works as expected. So does this if I'm willing to ignore that a new function object will be created with each call to render:

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={() => { this.setState({ bar: !this.state.bar }); }}>CLICK IT</button>
      </div>
    );
  }
}
</code>```

However, I can't get the "bind in the constructor" approach to work:

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };

    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={this.onClick}>CLICK IT</button>
      </div>
    );
  }
}
</code>```

Nor can I get the property initializer syntax approach to work:

```<code>class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  onClick = () => {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (
      <div>
        <p>{this.state.bar ? 'YAY' : 'BOO'}</p>
        <button onClick={this.onClick}>CLICK IT</button>
      </div>
    );
  }
}
</code>```

In both of those cases, whenever I click the button the aforementioned error message shows up in the browser console.

I'm hoping someone has encountered this problem themselves already and has advice on how to deal with it. I imagine that it's just something trivial that I'm completely overlooking. :)

Thanks in advance!

答:
Take a look at React Documentation: They have the same example.  BTW your bind example works for me: post your error message.</p>

```<code> class Toggle extends React.Component {
   constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
   }

   handleClick() {
     this.setState(prevState => ({
       isToggleOn: !prevState.isToggleOn
     }));
   }

   render() {
      return (
         <button onClick={this.handleClick}>
            {this.state.isToggleOn ? 'ON' : 'OFF'}
         </button>
      );
    }
  }

  ReactDOM.render(
    <Toggle />,
    document.getElementById('root')
  );
</code>```

Body:
I'm in the midst of preparing our React components for an upgrade to React 16 with the crux of that process being an update of components that use with React.createClass to use the class keyword instead.

I'm running into trouble when it comes to event handlers that invoke class methods as I keep seeing the Can only update a mounted or mounting component error.

A trivial example...

Original component using React.createClass:

const Foo = React.createClass({
  getInitialState() {
    return { bar: false };
  },

  onClick() {
    this.setState({ bar: !this.state.bar });
  },

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={this.onClick}>CLICK IT</button>

    );
  },
});

That works as expected. So does this if I'm willing to ignore that a new function object will be created with each call to render:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={() => { this.setState({ bar: !this.state.bar }); }}>CLICK IT</button>

    );
  }
}

However, I can't get the "bind in the constructor" approach to work:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };

    this.onClick = this.onClick.bind(this);
  }

  onClick() {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={this.onClick}>CLICK IT</button>

    );
  }
}

Nor can I get the property initializer syntax approach to work:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = { bar: false };
  }

  onClick = () => {
    this.setState({ bar: !this.state.bar });
  }

  render() {
    return (

{this.state.bar ? 'YAY' : 'BOO'}

        <button onClick={this.onClick}>CLICK IT</button>

    );
  }
}

In both of those cases, whenever I click the button the aforementioned error message shows up in the browser console.

I'm hoping someone has encountered this problem themselves already and has advice on how to deal with it. I imagine that it's just something trivial that I'm completely overlooking. :)

Thanks in advance!

Body:
Take a look at React Documentation: They have the same example.  BTW your bind example works for me: post your error message.

 class Toggle extends React.Component {
   constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
   }

   handleClick() {
     this.setState(prevState => ({
       isToggleOn: !prevState.isToggleOn
     }));
   }

   render() {
      return (
         <button onClick={this.handleClick}>
            {this.state.isToggleOn ? 'ON' : 'OFF'}
         </button>
      );
    }
  }

  ReactDOM.render(
    <Toggle />,
    document.getElementById('root')
  );


问:
Match a string between two characters regex
I need to use new RegExp
I need to get a match if there is a specific string between two characters, but no match if that is a similar string between those characters, / and ?.
I.e:

String to match is:

"https://www.mysite.se/should-match?ba=11"

And I have should-ma

That should not give any match. But should-match should give a match
So I need to create new RegExp()

Any ideas?

答:
Try this:

```<code>(?!\/)[^\/\?]*(?=\?)
</code>```

(test it out)

Replace \/ with the start delimiter and \? with the end delimiter. If the start or end delimiters have any of .?*+^$[]\(){}|- in them, you will need to add a \ before them, or use this function to do the work for you:

```<code>var escape = function(str) {
    return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
</code>```

Alternative:

```<code>var matcher = function(str, start, end){
    var quote = function(str) {
        return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
    };
    return str.match(new RegExp(quote(start) + "[^" + quote(start) + quote(end) + "]*" + quote(end)))[0].slice(1, -1)
};
</code>```

Use like matcher("https://www.mysite.se/should-match?ba=11", "/", "?").

Body:
Try this:

(?!\/)[^\/\?]*(?=\?)

(test it out)

Replace \/ with the start delimiter and \? with the end delimiter. If the start or end delimiters have any of .?*+^$[]\(){}|- in them, you will need to add a \ before them, or use this function to do the work for you:

var escape = function(str) {
    return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};

Alternative:

var matcher = function(str, start, end){
    var quote = function(str) {
        return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
    };
    return str.match(new RegExp(quote(start) + "[^" + quote(start) + quote(end) + "]*" + quote(end)))[0].slice(1, -1)
};

Use like matcher("https://www.mysite.se/should-match?ba=11", "/", "?").


问:
Horizontal scrollbar does not show when content in the table cell overflows
I am working with dgrid tables. I have a table with single column, and each column cell have some contents within it. When my cell content is really big, i would like to show a scrollbar, so the user can scroll and view the rest of the content. However in my table, the scrollbar does not show in this case, but if i use the dgrid columnResizer to expand the column, then the scrollbar shows up till the expanding width. If the width is less than the content, then the rest of the content will still remain invisible. Here is the jsFiddle.

http://jsfiddle.net/vrwe7dn5/

This is my CSS-

```<code>#grid{
  width: 20%;
  height: auto;
}
.dgrid-scroller{
  overflow:auto;
  position: relative;
}
.dgrid-content{
   white-space: nowrap;
}
</code>```

Please let me know if i am doing anything wrong.

答: The class you are using, .dgrid-scroller{} is only for the column. To make the content scrollable, you would have to apply overflow-x:scroll on the td's themselves.</p>

Body:
I am working with dgrid tables. I have a table with single column, and each column cell have some contents within it. When my cell content is really big, i would like to show a scrollbar, so the user can scroll and view the rest of the content. However in my table, the scrollbar does not show in this case, but if i use the dgrid columnResizer to expand the column, then the scrollbar shows up till the expanding width. If the width is less than the content, then the rest of the content will still remain invisible. Here is the jsFiddle.

http://jsfiddle.net/vrwe7dn5/

This is my CSS-

#grid{
  width: 20%;
  height: auto;
}
.dgrid-scroller{
  overflow:auto;
  position: relative;
}
.dgrid-content{
   white-space: nowrap;
}

Please let me know if i am doing anything wrong.


问:
captcha or not?
i hate captcha, do you think there is a better solution </p>

答:
Mathematical questions are becoming increasingly popular

e.g. : what is 3 + 2?

These are often easier to read than captchas which can be very confusing for some users.

ContentLicense: CC BY-SA 2.5

Title: captcha or not?


问:
Securing API-KEYs while running CIrcle Ci Tests
I've this Routific API-Key, and i want it not to expose while running Circle Ci tests. And without hitting on it i can pass my specs. How can i not expose my API-KEY and still be able to pass the tests?</p>

答: I requested Routific locally for once and then received the response and saved it. Made a factory a factory which had this response and then used accordingly where needed. In my conditions, this was the only way i could go for, as the API wasnt allowed to be on even Circle Ci.</p>


问:
How to write generic Entity name in constructor in EF4?
i try to write Generic Repository in EF 4. But my codes is not looking good. Because ExpressionEntities is not GENERIC.

I want to convert this codes:

```<code>public class DataRepository<T> : IRepository<T> where T : class
{
    private ExpressionsEntities _context;
    public DataRepository()
    {
    }

    public DataRepository(ExpressionsEntities context)
    {
        _context = context;
    }
}
</code>```

to the following:

```<code>public class DataRepository<T> : IRepository<T> where T : class
{
    private GetGenericEntityCONTEXT _context;

    public DataRepository()
    {
    }

    public DataRepository(GetGenericEntityCONTEXT  context)
    {
        _context = context;
    }
}
</code>```

because ExpressionsEntities  not global my entities : ExpressionsEntities1, ExpressionsEntities 2, ExpressionsEntities 3 etx... i need to write get take entity for example:

```<code>public class DataRepository<T> : IRepository<T> where T : class
{
    private Entity _context;
    public DataRepository()
    {
    }

    public DataRepository(Entity context)
    {
        _context = context;
    }

    public class Main
    {
        main()
        {
            new DataRepository(ExpressionEntities)
        }
    }
}
</code>```

答:
Not 100% sure what your asking - from what i can understand, you wan't a way to dynamically create the entity set based on T.

Well that's easy enough:

```<code>public class DataRepository<T> : IRepository<T> where T : class
{
   private ObjectContext _ctx;

   public DataRepository<T>(ObjectContext ctx)
   {
      this._ctx = ctx;
   }

   public IObjectSet<T> CurrentEntitySet<T>()
   {
       get
       {
          var entityName = _plularizer.Pluralize(typeof(T).Name);
          string entitySetName = string.Format("{0}.{1}", EntityContainerName, entityName);
          return _ctx.CreateObjectSet<T>(entitySetName );
       }
   }
}
</code>```

Then your specific Repository could do this (for example):

```<code>public class AppleRepository : DataRepository<Apple>
{
   public AppleRepository(IObjectContext ctx) : base(ctx) {}

   public ICollection<Apple> FindApples(Func<Apple,bool> predicate)
   {
      return CurrentEntitySet.Where(predicate).ToList();
   }
}
</code>```

And when your creating your repository, pass through the object context - preferably by DI:

```<code>var repository = new AppleRepository(new ExpressionEntities()); // should be DI'ed
</code>```

Basically, we're making use of Pluralization (the same code used by Entity Framework to pluralize entity set names), and CreateObjectSet<T>.

So if you created a DataRepository<Apple>, that would translate to an entity set name of Apples (which should match the entity set on your model), and we create an entity set based on that.

The EntityContainerName property is what's on your EDMX - you should pass this through the ctor (via DI preferably).

Does that answer your question?

Body:
i try to write Generic Repository in EF 4. But my codes is not looking good. Because ExpressionEntities is not GENERIC.

I want to convert this codes:

public class DataRepository<T> : IRepository<T> where T : class
{
    private ExpressionsEntities _context;
    public DataRepository()
    {
    }

    public DataRepository(ExpressionsEntities context)
    {
        _context = context;
    }
}

to the following:

public class DataRepository<T> : IRepository<T> where T : class
{
    private GetGenericEntityCONTEXT _context;

    public DataRepository()
    {
    }

    public DataRepository(GetGenericEntityCONTEXT  context)
    {
        _context = context;
    }
}

because ExpressionsEntities  not global my entities : ExpressionsEntities1, ExpressionsEntities 2, ExpressionsEntities 3 etx... i need to write get take entity for example:

public class DataRepository<T> : IRepository<T> where T : class
{
    private Entity _context;
    public DataRepository()
    {
    }

    public DataRepository(Entity context)
    {
        _context = context;
    }

    public class Main
    {
        main()
        {
            new DataRepository(ExpressionEntities)
        }
    }
}

Body:
Not 100% sure what your asking - from what i can understand, you wan't a way to dynamically create the entity set based on T.

Well that's easy enough:

public class DataRepository<T> : IRepository<T> where T : class
{
   private ObjectContext _ctx;

   public DataRepository<T>(ObjectContext ctx)
   {
      this._ctx = ctx;
   }

   public IObjectSet<T> CurrentEntitySet<T>()
   {
       get
       {
          var entityName = _plularizer.Pluralize(typeof(T).Name);
          string entitySetName = string.Format("{0}.{1}", EntityContainerName, entityName);
          return _ctx.CreateObjectSet<T>(entitySetName );
       }
   }
}

Then your specific Repository could do this (for example):

public class AppleRepository : DataRepository<Apple>
{
   public AppleRepository(IObjectContext ctx) : base(ctx) {}

   public ICollection<Apple> FindApples(Func<Apple,bool> predicate)
   {
      return CurrentEntitySet.Where(predicate).ToList();
   }
}

And when your creating your repository, pass through the object context - preferably by DI:

var repository = new AppleRepository(new ExpressionEntities()); // should be DI'ed

Basically, we're making use of Pluralization (the same code used by Entity Framework to pluralize entity set names), and CreateObjectSet<T>.

So if you created a DataRepository<Apple>, that would translate to an entity set name of Apples (which should match the entity set on your model), and we create an entity set based on that.

The EntityContainerName property is what's on your EDMX - you should pass this through the ctor (via DI preferably).

Does that answer your question?


问:
Go + Azure: Calling a method return undefined
Am trying to use Go Azure SDK to call the notification hub api

I have installed the SDK and imported to the GO file :

```<code>package hub

import (

    "fmt"

    "github.com/Azure/azure-sdk-for-go/arm/notificationhubs"
)

func GetHub() {
    if resourceType, err := notificationhubs.Get("sourceGroupName", "NameSpaceValue", "NameOfTheHub"); err != nil {
        fmt.Println("Error occured")
        return
    }
    fmt.Println("Success")

}
</code>```

However when am trying to runt he code i got this error

```<code>undefined: notificationhubs.Get
</code>```

And am not sure what it means since my IDE don't complain about importing the Azure SDK so am assuming the SDK is imported correctly.

答:
The function you're trying to use doesn't exist (https://godoc.org/github.com/Azure/azure-sdk-for-go/arm/notificationhubs).

You're probably trying to use the function GroupClient.Get; if that's the case, you need to get an object of type GroupClient and then call the function Get on it.

Body:
Am trying to use Go Azure SDK to call the notification hub api

I have installed the SDK and imported to the GO file :

package hub

import (

    "fmt"

    "github.com/Azure/azure-sdk-for-go/arm/notificationhubs"
)

func GetHub() {
    if resourceType, err := notificationhubs.Get("sourceGroupName", "NameSpaceValue", "NameOfTheHub"); err != nil {
        fmt.Println("Error occured")
        return
    }
    fmt.Println("Success")

}

However when am trying to runt he code i got this error

undefined: notificationhubs.Get

And am not sure what it means since my IDE don't complain about importing the Azure SDK so am assuming the SDK is imported correctly.


问:
Safe way to add new images to Android project
I'm working on an application that will require regular addition of images.
At the moment every time I add new images to the drawables folder, indexings get broken (or rebuild) and connections between images and indexes get completely wrong. I'm trying to solve this for a long time now, but with no success.
Do you guys know a good (safe) way of working with drawables?</p>

答:
If you are using images in your project and need to add more and more images, in the future you'll have problems with the size of the app and performance.

I suggest you to use the Firebase Storage the store your files and just reference from App. I'm using in my projects and it works well.


问:
Django web app deploy in Azure via Visual Studio 2017
I've made a simple app with Django in Visual Studio 2017, utilizing the default template in Visual Studio (file - new - project - python - django web application).
The app runs properly locally, but after i deploy it to Azure via Visual Studio, i can only access the page that shows:

```<code>Your App Service app has been created.
</code>```

The files are all properly uploaded (i can see them in the 'site\wwwroot' folder), but the app doesn't work!

I have tried every thing that i was able to find in my searches such as: following this tutorial; adding '.azurewebsites.net' to the allowed hosts, installing azure sdk in my project virtual environment via: 'pip install azure', adding 'manage.py' to default documents, among many other things.

The thing is when i deploy (in the exact same way: right click the project, select publish, azure...) my ASP.NET apps to Azure, they work properly with minimum effort.

I am very frustated, because i really like Django framework and Azure, please help.

Thanks in advance!

答:
After much struggle i manage to to do it!

I will explain how i did it (i've used many tutorials and forum posts answers to achieve this):

1) I've created a Django (PTVS) Web App in Azure;

2) Followed this tutorial to configure that app;

3) Make the necessary adjustments to web.config file in my project, notably the path to the python version installed via extension;

4) Published my project via Visual Studio 2017 to that Django App created in the first step.

And it worked!

Body:
I've made a simple app with Django in Visual Studio 2017, utilizing the default template in Visual Studio (file - new - project - python - django web application).
The app runs properly locally, but after i deploy it to Azure via Visual Studio, i can only access the page that shows:

Your App Service app has been created.

The files are all properly uploaded (i can see them in the 'site\wwwroot' folder), but the app doesn't work!

I have tried every thing that i was able to find in my searches such as: following this tutorial; adding '.azurewebsites.net' to the allowed hosts, installing azure sdk in my project virtual environment via: 'pip install azure', adding 'manage.py' to default documents, among many other things.

The thing is when i deploy (in the exact same way: right click the project, select publish, azure...) my ASP.NET apps to Azure, they work properly with minimum effort.

I am very frustated, because i really like Django framework and Azure, please help.

Thanks in advance!


问:
Laravel change get parameter in url string and return
I'm using get parameters for search filters, and need to be able to change a value of the query string variable and return the modified url (as a string variable, nothing fancy, no redirect or anything). This is what I have so far and what is happening:

```<code>public function index(Request $request){

    echo $request->fullUrl();
    // outputs https://test.com/search?type=somestring

    $request->merge(['type' => 'anotherstring']);

    echo $request->fullUrl();
    // still outputs https://test.com/search?type=somestring

    // is there a way to change a parameter value in the url and
    // return the modified url string?

}
</code>```

I figure if worse comes to worse, I'll just parse the string manually, but it feels like there's a "laravel way" to go about this that I happen to be missing?

答:
Use fullUrlWithQuery instead.

```<code>echo $request->fullUrlWithQuery(['type' => 'anotherstring']);
</code>```

Body:
I'm using get parameters for search filters, and need to be able to change a value of the query string variable and return the modified url (as a string variable, nothing fancy, no redirect or anything). This is what I have so far and what is happening:

public function index(Request $request){

    echo $request->fullUrl();
    // outputs https://test.com/search?type=somestring

    $request->merge(['type' => 'anotherstring']);

    echo $request->fullUrl();
    // still outputs https://test.com/search?type=somestring

    // is there a way to change a parameter value in the url and
    // return the modified url string?

}

I figure if worse comes to worse, I'll just parse the string manually, but it feels like there's a "laravel way" to go about this that I happen to be missing?

Body:
Use fullUrlWithQuery instead.

echo $request->fullUrlWithQuery(['type' => 'anotherstring']);


问:
How to get reuse lines of code using SonarQube API
Is it possible to use the API to get sum of reused lines of code? Please advise.

Additional info:

Reused LOC = number of lines of code from initial baseline (before start of evolution on Project independent of later deletion of code)

Deleted LOC are not taken into account

Comments, test scripts, automated generated lines are excluded. Only source code for operational software is included

Regards,
Mircea

答: What you want is Lines of Code - New Lines of Code, and API calls certainly exist to get these values.


问:
How to input foreign unicode characters into XeLaTeX?
Friends,

I am working on a XeLaTeX document. I am almost done with my document, but I need to input text from a foreign language. I am running Mac OS X. I go to Preferences > Language & Text and in there I enable Gurmukhi - QWERTY. This allows me to input Punjabi characters, which I am able to see in MS Word. I want to input the following unicode characters:

```<code>ਰੋਂਦਾ ਬੱਚਾ  ਿੲਕ
</code>```

However, when I simply paste it into my TeXworks file, it simply does not show up when I compile a PDF file. I have indeed tried to google this, but came up with nothing other than adding some of these statements to my preamble. I am pretty desperate at this point.

My preamble already looks like this:

```<code>\documentclass[a4paper,12pt]{article} %options: [a4paper, leqno, 11pt]
\usepackage{setspace}
\usepackage{fullpage}
\usepackage[cm-default]{fontspec}
\usepackage{amssymb}
\usepackage{xunicode}
\usepackage{xltxtra}
\usepackage[utf8]{inputenc}

% -----Page Style-------------
\pagestyle{plain}

% -----Symbols----------------

\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{graphicx}
</code>```

答:
The characters are correct, but the CM fonts do not contain the glyphs. You need to select an OpenType font that contains Gurmukhi glyphs, and I think you have to explicitly choose the font when you need it. On Mac you can use “Gurmukhi MT” like this:

```<code>\newfontfamily\gu{Gurmukhi MT}
\begin{document}
{\gu ਰੋਂਦਾ ਬੱਚਾ  ਿੲਕ}
</code>```

(FreeSans and FreeSerif also contain the glyphs.)

Also: The inputenc package warns that it should not be loaded as XeTeX already uses UTF8.

Body:
Friends,

I am working on a XeLaTeX document. I am almost done with my document, but I need to input text from a foreign language. I am running Mac OS X. I go to Preferences > Language & Text and in there I enable Gurmukhi - QWERTY. This allows me to input Punjabi characters, which I am able to see in MS Word. I want to input the following unicode characters:

ਰੋਂਦਾ ਬੱਚਾ  ਿੲਕ

However, when I simply paste it into my TeXworks file, it simply does not show up when I compile a PDF file. I have indeed tried to google this, but came up with nothing other than adding some of these statements to my preamble. I am pretty desperate at this point.

My preamble already looks like this:

\documentclass[a4paper,12pt]{article} %options: [a4paper, leqno, 11pt]
\usepackage{setspace}
\usepackage{fullpage}
\usepackage[cm-default]{fontspec}
\usepackage{amssymb}
\usepackage{xunicode}
\usepackage{xltxtra}
\usepackage[utf8]{inputenc}

% -----Page Style-------------
\pagestyle{plain}

% -----Symbols----------------

\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{graphicx}

Body:
The characters are correct, but the CM fonts do not contain the glyphs. You need to select an OpenType font that contains Gurmukhi glyphs, and I think you have to explicitly choose the font when you need it. On Mac you can use “Gurmukhi MT” like this:

\newfontfamily\gu{Gurmukhi MT}
\begin{document}
{\gu ਰੋਂਦਾ ਬੱਚਾ  ਿੲਕ}

(FreeSans and FreeSerif also contain the glyphs.)

Also: The inputenc package warns that it should not be loaded as XeTeX already uses UTF8.


问:
Laravel: error while seeding database from an url
I'm trying to seed my database table. I'm getting this following error.

```<code>public function run()
{
    //
    $json = file_get_contents('http://www.ottawacityjobs.ca/en/data/');
    $emplois = json_decode($json);

    foreach ($emplois as $item) {
        Emploi::insert(
            array(
                array('JOBURL' => $item->JOBURL ),
                array('SALARYMAX' => $item->SALARYMAX ),
                array('SALARYMIN' => $item->SALARYMIN ),
                array('SALARYTYPE' => $item->SALARYTYPE ),
                array('NAME' => $item->NAME ),
                array('POSITION' => $item->POSITION ),
                array('JOBREF' => $item->JOBREF ),
                array('JOB_SUMMARY' => $item->JOB_SUMMARY ),
                array('POSTDATE' => $item->POSTDATE ),
                array('EXPIRYDATE' => $item->EXPIRYDATE ),
                array('KNOWLEDGE' => $item->KNOWLEDGE ),
                array('LANGUAGE_CERTIFICATES' => $item->LANGUAGE_CERTIFICATES ),
                array('EDUCATIONANDEXP' => $item->EDUCATIONANDEXP ),
                array('COMPANY_DESC' => $item->COMPANY_DESC ),
            ));
    }//end foreach
</code>```

答:
The URL you provided (http://www.ottawacityjobs.ca/en/data/) doesn't present the data as you are accessing it. The json is structured like this:

```<code>{
    jobs: [
        {...},
        {...},
        {...}
    ]
}
</code>```

So your code needs to iterate over the jobs property:

```<code>public function run()
{
//
$json = file_get_contents('http://www.ottawacityjobs.ca/en/data/');
$emplois = json_decode($json);

foreach ($emplois->jobs as $item) {
    Emploi::insert(
        array(
            array('JOBURL' => $item->JOBURL ),
            array('SALARYMAX' => $item->SALARYMAX ),
            array('SALARYMIN' => $item->SALARYMIN ),
            array('SALARYTYPE' => $item->SALARYTYPE ),
            array('NAME' => $item->NAME ),
            array('POSITION' => $item->POSITION ),
            array('JOBREF' => $item->JOBREF ),
            array('JOB_SUMMARY' => $item->JOB_SUMMARY ),
            array('POSTDATE' => $item->POSTDATE ),
            array('EXPIRYDATE' => $item->EXPIRYDATE ),
            array('KNOWLEDGE' => $item->KNOWLEDGE ),
            array('LANGUAGE_CERTIFICATES' => $item->LANGUAGE_CERTIFICATES ),
            array('EDUCATIONANDEXP' => $item->EDUCATIONANDEXP ),
            array('COMPANY_DESC' => $item->COMPANY_DESC ),
        ));
}//end foreach
</code>```

Body:
I'm trying to seed my database table. I'm getting this following error.

public function run()
{
    //
    $json = file_get_contents('http://www.ottawacityjobs.ca/en/data/');
    $emplois = json_decode($json);

    foreach ($emplois as $item) {
        Emploi::insert(
            array(
                array('JOBURL' => $item->JOBURL ),
                array('SALARYMAX' => $item->SALARYMAX ),
                array('SALARYMIN' => $item->SALARYMIN ),
                array('SALARYTYPE' => $item->SALARYTYPE ),
                array('NAME' => $item->NAME ),
                array('POSITION' => $item->POSITION ),
                array('JOBREF' => $item->JOBREF ),
                array('JOB_SUMMARY' => $item->JOB_SUMMARY ),
                array('POSTDATE' => $item->POSTDATE ),
                array('EXPIRYDATE' => $item->EXPIRYDATE ),
                array('KNOWLEDGE' => $item->KNOWLEDGE ),
                array('LANGUAGE_CERTIFICATES' => $item->LANGUAGE_CERTIFICATES ),
                array('EDUCATIONANDEXP' => $item->EDUCATIONANDEXP ),
                array('COMPANY_DESC' => $item->COMPANY_DESC ),
            ));
    }//end foreach

Body:
The URL you provided (http://www.ottawacityjobs.ca/en/data/) doesn't present the data as you are accessing it. The json is structured like this:

{
    jobs: [
        {...},
        {...},
        {...}
    ]
}

So your code needs to iterate over the jobs property:

public function run()
{
//
$json = file_get_contents('http://www.ottawacityjobs.ca/en/data/');
$emplois = json_decode($json);

foreach ($emplois->jobs as $item) {
    Emploi::insert(
        array(
            array('JOBURL' => $item->JOBURL ),
            array('SALARYMAX' => $item->SALARYMAX ),
            array('SALARYMIN' => $item->SALARYMIN ),
            array('SALARYTYPE' => $item->SALARYTYPE ),
            array('NAME' => $item->NAME ),
            array('POSITION' => $item->POSITION ),
            array('JOBREF' => $item->JOBREF ),
            array('JOB_SUMMARY' => $item->JOB_SUMMARY ),
            array('POSTDATE' => $item->POSTDATE ),
            array('EXPIRYDATE' => $item->EXPIRYDATE ),
            array('KNOWLEDGE' => $item->KNOWLEDGE ),
            array('LANGUAGE_CERTIFICATES' => $item->LANGUAGE_CERTIFICATES ),
            array('EDUCATIONANDEXP' => $item->EDUCATIONANDEXP ),
            array('COMPANY_DESC' => $item->COMPANY_DESC ),
        ));
}//end foreach


问:
Return Entire Array for lowest value of one value inside of secondary array
I am sure this question has been asked but i cant find it so here goes...

I have this code   (have to use php 5.3)

```<code>foreach ($array["Book"] as $abeBooks) {

$abeResult[$i] = array(
            'itemCondition' => $abeBooks['itemCondition'],
            'isbn13' =>$abeBooks['isbn13'],
            'listingPrice' =>$abeBooks['listingPrice'],
            'Link' =>$abeBooks['listingUrl'],
            'sellerRating'=>$abeBooks['sellerRating'],

);

 $isbn13[$i] = $abeBooks["isbn13"];
 $itemCondition[$i] = $abeBooks["itemCondition"];
 $sellerRating[$i] =$abeBooks['sellerRating'];
 $Price[$i] = $abeBooks["listingPrice"];
 $Link[$i] =$abeBooks['listingUrl'];

$i++; }
</code>```

it returns :

```<code>[{"itemCondition":"Fair","isbn13":"9780134167398","listingPrice":"123.5","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22403600014&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22403600014","sellerRating":"4"},{"itemCondition":"Very Good","isbn13":"9780134167398","listingPrice":"140.22","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22334428082&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22334428082","sellerRating":"4"},{"itemCondition":null,"isbn13":"9780134167398","listingPrice":"480.7","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22173609508&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22173609508","sellerRating":"4"}]
</code>```

what i would like to do is find if the lowest listingPrice if the itemCondition is good,very good, fine, or new and return the entire array for that item ex for this it would return

```<code>({"itemCondition":"Fair","isbn13":"9780134167398","listingPrice":"123.5","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22403600014&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22403600014","sellerRating":"4"})
</code>```

答:
Establish the conditions you'll accept

```<code>$conditions = array('Fair', 'Very Good', 'Fair', 'New');
</code>```

Filter the array to only include items with those conditions

```<code>$results = array_filter($abeResult, function($book) use ($conditions) {
    return in_array($book['itemCondition'], $conditions);
});
</code>```

Sort the resulting array in ascending order by listingPrice

```<code>usort($results, function($a, $b) {
    if ($a['listingPrice'] < $b['listingPrice']) return -1;
    if ($a['listingPrice'] > $b['listingPrice']) return 1;
    return 0;
});
</code>```

The lowest price will be your first result.

```<code>$result = reset($results);
</code>```

Body:
I am sure this question has been asked but i cant find it so here goes...

I have this code   (have to use php 5.3)

foreach ($array["Book"] as $abeBooks) {

$abeResult[$i] = array(
            'itemCondition' => $abeBooks['itemCondition'],
            'isbn13' =>$abeBooks['isbn13'],
            'listingPrice' =>$abeBooks['listingPrice'],
            'Link' =>$abeBooks['listingUrl'],
            'sellerRating'=>$abeBooks['sellerRating'],

);

 $isbn13[$i] = $abeBooks["isbn13"];
 $itemCondition[$i] = $abeBooks["itemCondition"];
 $sellerRating[$i] =$abeBooks['sellerRating'];
 $Price[$i] = $abeBooks["listingPrice"];
 $Link[$i] =$abeBooks['listingUrl'];

$i++; }

it returns :

[{"itemCondition":"Fair","isbn13":"9780134167398","listingPrice":"123.5","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22403600014&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22403600014","sellerRating":"4"},{"itemCondition":"Very Good","isbn13":"9780134167398","listingPrice":"140.22","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22334428082&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22334428082","sellerRating":"4"},{"itemCondition":null,"isbn13":"9780134167398","listingPrice":"480.7","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22173609508&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22173609508","sellerRating":"4"}]

what i would like to do is find if the lowest listingPrice if the itemCondition is good,very good, fine, or new and return the entire array for that item ex for this it would return

({"itemCondition":"Fair","isbn13":"9780134167398","listingPrice":"123.5","Link":"www.abebooks.com\/servlet\/BookDetailsPL?bi=22403600014&cm_ven=sws&cm_cat=sws&cm_pla=sws&cm_ite=22403600014","sellerRating":"4"})

Body:
Establish the conditions you'll accept

$conditions = array('Fair', 'Very Good', 'Fair', 'New');

Filter the array to only include items with those conditions

$results = array_filter($abeResult, function($book) use ($conditions) {
    return in_array($book['itemCondition'], $conditions);
});

Sort the resulting array in ascending order by listingPrice

usort($results, function($a, $b) {
    if ($a['listingPrice'] < $b['listingPrice']) return -1;
    if ($a['listingPrice'] > $b['listingPrice']) return 1;
    return 0;
});

The lowest price will be your first result.

$result = reset($results);


问:
ESRI API for BAO reports in Python
Currently we use ESRI's Business Analyst Online (BAO) to create demographic reports based on geospatial inputs (3-mile ring around an address, or within a city's boundaries, etc.).  These are generally output from the point and click web application as PDF or Excel files.

I'm trying to automate the process of retrieving those reports from ESRI BAO.  I have installed the Python 3.5+ package arcgis following instructions found here.  This seems to get me started with the ArcGIS functionality, but I don't see any API functionality for the BAO toolset.  Is there another API package I should be downloading?  Or is there documentation on a REST/SOAP API I can call from Python?  I've looked over the documentation, but if there's something there about what I'm trying to do I haven't found it.

Has anybody tried to do this before and been successful?  Let me know.

答: After starting trials for several ArcGIS services I found that ArcGIS Online provides access to ESRI's REST API.  As of today, once you've signed up (either paying or with a trial) you can navigate to the ArcGIS GeoEnrichment Service Documentation.  That documentation tells you everything you need to know about how to access the same reports you would find in ESRI BAO, but through a REST API.</p>

Title: ESRI API for BAO reports in Python


问:
Returning a Date Range based on Day of the Month
```<code>Select *
From Orders

WHERE   (
        extract(day from sysdate)<=21
        and
        to_date(SCHEDULEDATE , 'yyyy/mm/dd') between
        to_date((to_char(sysdate, 'YYYY')||'/'||cast((extract(month from sysdate)-1)as char)||'/22'),'yyyy/mm/dd') and to_date((to_char(sysdate,'YYYY')||'/'||cast((extract(month from sysdate))as char)||'/21'),'yyyy/mm/dd')
       )
      or
      (

       extract(day from sysdate)>21
       and
       to_date(SCHEDULEDATE , 'yyyy/mm/dd') between
       to_date((to_char(sysdate, 'YYYY')||'/'||cast((extract(month from sysdate))as char)||'/22'),'yyyy/mm/dd') and to_date((to_char(sysdate, 'YYYY')||'/'||cast((extract(month from sysdate)+1)as char)||'/21'),'yyyy/mm/dd')
    )
</code>```

I'm trying to figure out a simple way of returning a set of date ranges based on the day of the Month. If the Day of the month of less than or Equal to I want it to return all orders the have a schedule date between the 22 of the Month before and the 21st of the Current month. If the Day of the month is greater than 21 I would like it return all orders that have a schedule date of the current month up to the end of the month. I've tried to use a case in the where with no luck. What I have now doesn't seem to work either. Any help would be appreciated.

答:
I think this does what you want:</p>

```<code>WHERE (extract(day from sysdate) <= 21 and
       scheduledate >= add_months(trunc(sysdate, 'MON'), -1) + 21 and
       scheduledate < trunc(sysdate, 'MON') + 21
      ) or
      (extract(day from sysdate) > 21 and
       trunc(scheduledate, 'MON') = trunc(sysdate, 'MON')
      )
</code>```

Body:
Select *
From Orders

WHERE   (
        extract(day from sysdate)<=21
        and
        to_date(SCHEDULEDATE , 'yyyy/mm/dd') between
        to_date((to_char(sysdate, 'YYYY')||'/'||cast((extract(month from sysdate)-1)as char)||'/22'),'yyyy/mm/dd') and to_date((to_char(sysdate,'YYYY')||'/'||cast((extract(month from sysdate))as char)||'/21'),'yyyy/mm/dd')
       )
      or
      (

       extract(day from sysdate)>21
       and
       to_date(SCHEDULEDATE , 'yyyy/mm/dd') between
       to_date((to_char(sysdate, 'YYYY')||'/'||cast((extract(month from sysdate))as char)||'/22'),'yyyy/mm/dd') and to_date((to_char(sysdate, 'YYYY')||'/'||cast((extract(month from sysdate)+1)as char)||'/21'),'yyyy/mm/dd')
    )

I'm trying to figure out a simple way of returning a set of date ranges based on the day of the Month. If the Day of the month of less than or Equal to I want it to return all orders the have a schedule date between the 22 of the Month before and the 21st of the Current month. If the Day of the month is greater than 21 I would like it return all orders that have a schedule date of the current month up to the end of the month. I've tried to use a case in the where with no luck. What I have now doesn't seem to work either. Any help would be appreciated.

Body:
I think this does what you want:

WHERE (extract(day from sysdate) <= 21 and
       scheduledate >= add_months(trunc(sysdate, 'MON'), -1) + 21 and
       scheduledate < trunc(sysdate, 'MON') + 21
      ) or
      (extract(day from sysdate) > 21 and
       trunc(scheduledate, 'MON') = trunc(sysdate, 'MON')
      )


问:
Get data from link in Ionic 3 Web App
Scenario:

I have an Ionic 3 Web app, which opens for this link http://localhost:8100. I need to pass a value with the link (i.e http://localhost:8100/index.html?cell=1234567890) and the ionic app while loading the app, fetches the cell value.

What i have done:

Seriously I have no idea, where to start. I used NavParams like this,

```<code>this.cell = this.navParams.get('cell');
</code>```

and opened the app like http://localhost:8100/index.html?cell=1234567890, the app is opened successfully, but i'm getting an undefined value.

Any advice would be appreciated.

答:
i don't know if this is what you want but you can send params like this </p>

```<code>this.navCtrl.push(ChildPage, {
        cell: value
    });
</code>```

<p>on Child page Constructor or </p>

```<code>    ionViewDidLoad() {
    this.cell= this.navParams.get('cell');
    console.log(this.cell);
}
</code>```

Title: Get data from link in Ionic 3 Web App

Body:
Scenario:

I have an Ionic 3 Web app, which opens for this link http://localhost:8100. I need to pass a value with the link (i.e http://localhost:8100/index.html?cell=1234567890) and the ionic app while loading the app, fetches the cell value.

What i have done:

Seriously I have no idea, where to start. I used NavParams like this,

this.cell = this.navParams.get('cell');

and opened the app like http://localhost:8100/index.html?cell=1234567890, the app is opened successfully, but i'm getting an undefined value.

Any advice would be appreciated.

Body:
i don't know if this is what you want but you can send params like this

this.navCtrl.push(ChildPage, {
        cell: value
    });

on Child page Constructor or

    ionViewDidLoad() {
    this.cell= this.navParams.get('cell');
    console.log(this.cell);
}


问:
Right way to delete and then reindex ES documents
I have a python3 script that attempts to reindex certain documents in an existing ElasticSearch index. I can't update the documents because I'm changing from an autogenerated id to an explicitly assigned id.

I'm currently attempting to do this by deleting existing documents using delete_by_query and then indexing once the delete is complete:

```<code>self.elasticsearch.delete_by_query(
                index='%s_*' % base_index_name,
                doc_type='type_a',
                conflicts='proceed',
                wait_for_completion=True,
                refresh=True,
                body={}
            )
</code>```

However, the index is massive, and so the delete can take several hours to finish. I'm currently getting a ReadTimeoutError, which is causing the script to crash:

```<code>WARNING:elasticsearch:Connection <Urllib3HttpConnection: X> has failed for 2 times in a row, putting on 120 second timeout.
WARNING:elasticsearch:POST X:9200/base_index_name_*/type_a/_delete_by_query?conflicts=proceed&wait_for_completion=true&refresh=true [status:N/A request:140.117s]
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='X', port=9200): Read timed out. (read timeout=140)
</code>```

Is my approach correct? If so, how can I make my script wait long enough for the delete_by_query to complete? There are 2 timeout parameters that can be passed to delete_by_query - search_timeout and timeout, but search_timeout defaults to no timeout (which is I think what I want), and timeout doesn't seem to do what I want. Is there some other parameter I can pass to delete_by_query to make it wait as long as it takes for the delete to finish? Or do I need to make my script wait some other way?

Or is there some better way to do this using the ElasticSearch API?

答: You should set wait_for_completion to False. In this case you'll get task details and will be able to track task progress using corresponding API: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html#docs-delete-by-query-task-api

Body:
I have a python3 script that attempts to reindex certain documents in an existing ElasticSearch index. I can't update the documents because I'm changing from an autogenerated id to an explicitly assigned id.

I'm currently attempting to do this by deleting existing documents using delete_by_query and then indexing once the delete is complete:

self.elasticsearch.delete_by_query(
                index='%s_*' % base_index_name,
                doc_type='type_a',
                conflicts='proceed',
                wait_for_completion=True,
                refresh=True,
                body={}
            )

However, the index is massive, and so the delete can take several hours to finish. I'm currently getting a ReadTimeoutError, which is causing the script to crash:

WARNING:elasticsearch:Connection <Urllib3HttpConnection: X> has failed for 2 times in a row, putting on 120 second timeout.
WARNING:elasticsearch:POST X:9200/base_index_name_*/type_a/_delete_by_query?conflicts=proceed&wait_for_completion=true&refresh=true [status:N/A request:140.117s]
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='X', port=9200): Read timed out. (read timeout=140)

Is my approach correct? If so, how can I make my script wait long enough for the delete_by_query to complete? There are 2 timeout parameters that can be passed to delete_by_query - search_timeout and timeout, but search_timeout defaults to no timeout (which is I think what I want), and timeout doesn't seem to do what I want. Is there some other parameter I can pass to delete_by_query to make it wait as long as it takes for the delete to finish? Or do I need to make my script wait some other way?

Or is there some better way to do this using the ElasticSearch API?


问:
How to sync an accordion with a carousel?
I am using two Owl Carousels that are sync'd together to have one main image and thumbnails below. I am using the code from this pen.

I also have an accordion on the page. I need to now sync my accordion with the thumbnails and have them work both ways where if I click on an accordion the thumbnail becomes active and if I click on the thumbnail the accordion opens up.

I have a demo here.

I have added selectors onto both:

Thumbnail Owl Carousel

```<code>$i = 1;

$html_out .= '<div class="item thumb" data-flavor="' . $i++ . '">';
   $html_out .= '<img class="slide-img-thumb" src="' . $slide . '" style="background: no-repeat center center; background-size: cover;" />';
$html_out .= '</div>';
</code>```

Accordion

```<code>$i = 1;
$html .= '<div class="x-accordion-heading">';
    html .= '<a class="x-accordion-toggle collapsed hvr-bounce-to-right" data-flavor="' . $i++ . '" data-cs-collapse-toggle="" data-cs-collapse-parent="#flavour-accordion">' . $title . '</a>';
$html .= '</div>';
</code>```

The main takeaway from each thing is that they both have data-flavor='1' and that increments to 2, 3, 4, etc.

How can I properly sync the two?

答:
Try this:</p>

```<code>jQuery("#sync1").on('changed.owl.carousel', function(e) {
 //Added the timeout so that transition completes in that time
 setTimeout(function(){
    var cEl = jQuery("#sync2 .owl-item.active.current");
    var item = cEl.children('.item');
    var flavor = Number(item.data('flavor'));
    if(!isNaN(flavor)){
        var el = jQuery("[data-cs-collapse-toggle]").filter("[data-flavor='" + flavor + "']");
        if(el.length > 0){
            el.trigger('click');
        }
    }
}, 100);
})
</code>```

Body:
I am using two Owl Carousels that are sync'd together to have one main image and thumbnails below. I am using the code from this pen.

I also have an accordion on the page. I need to now sync my accordion with the thumbnails and have them work both ways where if I click on an accordion the thumbnail becomes active and if I click on the thumbnail the accordion opens up.

I have a demo here.

I have added selectors onto both:

Thumbnail Owl Carousel

$i = 1;

$html_out .= '
';
   $html_out .= '';
$html_out .= '
';

Accordion

$i = 1;
$html .= '
';
    html .= '' . $title . '';
$html .= '
';

The main takeaway from each thing is that they both have data-flavor='1' and that increments to 2, 3, 4, etc.

How can I properly sync the two?

Body:
Try this:

jQuery("#sync1").on('changed.owl.carousel', function(e) {
 //Added the timeout so that transition completes in that time
 setTimeout(function(){
    var cEl = jQuery("#sync2 .owl-item.active.current");
    var item = cEl.children('.item');
    var flavor = Number(item.data('flavor'));
    if(!isNaN(flavor)){
        var el = jQuery("[data-cs-collapse-toggle]").filter("[data-flavor='" + flavor + "']");
        if(el.length > 0){
            el.trigger('click');
        }
    }
}, 100);
})


问:
Map dynamically array to nested object
I want to retrieve the form content on a submit and map that data into an object.

```<code>let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);
</code>```

--
Template objects to send through POST

```<code>serializedToObject(serializedArray) {
        let templateObject = {
            privider: '',
            pop3: {
                host: '',
                port: 110,
                ssl: false
            },
            imap: {
                host: '',
                port: 993
            },

            email: '',
            password: ''
        };

        for (let data in serializedArray) {
        }

        return templateObject;
    }
</code>```

--
The form of the userData is

```<code>[Object, Object, Object, Object, Object, Object, Object]
</code>```

-- While on object is of form

```<code>Object: {
  name: 'provider',
  value: 'Aladin'
}

Object: {
  name: 'imap-host',
  value: '955'
}

Object: {
  name: 'imap-port',
  value:
}

Object: {
  email: 'test@gmail.com',
  value:
}
</code>```

So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.

Update

```<code>[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]
</code>```

答:
You can also use reduce method, in a more functional way

```<code>const array = [{
  name: 'provider',
  value: 'Aladin'
},{
  name: 'imap-host',
  value: '955'
},{
  name: 'imap-port',
  value: 'something'
}];

const newObject = array.reduce( (acc, item, {}) => {
  acc[item.name] = item.value;
  return acc;
})

console.log(newObject);
</code>```

Link to fiddle: https://jsfiddle.net/y5xkddnn/

Title: Map dynamically array to nested object

Body:
I want to retrieve the form content on a submit and map that data into an object.

let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);

--
Template objects to send through POST

serializedToObject(serializedArray) {
        let templateObject = {
            privider: '',
            pop3: {
                host: '',
                port: 110,
                ssl: false
            },
            imap: {
                host: '',
                port: 993
            },

            email: '',
            password: ''
        };

        for (let data in serializedArray) {
        }

        return templateObject;
    }

--
The form of the userData is

[Object, Object, Object, Object, Object, Object, Object]

-- While on object is of form

Object: {
  name: 'provider',
  value: 'Aladin'
}

Object: {
  name: 'imap-host',
  value: '955'
}

Object: {
  name: 'imap-port',
  value:
}

Object: {
  email: 'test@gmail.com',
  value:
}

So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.

Update

[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]

Body:
You can also use reduce method, in a more functional way

const array = [{
  name: 'provider',
  value: 'Aladin'
},{
  name: 'imap-host',
  value: '955'
},{
  name: 'imap-port',
  value: 'something'
}];

const newObject = array.reduce( (acc, item, {}) => {
  acc[item.name] = item.value;
  return acc;
})

console.log(newObject);

Link to fiddle: https://jsfiddle.net/y5xkddnn/


问:
How do I display a text file content in CMD?
I want to display the content of a text file in a CMD window. In addition, I want to see the new lines that added to file, like tail -f command in Unix.

答:
You can use the 'more' command to see the content of the file:</p>

```<code>more filename.txt
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use the 'more' command to see the content of the file:

more filename.txt


问:
Anaconda new environment gives me python SyntaxError 'yield' inside async function
Ok, I'm sorry if this has been asked before, I did found some info here but I'm still stuck.

I have Anaconda 3 (python 3.6) on Windows.
Created a new environment using

conda create --tf python=3.5

That works just fine and in cmd I can activate it. But I get this nice error when running python.

I kind of get the idea my issue is my win environment variables.
But I have tried to added my Anaconda path to the beginning of my path variable and my new tf environment path to the beginning. But no luck. Is this some sort of conflict between python 3.6 and 3.5.

Thanks

答:
[Moved from comments]

Somehow or other you're trying to import from your root install even within your activated env, and that root install (being Python 3.6) uses async + yield in its stdlib, which isn't supported in the 3.5 you want to use.

When using Anaconda, you shouldn't have either PYTHONPATH or PYTHONHOME set (and if there are other PYTHON* environment variables set, might as well clear them too!)

These cause problems because these variables are very powerful and the interpreter winds up obeying them.  In the case of multiple environments and/or multiple Python distributions on the same system, it's best to leave them alone.