问:
Chart drawing couple lines, when open second file via OpenFileDialog
I'm making app, which taking data  from file and shows it on chart. But, when I'm adding an additional file I see 3 graphs, not 2.

I am reading csv file, parse into double and adding series. It has to be 2 graphs, but I see 3.

```<code>    string[] tmpStrArr;
    double x;
    double y;
    public Form1()
    {
        InitializeComponent();
        chartGraphic.ChartAreas[0].AxisY.ScaleView.Zoom(-60, 15); // -15<= y <=15
        chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoom(-60, 2); // -15 <= x <= 2
        chartGraphic.ChartAreas[0].CursorX.IsUserEnabled = true;
        chartGraphic.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
        chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
        chartGraphic.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        string line = "";
        ofd.Title = "Open File With Data";
        ofd.Filter = "CSV File|*.csv|TXT File|*txt";
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            textBox1.Text = ofd.FileName;
            MessageBox.Show(ofd.FileName);
            StreamReader sr = new StreamReader(ofd.FileName);
            while (line != null)
            {

                //for (int i = -15; i < 2; i++)
                //{
                //}
                line = sr.ReadLine();
                if (line != null)
                {
                    tmpStrArr = line.Split(',');
                    x = Double.Parse(tmpStrArr[0]);
                    y = Double.Parse(tmpStrArr[1]);
                    chartGraphic.Series[0].Points.AddXY(x,y);

                    listBox1.Items.Add(line);
                }
            }
            chartGraphic.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            tmpStrArr = null;
            x = 0;
            y = 0;

            sr.Close();
            ofd.Dispose();

        }

    }
</code>```

I expect the output of 2 graphs, from 2 files, not 3 graphs from 2 files.

答:
What you are seeing are not as you suspect three 'graphs' but two!

But as the ChartType is Line and the last point of the 1st data portion ends at x=30 and the first of the 2nd file start at x=1 you see an extra line connecting these two datapoints.

Line is one of the few type that support x-values going forward and back.

You can change to ChartType Point to test. Or you can use a 2nd Series for the 2nd file and the artifact will dissappear..

If you'd rather keep all points in the same series, you can't prevent the connecting line but you can hide it : You can start each set of datapoints with Color.Transparent, as the line color is determined by the 2nd point..:

```<code>int pt = chartGraphic.Series[0].Points.AddXY(x,y);
if (pt == 0) chartGraphic.Series[0].Points[pt].Color = Color.Transparent
</code>```

Body:
I'm making app, which taking data  from file and shows it on chart. But, when I'm adding an additional file I see 3 graphs, not 2.

I am reading csv file, parse into double and adding series. It has to be 2 graphs, but I see 3.

    string[] tmpStrArr;
    double x;
    double y;
    public Form1()
    {
        InitializeComponent();
        chartGraphic.ChartAreas[0].AxisY.ScaleView.Zoom(-60, 15); // -15<= y <=15
        chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoom(-60, 2); // -15 <= x <= 2
        chartGraphic.ChartAreas[0].CursorX.IsUserEnabled = true;
        chartGraphic.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
        chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
        chartGraphic.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        string line = "";
        ofd.Title = "Open File With Data";
        ofd.Filter = "CSV File|*.csv|TXT File|*txt";
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            textBox1.Text = ofd.FileName;
            MessageBox.Show(ofd.FileName);
            StreamReader sr = new StreamReader(ofd.FileName);
            while (line != null)
            {

                //for (int i = -15; i < 2; i++)
                //{
                //}
                line = sr.ReadLine();
                if (line != null)
                {
                    tmpStrArr = line.Split(',');
                    x = Double.Parse(tmpStrArr[0]);
                    y = Double.Parse(tmpStrArr[1]);
                    chartGraphic.Series[0].Points.AddXY(x,y);

                    listBox1.Items.Add(line);
                }
            }
            chartGraphic.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            tmpStrArr = null;
            x = 0;
            y = 0;

            sr.Close();
            ofd.Dispose();

        }

    }

I expect the output of 2 graphs, from 2 files, not 3 graphs from 2 files.

Body:
What you are seeing are not as you suspect three 'graphs' but two!

But as the ChartType is Line and the last point of the 1st data portion ends at x=30 and the first of the 2nd file start at x=1 you see an extra line connecting these two datapoints.

Line is one of the few type that support x-values going forward and back.

You can change to ChartType Point to test. Or you can use a 2nd Series for the 2nd file and the artifact will dissappear..

If you'd rather keep all points in the same series, you can't prevent the connecting line but you can hide it : You can start each set of datapoints with Color.Transparent, as the line color is determined by the 2nd point..:

int pt = chartGraphic.Series[0].Points.AddXY(x,y);
if (pt == 0) chartGraphic.Series[0].Points[pt].Color = Color.Transparent


来源: stackexchange

问:
How to find closest lower value in array angular 6?
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

```<code><button (click) ="getPrev()">Previous Value</button>
</code>```

app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}
</code>```

答:
Try this one.

```<code>  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reduce((prev, current) => {
       return (Math.abs(current.id - this.currentVal) < Math.abs(prev.id - this.currentVal) ? current : prev);
     })
     console.log(number.id);
  }
</code>```

Stackblitz

ContentLicense: CC BY-SA 4.0

Body:
I have an array of objects where I need to find closest lower value from that array based on some value or current value in angular 6, I have already tried but its showing undefined.

app.component.html

<button (click) ="getPrev()">Previous Value</button>

app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reverse().find(e => e <= this.currentVal);
     console.log(number);
  }
}

Body:
Try this one.

  getPrev(){
     this.currentVal = 5;
     this.arrayVal= this.array;
     let number = this.arrayVal.reduce((prev, current) => {
       return (Math.abs(current.id - this.currentVal) < Math.abs(prev.id - this.currentVal) ? current : prev);
     })
     console.log(number.id);
  }

Stackblitz


问:
How to find whether a string has repeated characters?
I have written this code ...and the answer I am expecting is not correct
in this code, if a string has repeated characters, it should return False
but its returning True in all cases

I have done this much coding to try to solve this problem
This is in JUPYTER notebook

```<code>def is_isogram(string):
   for i in string:
       if string.count(i) == 1:
           print('True')
       elif string.count(i) > 1:
           print('False')
</code>```

I typed 'Hello' it should return False, but returnung true in all cases

答:
Not very pythonic, but in your original style:</p>

```<code>def is_isogram(s):
    for i in s:
        if s.count(i) > 1:
            return False
    return True
</code>```

Body:
I have written this code ...and the answer I am expecting is not correct
in this code, if a string has repeated characters, it should return False
but its returning True in all cases

I have done this much coding to try to solve this problem
This is in JUPYTER notebook

def is_isogram(string):
   for i in string:
       if string.count(i) == 1:
           print('True')
       elif string.count(i) > 1:
           print('False')

I typed 'Hello' it should return False, but returnung true in all cases

Body:
Not very pythonic, but in your original style:

def is_isogram(s):
    for i in s:
        if s.count(i) > 1:
            return False
    return True


问:
Using DirectX from subprocess executed by windows service
I need to execute ffmpeg process from windows service and capture it's standard output. It works fine until I use hardware acceleration. Because accessing DirectX from windows service is restricted, the subprocess also fails to access it.

When I'm executing the same code from console application, everything works OK, but the same code executed from windows service fails to use hardware acceleration.

```<code>        string ffmpegArgs = /*-hwaccel dxva2 */"-threads 0 -probesize 100512 -i c:/Temp/test.mp4 -vf yadif -vcodec libx264 -preset ultrafast -tune zerolatency -profile baseline -x264-params keyint=20:min-keyint=20:scenecut=-1 -acodec aac -b:a 48k -flags +cgop -f mp4 -movflags empty_moov+default_base_moof+frag_keyframe c:/temp/output.avi";

        var psi = new ProcessStartInfo
        {
            FileName = "c:/Temp/ffmpeg4/ffmpeg.exe",
            Arguments = ffmpegArgs,
            WorkingDirectory = "c:/Temp/ffmpeg4",
            CreateNoWindow = false,
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardInput = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        };

        var processVideo = new Process { StartInfo = psi }.Start();
</code>```

I need somehow break the inherited restrictions to be able to execute ffmpeg with hardware acceleration (access DirectX API). Any suggestions?

答:
You can instruct FFMPEG process to use DirectX 11 Hardware Video acceleration.
In this case, FFMPEG will need to create a DirectX 11 device, by calling D3D11CreateDevice function, which doesn't need any window handles to be supplied.

In order to make FFMPEG utlize DirectX 11 hardware video acceleration, you need to specify the following hwaccel parameter instead:

```<code>-hwaccel d3d11va
</code>```

Body:
I need to execute ffmpeg process from windows service and capture it's standard output. It works fine until I use hardware acceleration. Because accessing DirectX from windows service is restricted, the subprocess also fails to access it.

When I'm executing the same code from console application, everything works OK, but the same code executed from windows service fails to use hardware acceleration.

        string ffmpegArgs = /*-hwaccel dxva2 */"-threads 0 -probesize 100512 -i c:/Temp/test.mp4 -vf yadif -vcodec libx264 -preset ultrafast -tune zerolatency -profile baseline -x264-params keyint=20:min-keyint=20:scenecut=-1 -acodec aac -b:a 48k -flags +cgop -f mp4 -movflags empty_moov+default_base_moof+frag_keyframe c:/temp/output.avi";

        var psi = new ProcessStartInfo
        {
            FileName = "c:/Temp/ffmpeg4/ffmpeg.exe",
            Arguments = ffmpegArgs,
            WorkingDirectory = "c:/Temp/ffmpeg4",
            CreateNoWindow = false,
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardInput = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        };

        var processVideo = new Process { StartInfo = psi }.Start();

I need somehow break the inherited restrictions to be able to execute ffmpeg with hardware acceleration (access DirectX API). Any suggestions?

Body:
You can instruct FFMPEG process to use DirectX 11 Hardware Video acceleration.
In this case, FFMPEG will need to create a DirectX 11 device, by calling D3D11CreateDevice function, which doesn't need any window handles to be supplied.

In order to make FFMPEG utlize DirectX 11 hardware video acceleration, you need to specify the following hwaccel parameter instead:

-hwaccel d3d11va


问:
exceeding number of urls when writing to excel file
I got this warning WARNING: C:\Users\diodi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlsxwriter\worksheet.py:923: UserWarning: Ignoring URL 'https://www.google.com/search?q=hello+world' since it exceeds Excel's limit of 65,530 URLS per worksheet.
  "65,530 URLS per worksheet." % force_unicode(url))

I use to write th output of scraped data

```<code>#spider.found_items is a list of dictionary
df = pd.DataFrame(spider.found_items)[ordered_list] #ordered_list is the order of dictiornary outputed
df.to_excel("{}.xlsx".format(file_name),sheet_name='All Products')
</code>```

I checked this Number of URLS is over Excel's limit of 65,530 URLS per worksheet. but this formats the links as strings (not clickable). is there a way to keep URL (as a link) if I can write to multiple sheets or any other suggestion?

答:
Fundamentally this is an Excel limitation. It only allows 65,530 unique* urls per worksheet. There isn't any workaround for that.

(*) Excel does allow more than 65,530 non-unique urls if they are grouped contiguously. For example the same url in cells A1 to A100 would only be counted as one url against the 65,530 limit. However, grouping of urls to take advantage of this isn't supported by XlsxWriter (and even if it was it doesn't help if all the urls are unique or non-contiguous).

Body:
I got this warning WARNING: C:\Users\diodi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlsxwriter\worksheet.py:923: UserWarning: Ignoring URL 'https://www.google.com/search?q=hello+world' since it exceeds Excel's limit of 65,530 URLS per worksheet.
  "65,530 URLS per worksheet." % force_unicode(url))

I use to write th output of scraped data

#spider.found_items is a list of dictionary
df = pd.DataFrame(spider.found_items)[ordered_list] #ordered_list is the order of dictiornary outputed
df.to_excel("{}.xlsx".format(file_name),sheet_name='All Products')

I checked this Number of URLS is over Excel's limit of 65,530 URLS per worksheet. but this formats the links as strings (not clickable). is there a way to keep URL (as a link) if I can write to multiple sheets or any other suggestion?


问:
MySQLdb._exceptions.OperationalError: (1048, "..........' cannot be null")
I am trying to push my excel.xlsm file data to sql php myadmin
and this is my code as I created a module that dict between the database sql and the excel.xlsm database as the columns name in xlsm is different from columns name in database sql
here's my simple code

```<code> from sqlalchemy import create_engine
 import pandas as pd
 import os
 import MySQLdb

 engine = create_engine('mysql+mysqldb://root:@localhost/myDB?
 charset=utf8mb4&binary_prefix=true', echo=False)

 mydir = (os.getcwd()).replace('\\', '/') + '/'
 all_data = pd.read_excel(r'' + mydir + 'Governance_Tracker - Copy -
 Copy.xlsm'
 ,header = 1).drop(['#'], axis=1)
 all_data.replace('\n','', regex=True)
 df = all_data.where((pd.notnull(all_data)), None)
 print(df)
 for i in range(len(df)):
 data_dict ={}
 data_dict['site_name'] = df['Site Name'][i]
 data_dict['region'] = df['Region'][i]
 data_dict['site_type'] = df['Site Type'][i]
 data_dict['site_code'] = df['SiteCode'][i]
 data_dict['tac_name'] = df['TAC Name'][i]
 data_dict['dt_readiness'] = df['DT\nReadiness'][i]
 data_dict['rfs'] = df['RFS'][i]
 data_dict['rfs_date'] = df['RFS Date'][i]
 data_dict['huawei_1st_submission_date'] = df['Huawei 1st submission date
 '][i]
 data_dict['te_1st_submission_date'] = df['TE 1st Response date '][i]
 data_dict['huawei_2nd_submission_date'] = df['Huawei 2nd submission date
 '][i]
 data_dict['te_2nd_submission_date'] = df['TE 2nd Response date '][i]
 data_dict['huawei_3rd_submission_date'] = df['Huawei 3rd submission date
 '][i]
 data_dict['te_3rd_submission_date'] = df['TE 3rd Response date '][i]
 data_dict['acceptance_date_opt'] = df['Acceptance Date(Optimization)'][i]
 data_dict['acceptance_date_plan'] = df['Acceptance Date(Planning)'][i]
 data_dict['signed_sites'] = df['signed sites'][i]
 data_dict['as_built_date'] = df['As Built Date'][i]
 data_dict['as_built_status'] = df['AS built status'][i]
 data_dict['date_dt'] = df['Date DT'][i]
 data_dict['dt_status'] = df['DT Status'][i]
 data_dict['shr_status'] = df['SHR Status'][i]
 data_dict['dt_planned'] = df['DT Planned'][i]
 data_dict['integeration_status'] = df['Integeration Status'][i]
 data_dict['comments_snags'] = df['Comments/snags'][i]
 data_dict['cluster_name'] = df['Cluster name'][i]
 data_dict['type_standalone_colocated'] = df['Type(Standalone/colocated)']
 [i]
 data_dict['installed_type_standalone_colocated'] = df['Installed type
 (Standalone/colocated)'][i]
 data_dict['status'] = df[' Status '][i]
 data_dict['pending'] = df['Pending  '][i]
 data_dict['pending_status'] = df['Pending Status'][i]
 data_dict['problematic_details'] = df['problematic details'][i]
 df1 = pd.DataFrame(data_dict,index=[0])
 df1.to_sql('govtracker', con=engine,if_exists='append',index=False)

 print("Success")
 rows = engine.execute("SELECT * FROM govtracker").fetchall()
 print(rows)
</code>```

but I find these error in terminal
traceback error

```<code> Traceback (most recent call last):
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1244, in _execute_context
 cursor, statement, parameters, context
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\default.py", line 552, in do_execute
 cursor.execute(statement, parameters)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 206, in execute
 res = self._query(query)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 312, in _query
 db.query(q)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\connections.py", line 224, in query
_mysql.connection.query(self, query)
 MySQLdb._exceptions.OperationalError: (1048, "Column
 'te_1st_submission_date' cannot be null")
 The above exception was the direct cause of the following exception:
 Traceback (most recent call last):
 File "<input>", line 1, in <module>
 File "C:\Program Files\JetBrains\PyCharm
 2019.1.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
 pydev_imports.execfile(filename, global_vars, local_vars)  # execute the
 script
 File "C:\Program Files\JetBrains\PyCharm
 2019.1.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in
 execfile
 exec(compile(contents+"\n", file, 'exec'), glob, loc)
 File "C:/Users/DELL/PycharmProjects/GUIRef/PyGUI.py", line 49, in
 <module>
 df1.to_sql('govtracker', con=engine,if_exists='append',index=False)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\core\generic.py", line 2531, in to_sql
 dtype=dtype, method=method)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 460, in to_sql
 chunksize=chunksize, dtype=dtype, method=method)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 1174, in to_sql
 table.insert(chunksize, method=method)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 686, in insert
 exec_insert(conn, keys, chunk_iter)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 599, in _execute_insert
 conn.execute(self.table.insert(), data)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 988, in execute
 return meth(self, multiparams, params)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
 return connection._execute_clauseelement(self, multiparams, params)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1107, in _execute_clauseelement
 distilled_params,
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1248, in _execute_context
 e, statement, parameters, cursor, context
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1466, in
 _handle_dbapi_exception
 util.raise_from_cause(sqlalchemy_exception, exc_info)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\util\compat.py", line 383, in raise_from_cause
 reraise(type(exception), exception, tb=exc_tb, cause=cause)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\util\compat.py", line 128, in reraise
 raise value.with_traceback(tb)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1244, in _execute_context
 cursor, statement, parameters, context
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\default.py", line 552, in do_execute
 cursor.execute(statement, parameters)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 206, in execute
 res = self._query(query)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 312, in _query
 db.query(q)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\connections.py", line 224, in query
_mysql.connection.query(self, query)
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError)
(1048, "Column 'te_1st_submission_date' cannot be null")
[SQL: INSERT INTO govtracker (site_name, region, site_type, site_code,
tac_name, dt_readiness, rfs, rfs_date, huawei_1st_submission_date,
te_1st_submission_date, huawei_2nd_submission_date,
te_2nd_submission_date, huawei_3rd_submission_date,
te_3rd_submission_date, acceptance_date_opt, acceptance_date_plan,
signed_sites, as_built_date, as_built_status, date_dt, dt_status,
shr_status, dt_planned, integeration_status, comments_snags, cluster_name,
type_standalone_colocated, installed_type_standalone_colocated, status,
pending, pending_status, problematic_details) VALUES (%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s)]
[parameters: ('Manshyet Naser', 'Cairo', 'Existing', 'LCAIE10002',
'Manshyet nasser', datetime.datetime(2017, 7, 20, 0, 0), 'yes',
datetime.datetime(2017, 7, 23, 0, 0), datetime.datetime(2017, 9, 12, 0,
0), None, None, None, None, None, datetime.datetime(2017, 9, 17, 0, 0),
None, 'PAC Signed', None, 'Done', None, None, None, None, None, None, 'Mid
Cairo', 'L700+L1800', None, 'PAC Signed', None, None, None)]
(Background on this error at: http://sqlalche.me/e/e3q8)
</code>```

and this is my sql query in php myadmin

```<code> CREATE TABLE `mydb`.`govtracker` (
 `id` DOUBLE(255, 0) NOT NULL,
 `site_name` VARCHAR(255) NOT NULL,
 `region` VARCHAR(255) NOT NULL,
 `site_type` VARCHAR(255) NOT NULL,
 `site_code` VARCHAR(255) NOT NULL,
 `tac_name` VARCHAR(255) NOT NULL,
 `dt_readiness` DATE NOT NULL,
 `rfs` BOOLEAN NOT NULL,
 `rfs_date` DATE NOT NULL,
 `huawei_1st_submission_date` DATE NOT NULL,
 `te_1st_submission_date` DATE NOT NULL,
 `huawei_2nd_submission_date` DATE NOT NULL,
 `te_2nd_submission_date` DATE NOT NULL,
 `huawei_3rd_submission_date` DATE NOT NULL,
 `te_3rd_submission_date` DATE NOT NULL,
 `acceptance_date_opt` DATE NOT NULL,
 `acceptance_date_plan` DATE NOT NULL,
 `signed_sites` VARCHAR(255) NOT NULL,
 `as_built_date` DATE NOT NULL,
 `as_built_status` VARCHAR(255) NOT NULL,
 `date_dt` DATE NOT NULL,
 `dt_status` VARCHAR(255) NOT NULL,
 `shr_status` VARCHAR(255) NOT NULL,
 `dt_planned` INT(255) NOT NULL,
 `integeration_status` VARCHAR(255) NOT NULL,
 `comments_snags` LONGTEXT NOT NULL,
 `cluster_name` LONGTEXT NOT NULL,
 `type_standalone_colocated` VARCHAR(255) NOT NULL,
 `installed_type_standalone_colocated` VARCHAR(255) NOT NULL,
 `status` VARCHAR(255) NOT NULL,
 `pending` VARCHAR(255) NOT NULL,
 `pending_status` LONGTEXT NOT NULL,
 `problematic_details` LONGTEXT NOT NULL,
 `ets_tac` INT(255) NOT NULL,
 `region_r` VARCHAR(255) NOT NULL,
 `sf6_signed_date` DATE NOT NULL,
 `sf6_signed_comment` LONGTEXT NOT NULL,
 `comment_history` LONGTEXT NOT NULL,
 `on_air_owner` VARCHAR(255) NOT NULL,
 `pp_owner` VARCHAR(255) NOT NULL,
 `report_comment` LONGTEXT NOT NULL,
 `hu_opt_area_owner` VARCHAR(255) NOT NULL,
 `planning_owner` VARCHAR(255) NOT NULL,
 `po_number` VARCHAR(255) NOT NULL,
 `trigger_date` DATE NOT NULL,
 `as_built_status_tr` VARCHAR(255) NOT NULL
 ) ENGINE = InnoDB;
</code>```

答:
the error is clear  you have  a column  in your table named te_1st_submission_date  declared as

```<code>`te_1st_submission_date` DATE NOT NULL,
</code>```

but you are trying to insert a null value for this column

1048, "Column 'te_1st_submission_date' cannot be null")

Probably your assignment

```<code>data_dict['te_1st_submission_date'] = df['TE 1st Response date '][i]
</code>```

contain a null value

try add  a valid value  for this (and eventually other null values)

Body:
I am trying to push my excel.xlsm file data to sql php myadmin
and this is my code as I created a module that dict between the database sql and the excel.xlsm database as the columns name in xlsm is different from columns name in database sql
here's my simple code

 from sqlalchemy import create_engine
 import pandas as pd
 import os
 import MySQLdb

 engine = create_engine('mysql+mysqldb://root:@localhost/myDB?
 charset=utf8mb4&binary_prefix=true', echo=False)

 mydir = (os.getcwd()).replace('\\', '/') + '/'
 all_data = pd.read_excel(r'' + mydir + 'Governance_Tracker - Copy -
 Copy.xlsm'
 ,header = 1).drop(['#'], axis=1)
 all_data.replace('\n','', regex=True)
 df = all_data.where((pd.notnull(all_data)), None)
 print(df)
 for i in range(len(df)):
 data_dict ={}
 data_dict['site_name'] = df['Site Name'][i]
 data_dict['region'] = df['Region'][i]
 data_dict['site_type'] = df['Site Type'][i]
 data_dict['site_code'] = df['SiteCode'][i]
 data_dict['tac_name'] = df['TAC Name'][i]
 data_dict['dt_readiness'] = df['DT\nReadiness'][i]
 data_dict['rfs'] = df['RFS'][i]
 data_dict['rfs_date'] = df['RFS Date'][i]
 data_dict['huawei_1st_submission_date'] = df['Huawei 1st submission date
 '][i]
 data_dict['te_1st_submission_date'] = df['TE 1st Response date '][i]
 data_dict['huawei_2nd_submission_date'] = df['Huawei 2nd submission date
 '][i]
 data_dict['te_2nd_submission_date'] = df['TE 2nd Response date '][i]
 data_dict['huawei_3rd_submission_date'] = df['Huawei 3rd submission date
 '][i]
 data_dict['te_3rd_submission_date'] = df['TE 3rd Response date '][i]
 data_dict['acceptance_date_opt'] = df['Acceptance Date(Optimization)'][i]
 data_dict['acceptance_date_plan'] = df['Acceptance Date(Planning)'][i]
 data_dict['signed_sites'] = df['signed sites'][i]
 data_dict['as_built_date'] = df['As Built Date'][i]
 data_dict['as_built_status'] = df['AS built status'][i]
 data_dict['date_dt'] = df['Date DT'][i]
 data_dict['dt_status'] = df['DT Status'][i]
 data_dict['shr_status'] = df['SHR Status'][i]
 data_dict['dt_planned'] = df['DT Planned'][i]
 data_dict['integeration_status'] = df['Integeration Status'][i]
 data_dict['comments_snags'] = df['Comments/snags'][i]
 data_dict['cluster_name'] = df['Cluster name'][i]
 data_dict['type_standalone_colocated'] = df['Type(Standalone/colocated)']
 [i]
 data_dict['installed_type_standalone_colocated'] = df['Installed type
 (Standalone/colocated)'][i]
 data_dict['status'] = df[' Status '][i]
 data_dict['pending'] = df['Pending  '][i]
 data_dict['pending_status'] = df['Pending Status'][i]
 data_dict['problematic_details'] = df['problematic details'][i]
 df1 = pd.DataFrame(data_dict,index=[0])
 df1.to_sql('govtracker', con=engine,if_exists='append',index=False)

 print("Success")
 rows = engine.execute("SELECT * FROM govtracker").fetchall()
 print(rows)

but I find these error in terminal
traceback error

 Traceback (most recent call last):
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1244, in _execute_context
 cursor, statement, parameters, context
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\default.py", line 552, in do_execute
 cursor.execute(statement, parameters)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 206, in execute
 res = self._query(query)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 312, in _query
 db.query(q)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\connections.py", line 224, in query
_mysql.connection.query(self, query)
 MySQLdb._exceptions.OperationalError: (1048, "Column
 'te_1st_submission_date' cannot be null")
 The above exception was the direct cause of the following exception:
 Traceback (most recent call last):
 File "<input>", line 1, in <module>
 File "C:\Program Files\JetBrains\PyCharm
 2019.1.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
 pydev_imports.execfile(filename, global_vars, local_vars)  # execute the
 script
 File "C:\Program Files\JetBrains\PyCharm
 2019.1.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in
 execfile
 exec(compile(contents+"\n", file, 'exec'), glob, loc)
 File "C:/Users/DELL/PycharmProjects/GUIRef/PyGUI.py", line 49, in
 <module>
 df1.to_sql('govtracker', con=engine,if_exists='append',index=False)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\core\generic.py", line 2531, in to_sql
 dtype=dtype, method=method)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 460, in to_sql
 chunksize=chunksize, dtype=dtype, method=method)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 1174, in to_sql
 table.insert(chunksize, method=method)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 686, in insert
 exec_insert(conn, keys, chunk_iter)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\pandas\io\sql.py", line 599, in _execute_insert
 conn.execute(self.table.insert(), data)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 988, in execute
 return meth(self, multiparams, params)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
 return connection._execute_clauseelement(self, multiparams, params)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1107, in _execute_clauseelement
 distilled_params,
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1248, in _execute_context
 e, statement, parameters, cursor, context
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1466, in
 _handle_dbapi_exception
 util.raise_from_cause(sqlalchemy_exception, exc_info)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\util\compat.py", line 383, in raise_from_cause
 reraise(type(exception), exception, tb=exc_tb, cause=cause)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\util\compat.py", line 128, in reraise
 raise value.with_traceback(tb)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\base.py", line 1244, in _execute_context
 cursor, statement, parameters, context
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\sqlalchemy\engine\default.py", line 552, in do_execute
 cursor.execute(statement, parameters)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 206, in execute
 res = self._query(query)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\cursors.py", line 312, in _query
 db.query(q)
 File "C:\Users\DELL\PycharmProjects\GUIRef\venv\lib\site-
 packages\MySQLdb\connections.py", line 224, in query
_mysql.connection.query(self, query)
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError)
(1048, "Column 'te_1st_submission_date' cannot be null")
[SQL: INSERT INTO govtracker (site_name, region, site_type, site_code,
tac_name, dt_readiness, rfs, rfs_date, huawei_1st_submission_date,
te_1st_submission_date, huawei_2nd_submission_date,
te_2nd_submission_date, huawei_3rd_submission_date,
te_3rd_submission_date, acceptance_date_opt, acceptance_date_plan,
signed_sites, as_built_date, as_built_status, date_dt, dt_status,
shr_status, dt_planned, integeration_status, comments_snags, cluster_name,
type_standalone_colocated, installed_type_standalone_colocated, status,
pending, pending_status, problematic_details) VALUES (%s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s)]
[parameters: ('Manshyet Naser', 'Cairo', 'Existing', 'LCAIE10002',
'Manshyet nasser', datetime.datetime(2017, 7, 20, 0, 0), 'yes',
datetime.datetime(2017, 7, 23, 0, 0), datetime.datetime(2017, 9, 12, 0,
0), None, None, None, None, None, datetime.datetime(2017, 9, 17, 0, 0),
None, 'PAC Signed', None, 'Done', None, None, None, None, None, None, 'Mid
Cairo', 'L700+L1800', None, 'PAC Signed', None, None, None)]
(Background on this error at: http://sqlalche.me/e/e3q8)

and this is my sql query in php myadmin

 CREATE TABLE `mydb`.`govtracker` (
 `id` DOUBLE(255, 0) NOT NULL,
 `site_name` VARCHAR(255) NOT NULL,
 `region` VARCHAR(255) NOT NULL,
 `site_type` VARCHAR(255) NOT NULL,
 `site_code` VARCHAR(255) NOT NULL,
 `tac_name` VARCHAR(255) NOT NULL,
 `dt_readiness` DATE NOT NULL,
 `rfs` BOOLEAN NOT NULL,
 `rfs_date` DATE NOT NULL,
 `huawei_1st_submission_date` DATE NOT NULL,
 `te_1st_submission_date` DATE NOT NULL,
 `huawei_2nd_submission_date` DATE NOT NULL,
 `te_2nd_submission_date` DATE NOT NULL,
 `huawei_3rd_submission_date` DATE NOT NULL,
 `te_3rd_submission_date` DATE NOT NULL,
 `acceptance_date_opt` DATE NOT NULL,
 `acceptance_date_plan` DATE NOT NULL,
 `signed_sites` VARCHAR(255) NOT NULL,
 `as_built_date` DATE NOT NULL,
 `as_built_status` VARCHAR(255) NOT NULL,
 `date_dt` DATE NOT NULL,
 `dt_status` VARCHAR(255) NOT NULL,
 `shr_status` VARCHAR(255) NOT NULL,
 `dt_planned` INT(255) NOT NULL,
 `integeration_status` VARCHAR(255) NOT NULL,
 `comments_snags` LONGTEXT NOT NULL,
 `cluster_name` LONGTEXT NOT NULL,
 `type_standalone_colocated` VARCHAR(255) NOT NULL,
 `installed_type_standalone_colocated` VARCHAR(255) NOT NULL,
 `status` VARCHAR(255) NOT NULL,
 `pending` VARCHAR(255) NOT NULL,
 `pending_status` LONGTEXT NOT NULL,
 `problematic_details` LONGTEXT NOT NULL,
 `ets_tac` INT(255) NOT NULL,
 `region_r` VARCHAR(255) NOT NULL,
 `sf6_signed_date` DATE NOT NULL,
 `sf6_signed_comment` LONGTEXT NOT NULL,
 `comment_history` LONGTEXT NOT NULL,
 `on_air_owner` VARCHAR(255) NOT NULL,
 `pp_owner` VARCHAR(255) NOT NULL,
 `report_comment` LONGTEXT NOT NULL,
 `hu_opt_area_owner` VARCHAR(255) NOT NULL,
 `planning_owner` VARCHAR(255) NOT NULL,
 `po_number` VARCHAR(255) NOT NULL,
 `trigger_date` DATE NOT NULL,
 `as_built_status_tr` VARCHAR(255) NOT NULL
 ) ENGINE = InnoDB;

Body:
the error is clear  you have  a column  in your table named te_1st_submission_date  declared as

`te_1st_submission_date` DATE NOT NULL,

but you are trying to insert a null value for this column

1048, "Column 'te_1st_submission_date' cannot be null")

Probably your assignment

data_dict['te_1st_submission_date'] = df['TE 1st Response date '][i]

contain a null value

try add  a valid value  for this (and eventually other null values)


问:
How to get keyboard input in pygame?
I am making a game in pygame 1.9.2.
It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code:

keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    location-=1
    if location==-1:
        location=0
if keys[K_RIGHT]:
    location+=1
    if location==5:
        location=4
```

It works too well. The ship moves too fast. It is near impossible to have it move only one location, left or right. How can i make it so the ship only moves once every time the key is pressed?

答: To slow down your game, use pygame.clock.tick(10)

Title: How to get keyboard input in pygame?

Body:
I am making a game in pygame 1.9.2.
It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code:

keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    location-=1
    if location==-1:
        location=0
if keys[K_RIGHT]:
    location+=1
    if location==5:
        location=4

It works too well. The ship moves too fast. It is near impossible to have it move only one location, left or right. How can i make it so the ship only moves once every time the key is pressed?


问:
How to fix layers offsets when exporting all Photoshop groups to .pngs in a javascript script?
When I play the animation in photoshop, it looks fine. Every layer is in the correct position. When I run my script that saves each group to a png, the results have some layers offset.

I believe layers have weird issues with positions in animations. An image in a layer could have a different position in one frame and not another frame. I believe I'd have to get the script to step the frame in the animation to get the correct position, but I'm not sure how I would do that.

```<code>var set;
var layer;
var count = 0;
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = false;
    count ++;
}
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = true;

    // save
    var fileName = set.name.replace(/[\\\*\/\?:"\|<> ]/g,'');
    if(fileName.length ==0) fileName = "autoname";
    var handle = File(app.activeDocument.path + "/" + fileName + ".png");
    pngSaveOptions = new PNGSaveOptions();
    activeDocument.saveAs(handle, pngSaveOptions, true, Extension.LOWERCASE);

    set.visible = false;
}

alert("Saved " + count + " images.");
</code>```

The correct animation plays in photoshop. The resulting .pngs are incorrect.
https://imgur.com/a/y9PLPUX

答: If your animation is already in Photoshop timeline, maybe it's easier just to render the animation to frames? Go to File > Export > Render Video..., Chose Photoshop Image Sequence as a renderer, PNG as a format and in Render Options don't forget to select Straight Alpha Channel. This will render all frames to PNGs with transparency.

Body:
When I play the animation in photoshop, it looks fine. Every layer is in the correct position. When I run my script that saves each group to a png, the results have some layers offset.

I believe layers have weird issues with positions in animations. An image in a layer could have a different position in one frame and not another frame. I believe I'd have to get the script to step the frame in the animation to get the correct position, but I'm not sure how I would do that.

var set;
var layer;
var count = 0;
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = false;
    count ++;
}
for(var i = 0; i < app.activeDocument.layerSets.length; i ++)
{
    set = app.activeDocument.layerSets[i];
    set.visible = true;

    // save
    var fileName = set.name.replace(/[\\\*\/\?:"\|<> ]/g,'');
    if(fileName.length ==0) fileName = "autoname";
    var handle = File(app.activeDocument.path + "/" + fileName + ".png");
    pngSaveOptions = new PNGSaveOptions();
    activeDocument.saveAs(handle, pngSaveOptions, true, Extension.LOWERCASE);

    set.visible = false;
}

alert("Saved " + count + " images.");

The correct animation plays in photoshop. The resulting .pngs are incorrect.
https://imgur.com/a/y9PLPUX


问:
Regex splitting strings on a character, not contained in ()
I'm trying to split a string on a , where that character is not contained in ().

Example String:

```<code>`table1`.`lname`,`table1`.`fname`,if(foo is not null,foo,if(bar is not null,bar,table3.baz)),`table3`.`shu`
</code>```

I want to split it into an array looking like

```<code>(
  0=>`table1`.`lname`
  1=>`table1`.`fname`
  2=>if(foo is not null,foo,if(bar is not null,bar,table3.baz))
  3=>`table3`.`shu`
)
</code>```

Any ideas on how to tackle this problem?

--
Dave

答:
Regex isn't very good at this.  Consider the following snippet:

(a)b(c(d)e)

Where each letter represents a comma (your search target).  Based on your question, you would only want to match comma b. The trick is that expressions are generally either greedy or not greedy, with no middle ground.

A greedy expression would see the ( at the very beginning of the segment and the ) at the very end and take everything inside them, regardless that there are closing parentheses elsewhere. Nothing would be matched.

An ungreedy expression would take only the smallest set possible, starting from the beginning.  It would match comma b, but also see this segment as one unit: (c(d) and then proceed to also match comma e.

There are some engines that allow you to count nesting levels, but the expressions are usually ugly and hard to maintain: best to just avoid the feature unless you really understand it well.

OwnerDisplayName: david walker

LastEditorDisplayName: Lawrence Johnston

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to split a string on a , where that character is not contained in ().

Example String:

`table1`.`lname`,`table1`.`fname`,if(foo is not null,foo,if(bar is not null,bar,table3.baz)),`table3`.`shu`

I want to split it into an array looking like

(
  0=>`table1`.`lname`
  1=>`table1`.`fname`
  2=>if(foo is not null,foo,if(bar is not null,bar,table3.baz))
  3=>`table3`.`shu`
)

Any ideas on how to tackle this problem?

--
Dave

OwnerDisplayName: Joel Coehoorn


问:
how to exclude resources from being copied within Intellij?
When I'm doing a build intellij, I get errors due to emacs creating temporary files that are not able to be packaged

```<code>Error:Maven Resources Compiler: Failed to copy '... /.#env_app.clj'
</code>```

Is there any way to exclude the .# files from intellij?

答:
In IDE, the compiler excludes are configured in Settings(Preferences) | Build, Execution, Deployment | Compiler | Excludes settings page.

But if it is a Maven-based project, the compiler excludes (as other build-related options) must be configured via pom.xml files:

```<code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.8.1</version>
  <configuration>
    <excludes>
      <exclude>**/.#*</exclude>
    </excludes>
  </configuration>
</plugin>
</code>```

Body:
When I'm doing a build intellij, I get errors due to emacs creating temporary files that are not able to be packaged

Error:Maven Resources Compiler: Failed to copy '... /.#env_app.clj'

Is there any way to exclude the .# files from intellij?

Body:
In IDE, the compiler excludes are configured in Settings(Preferences) | Build, Execution, Deployment | Compiler | Excludes settings page.

But if it is a Maven-based project, the compiler excludes (as other build-related options) must be configured via pom.xml files:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.8.1</version>
  <configuration>
    <excludes>
      <exclude>**/.#*</exclude>
    </excludes>
  </configuration>
</plugin>


问:
arising from a use of `Control.Exception.catch'
When i load a haskell file, it has error</p>

```<code>module REPL(REPL(..), repl) where
import qualified Control.Exception as E
import System.Console.Readline(readline, addHistory)

data REPL s = REPL {
    repl_init :: IO (String, s),        -- prompt and initial state
    repl_eval :: s -> String -> IO (Bool, s),       -- quit flag and new state
    repl_exit :: s -> IO ()
    }

repl :: REPL s -> IO ()
repl p = do
    (prompt, state) <- repl_init p
    let loop s = (do
        mline <- readline prompt
        case mline of
        Nothing -> loop s
        Just line -> do
            (quit, s') <- repl_eval p s line
            if quit then
            repl_exit p s'
             else do
            addHistory line
            loop s'
        ) E.catch undefined (\(e :: E.SomeException) -> putStrLn "Handled exception!"
        )
    loop state

REPL.hs:21:5:
    Couldn't match expected type `IO (Maybe String)'
           against inferred type `t -> Maybe String'
    In a stmt of a 'do' expression: mline <- readline prompt
    In the expression:
        (do { mline <- readline prompt;
              case mline of {
                Nothing -> loop s
                Just line
                  -> do { (quit, s') <- repl_eval p s line;
                          .... } } })
          E.catch
          undefined
          (\ (e :: E.SomeException) -> putStrLn "Handled exception!")
    In the definition of `loop':
        loop s = (do { mline <- readline prompt;
                       case mline of {
                         Nothing -> loop s
                         Just line -> do { ... } } })
                   E.catch
                   undefined
                   (\ (e :: E.SomeException) -> putStrLn "Handled exception!")
</code>```

答:
It would help to see the actual code that's giving you trouble, but please see the below for an example of the problem you describe and solution to the example by adding a type signature.  In ghci:

```<code>> :m + Control.Exception
> print "hello world" `Control.Exception.catch` (\_ -> print "goodby world")

<interactive>:1:21:
    Ambiguous type variable `e' in the constraint:
      (Exception e) arising from a use of `Control.Exception.catch'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression:
        print "hello world"
      `Control.Exception.catch`
        (\ _ -> print "goodby world")
    In an equation for `it':
        it
          = print "hello world"
          `Control.Exception.catch`
            (\ _ -> print "goodby world")
> print "hello world" `Control.Exception.catch` ((\_ -> print "goodby world") :: IOException -> IO ())
"hello world"
</code>```

The point is that the catch expression (\_ -> print "goodby world") doesn't constrain the type of its argument.  I expect you're have a similar problem.

ContentLicense: CC BY-SA 3.0

Body:
When i load a haskell file, it has error

module REPL(REPL(..), repl) where
import qualified Control.Exception as E
import System.Console.Readline(readline, addHistory)

data REPL s = REPL {
    repl_init :: IO (String, s),        -- prompt and initial state
    repl_eval :: s -> String -> IO (Bool, s),       -- quit flag and new state
    repl_exit :: s -> IO ()
    }

repl :: REPL s -> IO ()
repl p = do
    (prompt, state) <- repl_init p
    let loop s = (do
        mline <- readline prompt
        case mline of
        Nothing -> loop s
        Just line -> do
            (quit, s') <- repl_eval p s line
            if quit then
            repl_exit p s'
             else do
            addHistory line
            loop s'
        ) E.catch undefined (\(e :: E.SomeException) -> putStrLn "Handled exception!"
        )
    loop state

REPL.hs:21:5:
    Couldn't match expected type `IO (Maybe String)'
           against inferred type `t -> Maybe String'
    In a stmt of a 'do' expression: mline <- readline prompt
    In the expression:
        (do { mline <- readline prompt;
              case mline of {
                Nothing -> loop s
                Just line
                  -> do { (quit, s') <- repl_eval p s line;
                          .... } } })
          E.catch
          undefined
          (\ (e :: E.SomeException) -> putStrLn "Handled exception!")
    In the definition of `loop':
        loop s = (do { mline <- readline prompt;
                       case mline of {
                         Nothing -> loop s
                         Just line -> do { ... } } })
                   E.catch
                   undefined
                   (\ (e :: E.SomeException) -> putStrLn "Handled exception!")

Body:
It would help to see the actual code that's giving you trouble, but please see the below for an example of the problem you describe and solution to the example by adding a type signature.  In ghci:

> :m + Control.Exception
> print "hello world" `Control.Exception.catch` (\_ -> print "goodby world")

<interactive>:1:21:
    Ambiguous type variable `e' in the constraint:
      (Exception e) arising from a use of `Control.Exception.catch'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression:
        print "hello world"
      `Control.Exception.catch`
        (\ _ -> print "goodby world")
    In an equation for `it':
        it
          = print "hello world"
          `Control.Exception.catch`
            (\ _ -> print "goodby world")
> print "hello world" `Control.Exception.catch` ((\_ -> print "goodby world") :: IOException -> IO ())
"hello world"

The point is that the catch expression (\_ -> print "goodby world") doesn't constrain the type of its argument.  I expect you're have a similar problem.


问:
How to save max duration with sharedpref in flutter?
I tried to save duration with sharedpreference only if my last duration is superior to the current duration and so show the MAX duration. my problem is that I don't know how to compare two string duration.

here is the code thanks (@ZeRj)

```<code>  load_lastPressString()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

      final lastPressString = prefs.getString("lastButtonPress");
      _lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
      _updateTimer();
      _ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
    });
  }

  save_lastPressString()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setString('_lastButtonPress', _lastButtonPress.toIso8601String());
    });
  }

  void _updateTimer() {
    final duration = DateTime.now().difference(_lastButtonPress);
    final newDuration = _formatDuration(duration);
    setState(() {
      _pressDuration = newDuration;
    });
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inDays)}:${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";

  }
</code>```

I tried the code bellow, but I can't use > with string and tried to parse int but not possible with date, and I tried to extract each decimal with regex but it's to complicated and I have errors I havn't understand.

```<code>  save_max_lastPress()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

if(_lastButtonPress>Max_lastButtonPress)
               {
        prefs.setString('_max_lastPress', Max_lastButtonPress)    ;

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

答:
For that you have to save the maximal as the duration.

Use prefs.setInt("maxDuration",maxDuration.toSeconds()) to save it as a int in shared preferences and load it with

```<code>Duration(seconds: prefs.getInt("maxDuration")
</code>```

You can simply compare two instances of Duration.

I edited the last example to implement this feature:

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutterfly/SharedPrefs.dart';
import 'package:flutterfly/SharedPrefs.dart' as prefix0;

class TestWidget extends StatefulWidget {
  @override
  _TestWidgetState createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {
  DateTime _lastButtonPress;
  String _pressDuration;
  Timer _ticker;
  Duration _maxDuration;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("Time since button pressed"),
          Text(_pressDuration),
          Text("Maximal Duration"),
          Text(_formatDuration(_maxDuration)),
          RaisedButton(
            child: Text("Press me"),
            onPressed: () {
              _lastButtonPress = DateTime.now();
              _updateTimer();
              sharedPreferences.setString("lastButtonPress",_lastButtonPress.toIso8601String());
            },
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    //load max duration, if there is none start with 0
    _maxDuration = Duration(seconds:sharedPreferences.getInt("maxDuration")??0);
    final lastPressString = sharedPreferences.getString("lastButtonPress");
    _lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
    _updateTimer();
    _ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
  }

  @override
  void dispose() {
    _ticker.cancel();
    super.dispose();
  }

  void _updateTimer() {
    final duration = DateTime.now().difference(_lastButtonPress);
    //check for new max duration here
    Duration newMaxDuration = _maxDuration;
    if(duration> _maxDuration) {
      //save when current duration is a new max
      newMaxDuration = duration;
      sharedPreferences.setInt("maxDuration",newMaxDuration.inSeconds);
    }
    final newDuration =_formatDuration(duration);
    setState(() {
      _maxDuration = newMaxDuration;
      _pressDuration = newDuration;
    });
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }
}
</code>```

Body:
I tried to save duration with sharedpreference only if my last duration is superior to the current duration and so show the MAX duration. my problem is that I don't know how to compare two string duration.

here is the code thanks (@ZeRj)

  load_lastPressString()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

      final lastPressString = prefs.getString("lastButtonPress");
      _lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
      _updateTimer();
      _ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
    });
  }

  save_lastPressString()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      prefs.setString('_lastButtonPress', _lastButtonPress.toIso8601String());
    });
  }

  void _updateTimer() {
    final duration = DateTime.now().difference(_lastButtonPress);
    final newDuration = _formatDuration(duration);
    setState(() {
      _pressDuration = newDuration;
    });
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inDays)}:${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";

  }

I tried the code bellow, but I can't use > with string and tried to parse int but not possible with date, and I tried to extract each decimal with regex but it's to complicated and I have errors I havn't understand.

  save_max_lastPress()async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {

if(_lastButtonPress>Max_lastButtonPress)
               {
        prefs.setString('_max_lastPress', Max_lastButtonPress)    ;

           }
       }
     );
  }

Body:
For that you have to save the maximal as the duration.

Use prefs.setInt("maxDuration",maxDuration.toSeconds()) to save it as a int in shared preferences and load it with

Duration(seconds: prefs.getInt("maxDuration")

You can simply compare two instances of Duration.

I edited the last example to implement this feature:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutterfly/SharedPrefs.dart';
import 'package:flutterfly/SharedPrefs.dart' as prefix0;

class TestWidget extends StatefulWidget {
  @override
  _TestWidgetState createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {
  DateTime _lastButtonPress;
  String _pressDuration;
  Timer _ticker;
  Duration _maxDuration;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("Time since button pressed"),
          Text(_pressDuration),
          Text("Maximal Duration"),
          Text(_formatDuration(_maxDuration)),
          RaisedButton(
            child: Text("Press me"),
            onPressed: () {
              _lastButtonPress = DateTime.now();
              _updateTimer();
              sharedPreferences.setString("lastButtonPress",_lastButtonPress.toIso8601String());
            },
          )
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    //load max duration, if there is none start with 0
    _maxDuration = Duration(seconds:sharedPreferences.getInt("maxDuration")??0);
    final lastPressString = sharedPreferences.getString("lastButtonPress");
    _lastButtonPress = lastPressString!=null ? DateTime.parse(lastPressString) : DateTime.now();
    _updateTimer();
    _ticker = Timer.periodic(Duration(seconds:1),(_)=>_updateTimer());
  }

  @override
  void dispose() {
    _ticker.cancel();
    super.dispose();
  }

  void _updateTimer() {
    final duration = DateTime.now().difference(_lastButtonPress);
    //check for new max duration here
    Duration newMaxDuration = _maxDuration;
    if(duration> _maxDuration) {
      //save when current duration is a new max
      newMaxDuration = duration;
      sharedPreferences.setInt("maxDuration",newMaxDuration.inSeconds);
    }
    final newDuration =_formatDuration(duration);
    setState(() {
      _maxDuration = newMaxDuration;
      _pressDuration = newDuration;
    });
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }
}


问:
How to pass different types as struct{} to function in GoLang?
I want to write a function that takes different struct-types as 1 parameter. Also, I have to be sure, that in these structs is an Id field. So I want a function like this:

```<code>MyFunction(object *struct{ Id int })
</code>```

I tried it with passing the struct as a *struct{ Id int } and an interface{} parameter.

For example, I have these 2 struct-types:

```<code>type TableOne struct {
    Id   int
    name string
    date string
}

type TableTwo struct {
    Id      int
    address string
    athome  bool
}
</code>```

To save them in the database (using reflection) I have the following function:

```<code>func SaveMyTables(tablename string, obj *struct{ Id int }) {
    // ... Some code here

    if obj.Id != 0 {
        // ... Some code here
    }

    // ... Some code here
}
</code>```

I call the function like this:

```<code>obj := &TableTwo{
    Id: 5
    address: "some address"
    athome: false
}

myPackage.Save("addresses", obj).
</code>```

But I get this error:

cannot use obj (type *mytables.TableTwo) as type *struct { Id int } in argument to myPackage.Save

答:
I want to write a function that takes different struct-types as 1 parameter. Also, I have to get sure, that in these struct is an Id field.

As of the current version of Go, you cannot do this. The only way Go supports passing multiple argument types to a single parameter is through the use of interfaces, and interfaces can only specify method sets, not fields.

(Go 2 plans to add generics, and this may be possible then. However, there's no concrete timeline for when that will be available.)

Body:
I want to write a function that takes different struct-types as 1 parameter. Also, I have to be sure, that in these structs is an Id field. So I want a function like this:

MyFunction(object *struct{ Id int })

I tried it with passing the struct as a *struct{ Id int } and an interface{} parameter.

For example, I have these 2 struct-types:

type TableOne struct {
    Id   int
    name string
    date string
}

type TableTwo struct {
    Id      int
    address string
    athome  bool
}

To save them in the database (using reflection) I have the following function:

func SaveMyTables(tablename string, obj *struct{ Id int }) {
    // ... Some code here

    if obj.Id != 0 {
        // ... Some code here
    }

    // ... Some code here
}

I call the function like this:

obj := &TableTwo{
    Id: 5
    address: "some address"
    athome: false
}

myPackage.Save("addresses", obj).

But I get this error:

cannot use obj (type *mytables.TableTwo) as type *struct { Id int } in argument to myPackage.Save


问:
how to format django models?
I'm having trouble understanding the formatting of django, my project is this, can anyone help me ?? I would like the Admin to have the function of the user inserting the images there. Thank you.

HOME:

```<code>{% for picture in photos %}
          <div><img> src="{{picture.pic}}"</img></div>
{% endfor %}
</code>```

MODELS:

```<code>class Photos(models.Model):
    pic = models.ImageField(upload_to='images')

    def __str__ (self):
        return self.pic
</code>```

VIEWS:

```<code>...
picture = Photos.objects.all()
    return render(request, 'home.html', {'photos':picture})
</code>```

答:
change this line

```<code>  <div><img> src="{{picture.pic}}"</img></div>
</code>```

to

```<code>  <div><img> src="{{picture.pic.url}}"</img></div>
</code>```

Title: how to format django models?

Body:
I'm having trouble understanding the formatting of django, my project is this, can anyone help me ?? I would like the Admin to have the function of the user inserting the images there. Thank you.

HOME:

{% for picture in photos %}

 src="{{picture.pic}}"

{% endfor %}

MODELS:

class Photos(models.Model):
    pic = models.ImageField(upload_to='images')

    def __str__ (self):
        return self.pic

VIEWS:

...
picture = Photos.objects.all()
    return render(request, 'home.html', {'photos':picture})

Body:
change this line

  <div><img> src="{{picture.pic}}"</img></div>

to

  <div><img> src="{{picture.pic.url}}"</img></div>


问:
How to add two numbers using only pointer variables such as int *a,*b,*add;
I am getting a problem with pointers in 32-bit architecture.I want to add two numbers using only pointer variables for ex: int *a,*b,*add; but in 32-bit based compiler such as codeblocks doesn't giving the ouptut.

But in case of 16-bit based compiler such as turbo c++ it is working properly.

This is the code that I've tried

```<code>int *a,*b,*add;
printf("Enter two no.");
scanf("%d%d",a,b);
*add=*a+*b;
</code>```

in code block it is returning nothing .
but in turbo c ++ it is working properly.

答:
scanf("%d%d",a,b); tells scanf to read numerals from input and write their values to the places in memory where a and b point. But a and b do not properly point to anywhere because you did not initialize them. Neither their definition in int *a,*b,*add; nor their use in scanf sets a value for where they point to.

To make a, b, or add point to an actual int object, you must define or allocate an int object and then assign its address to a, b, or add.

For example, you can use:

```<code>int x, y, z;
int *a = x, *b = y, *add = z;
</code>```

Or:

```<code>int *a, *b, *add;
a = malloc(sizeof *a);
b = malloc(sizeof *b);
add = malloc(sizeof *add);
if (!a || !b || !c)
{
    fprintf(stderr, "Error, memory allocation failed.\n");
    exit(EXIT_FAILURE); // Include <stdlib.h> for this.
}
</code>```

If your code “works” in Turbo C++, it may be because the uninitialized a, b, and add take on values that happen to be in memory that happened to point to usable memory. This is not reliable behavior, and it could easily break if any changes are made to the program. Always initialize pointers and other objects before you use them.

When you are done using memory allocated with malloc, you should generally release it, which you can do with free:

```<code>free(add);
free(b);
free(a);
</code>```

Body:
I am getting a problem with pointers in 32-bit architecture.I want to add two numbers using only pointer variables for ex: int *a,*b,*add; but in 32-bit based compiler such as codeblocks doesn't giving the ouptut.

But in case of 16-bit based compiler such as turbo c++ it is working properly.

This is the code that I've tried

int *a,*b,*add;
printf("Enter two no.");
scanf("%d%d",a,b);
*add=*a+*b;

in code block it is returning nothing .
but in turbo c ++ it is working properly.

Body:
scanf("%d%d",a,b); tells scanf to read numerals from input and write their values to the places in memory where a and b point. But a and b do not properly point to anywhere because you did not initialize them. Neither their definition in int *a,*b,*add; nor their use in scanf sets a value for where they point to.

To make a, b, or add point to an actual int object, you must define or allocate an int object and then assign its address to a, b, or add.

For example, you can use:

int x, y, z;
int *a = x, *b = y, *add = z;

Or:

int *a, *b, *add;
a = malloc(sizeof *a);
b = malloc(sizeof *b);
add = malloc(sizeof *add);
if (!a || !b || !c)
{
    fprintf(stderr, "Error, memory allocation failed.\n");
    exit(EXIT_FAILURE); // Include <stdlib.h> for this.
}

If your code “works” in Turbo C++, it may be because the uninitialized a, b, and add take on values that happen to be in memory that happened to point to usable memory. This is not reliable behavior, and it could easily break if any changes are made to the program. Always initialize pointers and other objects before you use them.

When you are done using memory allocated with malloc, you should generally release it, which you can do with free:

free(add);
free(b);
free(a);


问:
Angular values are not reflecting in view
Angular values are not reflecting in view

HTML

```<code><div class="col-md-6 cardexpiry-block" [ngClass]="{'cardexpiry-block-remove':!!hasCardExpiryDate}"><!-- -->
    <div class="col-sm-6 text-left"><label for="CardExpiry">Card Expiry</label></div>
    <div class="col-md-3 text-left d-inline-flex"> <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(true)">
        Yes </div>
    <div class="col-md-3 text-left d-inline-flex"> <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(false)"
            checked> No</div>
    <my-date-picker *ngIf="!!hasCardExpiryDate" name="CardExpiry" [options]="myDatePickerOptions"
        formControlName="expiryDate"></my-date-picker>
</div>
</code>```

TS Code:

```<code>hasCardExpiryDate : boolean = false;

hasCardExpiry(falg){
    this.hasCardExpiryDate = falg;
}
</code>```

When I toggle between Yes and No, the values if "hasCardExpiryDate" is not changing
when i check-in HTML using  {{ hasCardExpiryDate | json }}

答:
You need to set ngModel and value

```<code><input name="hasCardExpiry" type="radio" [value]="true" [(ngModel)]="hasCardExpiryDate" (click)="hasCardExpiry(true)"> Yes

<input name="hasCardExpiry" type="radio" [value]="false" [(ngModel)]="hasCardExpiryDate" (click)="hasCardExpiry(true)" checked> No
</code>```

Body:
Angular values are not reflecting in view

HTML

Card Expiry

 <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(true)">
        Yes

 <input name="hasCardExpiry" type="radio" (click)="hasCardExpiry(false)"
            checked> No

    <my-date-picker *ngIf="!!hasCardExpiryDate" name="CardExpiry" [options]="myDatePickerOptions"
        formControlName="expiryDate"></my-date-picker>

TS Code:

hasCardExpiryDate : boolean = false;

hasCardExpiry(falg){
    this.hasCardExpiryDate = falg;
}

When I toggle between Yes and No, the values if "hasCardExpiryDate" is not changing
when i check-in HTML using  {{ hasCardExpiryDate | json }}

Body:
You need to set ngModel and value

<input name="hasCardExpiry" type="radio" [value]="true" [(ngModel)]="hasCardExpiryDate" (click)="hasCardExpiry(true)"> Yes

<input name="hasCardExpiry" type="radio" [value]="false" [(ngModel)]="hasCardExpiryDate" (click)="hasCardExpiry(true)" checked> No


问:
What is a TransientTransactionError in Mongoose (or MongoDB)?
I have server.js and db.js The db.js file interacts with my database using Mongoose and I use server.js to call functions from db.js :

```<code>var mongoose = require('mongoose');
mongoose.connect('', { useNewUrlParser: true })
var Schema = mongoose.Schema;

module.exports = function () {
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    return db.once('open', function() {
        console.log("Connected to DB")
        var postschema = new Schema({
            title: String,
            intro: String,
            body: String,
            author: String,
            timestamp: { type: Date, default: Date.now }
        });

        var post = mongoose.model('post', postschema);

        return {
            newPost(title, intro, body, author) {
                var newpost = new post({
                    title: title,
                    intro: intro,
                    body: body,
                    author: author
                })
            },
            getPostsAll() {
                post.find({}, function (err, res) {
                    return (`Error:${err} Posts:${res}`)
                })
            }
        }
    })
}
</code>```

And my server.js calls three functions from db.js :

```<code>var DB = require('./db.js')
var db = DB()
db.getPostsAll()
db.newPost()
</code>```

I don't understand why I get this error :

```<code>connection error: { MongoNetworkError: connection 4 to black-test-shard-00-01-ewyaf.mongodb.net:27017 closed
at TLSSocket.<anonymous> (E:\HTML\black-box\node_modules\mongodb-core\lib\connection\connection.js:276:9)
at Object.onceWrapper (events.js:272:13)
at TLSSocket.emit (events.js:185:15)
at _handle.close (net.js:541:12)
at TCP.done [as _onclose] (_tls_wrap.js:379:7)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }
</code>```

What am I doing wrong? I found an article but can't make anything of it.

答:
You can read about the error online but the solution for this problem is: go to you MongoDB atlas and add your IP address.

Go to:
main page > security section > network access > add IP

This problem is basically when the architecture do not know your own IP address.

Also, copy-paste directly to google to get straight forward solution.

Body:
I have server.js and db.js The db.js file interacts with my database using Mongoose and I use server.js to call functions from db.js :

var mongoose = require('mongoose');
mongoose.connect('', { useNewUrlParser: true })
var Schema = mongoose.Schema;

module.exports = function () {
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    return db.once('open', function() {
        console.log("Connected to DB")
        var postschema = new Schema({
            title: String,
            intro: String,
            body: String,
            author: String,
            timestamp: { type: Date, default: Date.now }
        });

        var post = mongoose.model('post', postschema);

        return {
            newPost(title, intro, body, author) {
                var newpost = new post({
                    title: title,
                    intro: intro,
                    body: body,
                    author: author
                })
            },
            getPostsAll() {
                post.find({}, function (err, res) {
                    return (`Error:${err} Posts:${res}`)
                })
            }
        }
    })
}

And my server.js calls three functions from db.js :

var DB = require('./db.js')
var db = DB()
db.getPostsAll()
db.newPost()

I don't understand why I get this error :

connection error: { MongoNetworkError: connection 4 to black-test-shard-00-01-ewyaf.mongodb.net:27017 closed
at TLSSocket.<anonymous> (E:\HTML\black-box\node_modules\mongodb-core\lib\connection\connection.js:276:9)
at Object.onceWrapper (events.js:272:13)
at TLSSocket.emit (events.js:185:15)
at _handle.close (net.js:541:12)
at TCP.done [as _onclose] (_tls_wrap.js:379:7)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }

What am I doing wrong? I found an article but can't make anything of it.


问:
multiple belongs_to relationship to three model
The situation is this way..

```<code>class Organization < ActiveRecord::Base

  has_many :role_memberships
  has_many :roles
  has_many :users, :through => :role_memberships, :uniq => true

end

class User

 has_many :role_memberships
  has_many :organizations, :through => :role_memberships, :uniq => true
  has_many :roles, :through => :role_memberships, :uniq => true

end

class RoleMembership < ActiveRecord::Base

  belongs_to :organization
  belongs_to :role
  belongs_to :user

end

class Role < ActiveRecord::Base
  belongs_to :organization
  has_many :role_memberships
  has_many :users, :through => :role_memberships, :uniq => true
end
</code>```

The QUESTION is how do I populate all the three foreign-keys in rolemembership table..when I do org.users.push(u) this create a record but role_id is left out...

答:
In this case I will probably create RoleMembership object itself, like this:</p>

```<code>RoleMembership.create(:organization_id => org.id, :role_id => role.id, :user_id => user.id)
</code>```

Body:
The situation is this way..

class Organization < ActiveRecord::Base

  has_many :role_memberships
  has_many :roles
  has_many :users, :through => :role_memberships, :uniq => true

end

class User

 has_many :role_memberships
  has_many :organizations, :through => :role_memberships, :uniq => true
  has_many :roles, :through => :role_memberships, :uniq => true

end

class RoleMembership < ActiveRecord::Base

  belongs_to :organization
  belongs_to :role
  belongs_to :user

end

class Role < ActiveRecord::Base
  belongs_to :organization
  has_many :role_memberships
  has_many :users, :through => :role_memberships, :uniq => true
end

The QUESTION is how do I populate all the three foreign-keys in rolemembership table..when I do org.users.push(u) this create a record but role_id is left out...

Body:
In this case I will probably create RoleMembership object itself, like this:

RoleMembership.create(:organization_id => org.id, :role_id => role.id, :user_id => user.id)


问:
React Data Grid rows disappearing on dynamically providing height
I am trying to make RDG Table which can be expanded(for expansion i have used ReactGridLayout) in height & Width. I am using react-sizeme for dynamically providing height & Width to my component(in my case Example component). Now, Table is getting expanded in height & Width correctly when scrollbar in table is at top.
Below image shows Table with scrollbar at top:

If i expand table, everything will work correctly as in below image:

As soon as we bring Scrollbar somewhat in between and then expand table's height, rows are getting disappeared. These rows become visible as soon as i scroll by just a small amount in table.
For e.g. In below image, Scrollbar is in not in beginning(row6 is visible).

Now if i expand table, some rows are getting disappeared as shown in below image:

I am unable to understand why rows are getting disappeared on expansion when scrollbar is not in beginning.

CodeSandbox Link: https://codesandbox.io/embed/rdg-optimising-scrolling-n6xpj

Edit: Table contains 199 rows currently.

答:
When scrollbar is in between and component is resized(by increasing height), RDG will not know that it has to render new rows to fill empty rows created by increasing height. That's why as soon as, i scroll manually by just a small amount, RDG will know that it has to render new rows and everything will work fine.

So, now problem was reduced to making RDG understand that it has to render new rows.

For this, i kept key: Math.random() in state and passed this key to RDG as prop.
On resizing, i am checking if new height is not equal to previous height and if so, update key in state which will re-render entire RDG.

I know this is not efficient solution but it won't matter since i will have max 200 rows.

Working Code: https://codesandbox.io/embed/rdg-optimising-scrolling-pgso9

Edit(24-08-2019):
Above mentioned code will bring scroll position to always at top because we are creating entirely new table everytime there is change in height. So, i tried keeping scroll position at the same place and arrived at more optimised code.

First of all, i removed key from state because it is no longer required.
Then, in scroll callback function, i saved scrollTop position in state.

Now once there is any change in height, 2 things are required to be done:

```<code>1. Scroll to `zeroth` row.
2. Scroll to `scrollTop`.
Point 1 is required so that RDG can be made aware that their was change in height.
This way it will render additional rows to fill entire table.
</code>```

Code is present here: https://codesandbox.io/s/rdg-optimising-scrolling-7lvdv

Body:
When scrollbar is in between and component is resized(by increasing height), RDG will not know that it has to render new rows to fill empty rows created by increasing height. That's why as soon as, i scroll manually by just a small amount, RDG will know that it has to render new rows and everything will work fine.

So, now problem was reduced to making RDG understand that it has to render new rows.

For this, i kept key: Math.random() in state and passed this key to RDG as prop.
On resizing, i am checking if new height is not equal to previous height and if so, update key in state which will re-render entire RDG.

I know this is not efficient solution but it won't matter since i will have max 200 rows.

Working Code: https://codesandbox.io/embed/rdg-optimising-scrolling-pgso9

Edit(24-08-2019):
Above mentioned code will bring scroll position to always at top because we are creating entirely new table everytime there is change in height. So, i tried keeping scroll position at the same place and arrived at more optimised code.

First of all, i removed key from state because it is no longer required.
Then, in scroll callback function, i saved scrollTop position in state.

Now once there is any change in height, 2 things are required to be done:

1. Scroll to `zeroth` row.
2. Scroll to `scrollTop`.
Point 1 is required so that RDG can be made aware that their was change in height.
This way it will render additional rows to fill entire table.

Code is present here: https://codesandbox.io/s/rdg-optimising-scrolling-7lvdv


问:
Restore minimized window of another, suspended application
I am trying to restore a minimized, suspended UWP application from another application,
but I cant manage to find a workable solution.

Using .NET Core 2.2 and win32 API via PInvoke

I have tried setting the window placement, setting the window position but nothing works. The only reason I find is that the process that I want to restore is suspended.
I did some research and the app is a UWP which is managed by the WinRT stack. sadly I cant find a way to resume the process and display it

Every help or suggestion is appreciated.

```<code>        Process proc = Process.GetProcessesByName("HxOutlook").FirstOrDefault();

        if (proc != null)
        {
            ShowWindow(proc.MainWindowHandle, SW_SHOWNORMAL);   // Make the window visible if it was hidden
            ShowWindow(proc.MainWindowHandle, SW_RESTORE);      // Next, restore it if it was minimized
            SetForegroundWindow(proc.MainWindowHandle);         // Finally, activate the window
        }
</code>```

答:
The Issue wasn't in the fact that the process was suspended but that I couldn't get the correct window handle via the C# API (System.Diagnostics.Process). All credit goes to jwezorek, this is the C# implementation. (It has issues, but it works)</p>

```<code>    static UInt32 GetProccessByName(string targetProcessName)
    {
        UInt32[] processes = new UInt32[1024];
        UInt32 bytesCopied;

        if (!Psapi.EnumProcesses(processes, (UInt32)processes.Length, out bytesCopied))
        {
            return 0;
        }

        foreach (var pid in processes)
        {
            IntPtr handle = Kernel32.OpenProcess(
              (Kernel32.ProcessAccessFlags.QueryInformation |
                Kernel32.ProcessAccessFlags.VirtualMemoryRead),
                false,
                (int)pid);

            UInt32[] modules = new UInt32[1024];
            UInt32 bytesNeeeded;

            if (handle != null)
            {
                if (Psapi.EnumProcessModules(handle, modules, (UInt32)modules.Length, out bytesNeeeded))
                {
                    StringBuilder text = new StringBuilder(1024);
                    Psapi.GetModuleBaseName(handle, IntPtr.Zero, text, (UInt32)text.Capacity);

                    if (text.Equals(targetProcessName))
                    {
                        return pid;
                    }
                }
            }
        }

        return 0;
    }

    public static bool EnumProc(IntPtr hWnd, ref SearchData data)
    {
        UInt32 pid;

        User32.GetWindowThreadProcessId(hWnd, out pid);

        if(pid == data.PID)
        {
            data.Windows.Add(hWnd);
        }

        return true;
    }

    static List<IntPtr> GetWindowFromProcessID(UInt32 pid)
    {
        var searchData = new SearchData(pid);

        User32.EnumWindows(new User32.EnumWindowsProc(EnumProc), ref searchData);

        return searchData.Windows;
    }

    static void Main(string[] args)
    {
        var pid = GetProccessByName("HxOutlook.exe");

        var windows = GetWindowFromProcessID(pid);

        foreach (var window in windows)
        {
            var owner = User32.GetWindow(window, User32.GetWindowType.GW_OWNER);
            if(owner != null)
            {
                User32.ShowWindow(owner, SW_RESTORE);
            }
        }
    }
</code>```

Body:
I am trying to restore a minimized, suspended UWP application from another application,
but I cant manage to find a workable solution.

Using .NET Core 2.2 and win32 API via PInvoke

I have tried setting the window placement, setting the window position but nothing works. The only reason I find is that the process that I want to restore is suspended.
I did some research and the app is a UWP which is managed by the WinRT stack. sadly I cant find a way to resume the process and display it

Every help or suggestion is appreciated.

        Process proc = Process.GetProcessesByName("HxOutlook").FirstOrDefault();

        if (proc != null)
        {
            ShowWindow(proc.MainWindowHandle, SW_SHOWNORMAL);   // Make the window visible if it was hidden
            ShowWindow(proc.MainWindowHandle, SW_RESTORE);      // Next, restore it if it was minimized
            SetForegroundWindow(proc.MainWindowHandle);         // Finally, activate the window
        }

Body:
The Issue wasn't in the fact that the process was suspended but that I couldn't get the correct window handle via the C# API (System.Diagnostics.Process). All credit goes to jwezorek, this is the C# implementation. (It has issues, but it works)

    static UInt32 GetProccessByName(string targetProcessName)
    {
        UInt32[] processes = new UInt32[1024];
        UInt32 bytesCopied;

        if (!Psapi.EnumProcesses(processes, (UInt32)processes.Length, out bytesCopied))
        {
            return 0;
        }

        foreach (var pid in processes)
        {
            IntPtr handle = Kernel32.OpenProcess(
              (Kernel32.ProcessAccessFlags.QueryInformation |
                Kernel32.ProcessAccessFlags.VirtualMemoryRead),
                false,
                (int)pid);

            UInt32[] modules = new UInt32[1024];
            UInt32 bytesNeeeded;

            if (handle != null)
            {
                if (Psapi.EnumProcessModules(handle, modules, (UInt32)modules.Length, out bytesNeeeded))
                {
                    StringBuilder text = new StringBuilder(1024);
                    Psapi.GetModuleBaseName(handle, IntPtr.Zero, text, (UInt32)text.Capacity);

                    if (text.Equals(targetProcessName))
                    {
                        return pid;
                    }
                }
            }
        }

        return 0;
    }

    public static bool EnumProc(IntPtr hWnd, ref SearchData data)
    {
        UInt32 pid;

        User32.GetWindowThreadProcessId(hWnd, out pid);

        if(pid == data.PID)
        {
            data.Windows.Add(hWnd);
        }

        return true;
    }

    static List<IntPtr> GetWindowFromProcessID(UInt32 pid)
    {
        var searchData = new SearchData(pid);

        User32.EnumWindows(new User32.EnumWindowsProc(EnumProc), ref searchData);

        return searchData.Windows;
    }

    static void Main(string[] args)
    {
        var pid = GetProccessByName("HxOutlook.exe");

        var windows = GetWindowFromProcessID(pid);

        foreach (var window in windows)
        {
            var owner = User32.GetWindow(window, User32.GetWindowType.GW_OWNER);
            if(owner != null)
            {
                User32.ShowWindow(owner, SW_RESTORE);
            }
        }
    }


问:
How to pretty-print an AST using Visitor pattern?
I am trying to build a simple interpreter using the Visitor pattern. I'm having a difficult time trying to understand how a task such as pretty-printing the tree can be implemented using this pattern.

The result I am trying to obtain is printing the AST with proper indentation:

```<code>Expr
'---Abstr
    |---Id
    '---Expr
        '---App
            '---Atom
                '---Id
</code>```

I have defined a number of classes representing nodes in the AST:

```<code>class ASTNode
    attr_reader :children, :pos

    def initialize(children, pos)
         @children = children
         @pos = pos
    end

    def accept(visitor)
        visitor.visit(self)
        @children.each { |child| child.accept(visitor) } unless @children.nil?
    end
end

class ExprNode < ASTNode
    def initialize(children, pos)
         super(children, pos)
    end
end

...
</code>```

and a base visitor class performing double dispatch:

```<code>class Visitor
    def visit(subject)
        method_name = "visit_#{subject.class}".intern
        send(method_name, subject)
    end
end
</code>```

Finally, the visitor for printing the AST:

```<code>class PrintVisitor < Visitor
    def visit_ExprNode(subject)
    end

    def visit_AbstrNode(subject)
    end

    ...
end
</code>```

答:
There are two versions of the visitor pattern: One version only takes care of the double dispatch and the other also takes care of iteration by automatically visiting a node's children. The latter version is less flexible because you decide what kind of traversal (pre-order or post-order) you want ahead of time instead of leaving that decision to the individual visitor. It also forces you to visit all the nodes exactly once (which you wouldn't want in many cases, such as when implementing an AST interpreter).

In your code you're actually implementing both of those versions: Your Visitor#visit method implements the plain visitor pattern and ASTNode#accept implements the one with iteration. That's a weird use of the accept method because usually the job of the accept method is simply to call a specific visit method (like visit_whatever) on the visitor to get the double dispatch to work. Since you've used reflection to implement the double dispatch, you don't need an accept method at all.

I assume that the printing should be implemented in visit_*Node(subject) methods of PrintVisitor

That is correct.

Printing each node requires additional context to determine the right indentation level.

Also correct. You can keep track of the indentation level by storing it in an instance variable. Then a given visitor method would print its contents with the given amount of indentation, increase the indentation level, visit its child notes, and then decrease the indentation again. Something like this:

```<code>def visit_SomeNode(some_node)
    puts "#{@indent * " "}---SomeNode"
    @indent += 4
    some_node.children.each {|child| visit(child)}
    @indent -= 4
end
</code>```

You could also put some_node.children.each {|child| visit(child)} into its own visit_children(node) method and just call that for the cases where you want to perform the same action for all children (as above).

If you want to avoid that mutable state, you can also adjust your visitor class to allow passing arguments to visit like this:

```<code>class Visitor
    def visit(subject, *args)
        method_name = "visit_#{subject.class}".intern
        send(method_name, subject, *args)
    end
end
</code>```

Then you can add a parameter for the indentation level to your methods and pass an increased indentation level to visit when visiting your children.

Body:
I am trying to build a simple interpreter using the Visitor pattern. I'm having a difficult time trying to understand how a task such as pretty-printing the tree can be implemented using this pattern.

The result I am trying to obtain is printing the AST with proper indentation:

Expr
'---Abstr
    |---Id
    '---Expr
        '---App
            '---Atom
                '---Id

I have defined a number of classes representing nodes in the AST:

class ASTNode
    attr_reader :children, :pos

    def initialize(children, pos)
         @children = children
         @pos = pos
    end

    def accept(visitor)
        visitor.visit(self)
        @children.each { |child| child.accept(visitor) } unless @children.nil?
    end
end

class ExprNode < ASTNode
    def initialize(children, pos)
         super(children, pos)
    end
end

...

and a base visitor class performing double dispatch:

class Visitor
    def visit(subject)
        method_name = "visit_#{subject.class}".intern
        send(method_name, subject)
    end
end

Finally, the visitor for printing the AST:

class PrintVisitor < Visitor
    def visit_ExprNode(subject)
    end

    def visit_AbstrNode(subject)
    end

    ...
end

Body:
There are two versions of the visitor pattern: One version only takes care of the double dispatch and the other also takes care of iteration by automatically visiting a node's children. The latter version is less flexible because you decide what kind of traversal (pre-order or post-order) you want ahead of time instead of leaving that decision to the individual visitor. It also forces you to visit all the nodes exactly once (which you wouldn't want in many cases, such as when implementing an AST interpreter).

In your code you're actually implementing both of those versions: Your Visitor#visit method implements the plain visitor pattern and ASTNode#accept implements the one with iteration. That's a weird use of the accept method because usually the job of the accept method is simply to call a specific visit method (like visit_whatever) on the visitor to get the double dispatch to work. Since you've used reflection to implement the double dispatch, you don't need an accept method at all.

I assume that the printing should be implemented in visit_*Node(subject) methods of PrintVisitor

That is correct.

Printing each node requires additional context to determine the right indentation level.

Also correct. You can keep track of the indentation level by storing it in an instance variable. Then a given visitor method would print its contents with the given amount of indentation, increase the indentation level, visit its child notes, and then decrease the indentation again. Something like this:

def visit_SomeNode(some_node)
    puts "#{@indent * " "}---SomeNode"
    @indent += 4
    some_node.children.each {|child| visit(child)}
    @indent -= 4
end

You could also put some_node.children.each {|child| visit(child)} into its own visit_children(node) method and just call that for the cases where you want to perform the same action for all children (as above).

If you want to avoid that mutable state, you can also adjust your visitor class to allow passing arguments to visit like this:

class Visitor
    def visit(subject, *args)
        method_name = "visit_#{subject.class}".intern
        send(method_name, subject, *args)
    end
end

Then you can add a parameter for the indentation level to your methods and pass an increased indentation level to visit when visiting your children.