问:
Avoiding repetitive sub-class definitions in C++
I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.

Take the following example which might appear in a header file with 3 sub-classes:

```<code>class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
    // ... many more functions
}

class Zebra: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Cow: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Salmon: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

// ... many more animals
</code>```

Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?

In the context I am working in each animal would have a completely independent implementation in separate .cpp files.

Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.

答:
It is indeed error prone when you don't make use of the override keyword for each overridden virtual class member function.

Instead of declaring the derived class function like this

```<code>bool someFunction();
</code>```

you can/should declare it like this

```<code>bool someFunction() override;
</code>```

In this way, you would get a compilation error if the declaration doesn't match the base class signature. Without it, you would have a perfectly good compilable program but with a behaviour bug.

Other than that, your strategy is fine, and is the way to do handle abstract functions.

Body:
I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.

Take the following example which might appear in a header file with 3 sub-classes:

class Animal {
private:
    int a;
    int b;
public:
    explicit Animal(int a) {}
    virtual Animal* getFriend() = 0;
    virtual bool walk() = 0;
    virtual bool talk() = 0;
    virtual bool someFunction() = 0;
    virtual bool someOtherFunction() = 0;
    // ... many more functions
}

class Zebra: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Cow: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

class Salmon: public Animal {
    Animal* getFriend();
    bool walk();
    bool someFunction();
    bool someOtherFunction();
    // ... continues for many more functions
}

// ... many more animals

Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?

In the context I am working in each animal would have a completely independent implementation in separate .cpp files.

Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.

Body:
It is indeed error prone when you don't make use of the override keyword for each overridden virtual class member function.

Instead of declaring the derived class function like this

bool someFunction();

you can/should declare it like this

bool someFunction() override;

In this way, you would get a compilation error if the declaration doesn't match the base class signature. Without it, you would have a perfectly good compilable program but with a behaviour bug.

Other than that, your strategy is fine, and is the way to do handle abstract functions.


来源: stackexchange

问:
Update inner object element in Json using Gson
I have below json and need to update elements, below code works for elements in top level, How can I extend this to work it inside another inner level (object).

Json:

```<code>{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  }
}
</code>```

In below code I am passing below

eg.
keyPath = "headerId"
updateText = "123456"
jsonText = above json

Code :

```<code>public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for(String key : keys)
    {
        if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject())
        {
            jsonObject = (JsonObject)jsonObject.get(key);
        }
    }
    jsonObject.remove(finalKey);
    jsonObject.add(finalKey, jp);
    return returnVal.toString();
}
</code>```

Code

Expected out put json:

```<code>{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "123456",
    "queue": "draft",
  }
}
</code>```

Actual reult:

```<code>{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  },
  "headerId": "123456",
}
</code>```

答: Pass keyPath as "reqParams/headerId" because headerId is inside reqParams and not at root level of JSON.

ContentLicense: CC BY-SA 4.0

Body:
I have below json and need to update elements, below code works for elements in top level, How can I extend this to work it inside another inner level (object).

Json:

{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  }
}

In below code I am passing below

eg.
keyPath = "headerId"
updateText = "123456"
jsonText = above json

Code :

public String updateValue(String keyPath, String updateText, String jsonText) {
    String[] keys = keyPath.split("/");
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
    JsonObject returnVal = jsonObject; // This holds the ref to target json object
    JsonPrimitive jp = new JsonPrimitive(updateText);
    String finalKey = keys[keys.length - 1];
    for(String key : keys)
    {
        if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject())
        {
            jsonObject = (JsonObject)jsonObject.get(key);
        }
    }
    jsonObject.remove(finalKey);
    jsonObject.add(finalKey, jp);
    return returnVal.toString();
}

Code

Expected out put json:

{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "123456",
    "queue": "draft",
  }
}

Actual reult:

{
  "name": George,
  "version": "2.0",
  "reqParams": {
    "headerId": "this needs to be updated",
    "queue": "draft",
  },
  "headerId": "123456",
}


问:
How to put string variables into a Python array?
I'm rather new at this (it's my first question ha!), and my english isn't as good and technical as yours so I apologize in advance. That being said, I'm trying to fit string variables to an array but I can't get it done. Here are the variables:

```<code>basket1 = {'vanilla wafers', 'bananas' , 'dog food'}
basket2 = {'bananas', 'bread', 'yogurt'}
basket3 = {'bananas','apples','yogurt'}
basket4 = {'vanilla wafers','bananas','whipped cream'}
basket5 = {'bread', 'vanilla wafers' , 'yogurt'}
basket6 = {'milk', 'bread', 'bananas'}
basket7 = {'vanilla wafers', 'apples' , 'bananas'}
basket8 = {'yogurt', 'apples', 'vanilla wafers'}
basket9 = {'vanilla wafers', 'bananas' , 'milk'}
basket10 =  {'bananas', 'bread', 'peanut butter'}
</code>```

Any ideas? Should I use a list instead? It must have a 10x3 shape though.

答:
You could use declare a baskets list and iterate over a for loop to append values to the end of the list.

You can modify the temp list and fill it with values accordingly each time.

```<code>baskets = list()

for i in range(n):
   temp = [value1,value2,value3]
   baskets.append(temp)

print(baskets)
</code>```

Body:
I'm rather new at this (it's my first question ha!), and my english isn't as good and technical as yours so I apologize in advance. That being said, I'm trying to fit string variables to an array but I can't get it done. Here are the variables:

basket1 = {'vanilla wafers', 'bananas' , 'dog food'}
basket2 = {'bananas', 'bread', 'yogurt'}
basket3 = {'bananas','apples','yogurt'}
basket4 = {'vanilla wafers','bananas','whipped cream'}
basket5 = {'bread', 'vanilla wafers' , 'yogurt'}
basket6 = {'milk', 'bread', 'bananas'}
basket7 = {'vanilla wafers', 'apples' , 'bananas'}
basket8 = {'yogurt', 'apples', 'vanilla wafers'}
basket9 = {'vanilla wafers', 'bananas' , 'milk'}
basket10 =  {'bananas', 'bread', 'peanut butter'}

Any ideas? Should I use a list instead? It must have a 10x3 shape though.

Body:
You could use declare a baskets list and iterate over a for loop to append values to the end of the list.

You can modify the temp list and fill it with values accordingly each time.

baskets = list()

for i in range(n):
   temp = [value1,value2,value3]
   baskets.append(temp)

print(baskets)


问:
Download a file with password and username with C#
How would I write a script to download files from this site. Is it possible to supply the login and password with the url?

http://feeds.itunes.apple.com/feeds/epf/

Would I format the url like this?

```<code>WebClient Client = new WebClient();
Client.DownloadFile("http://feeds.itunes.apple.com/feeds/epf/v3/full/current/itunes20110511.tbz.md5?username=myusername&password=mypassword", @"C:\folder\file.md5");
</code>```

答:
Use WebClient.Credentials property to supply your credentials to the web site:</p>

```<code>using (WebClient client = new WebClient()) {
    client.Credentials = new NetworkCredential(username, password);
    client.DownloadFile("http://feeds.itunes.apple.com/feeds/epf/v3/full/current/itunes20110511.tbz.md5", @"C:\folder\file.md5");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How would I write a script to download files from this site. Is it possible to supply the login and password with the url?

http://feeds.itunes.apple.com/feeds/epf/

Would I format the url like this?

WebClient Client = new WebClient();
Client.DownloadFile("http://feeds.itunes.apple.com/feeds/epf/v3/full/current/itunes20110511.tbz.md5?username=myusername&password=mypassword", @"C:\folder\file.md5");

Body:
Use WebClient.Credentials property to supply your credentials to the web site:

using (WebClient client = new WebClient()) {
    client.Credentials = new NetworkCredential(username, password);
    client.DownloadFile("http://feeds.itunes.apple.com/feeds/epf/v3/full/current/itunes20110511.tbz.md5", @"C:\folder\file.md5");
}


问:
VBA with Internet Explorer
Just need to have a better understanding of using the internet explorer object in VBA.
So I want to click the following button with a code as following

```<code><a id="DLG_VARIABLE_dlgBase_BTNOK" ct="B" st="" href="javascript:void(0);" class="urBtnEmph" ocl="sapbi_page.sendCommandArray([['TARGET_DIALOG_REF','DLG_VARIABLE',0],['BI_COMMAND_TYPE','OK',0]],event);" onkeydown="ur_Button_keypress(event);" onclick="ur_Button_click(event);" style="text-align:center;overflow:visible;">OK</a>
</code>```

My code is as following -

```<code> Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
 Set IE = New InternetExplorer
 With IE
 .Visible = True
 .Navigate2 "Somewebsite"

 .Document.getelemetbyclass("urBtnEmph").Click

 End With

End Sub
</code>```

but when I try to run it, it says

'Object doesn't support this property or method'.

I'm very new to this internet explorer object and javascript :(

Edit:
I had changed the line to ' .Document.getelementsbyclass("urBtnEmph").Click' however still have the same warning.

Then I tried this '.Document.getElementById("DLG_VARIABLE_dlgBase_BTNOK").Click' and it shows 'Object variable or with block variable not set'. I had attached the html code for this button

答:
Please check the Common VBA Methods & Properties used in web automation, you could use the getElementsByClassName or getElementById method to access web page element.

When using the getElementsByClassName method, it will return multiple elements with the same class name, so, if we want to get the special element, we could find it from the array list.

So, please modify your code as below:

```<code>Public Sub ClickTest()

    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "<website url>"

        While .Busy Or .readyState <> 4: DoEvents: Wend

        'ie.Document.getElementbyId("DLG_VARIABLE_dlgBase_BTNOK").Click  // it also work well. find element by id

        ie.Document.getElementsByClassName("urBtnEmph")(0).Click

    End With
End Sub
</code>```

Title: VBA with Internet Explorer

Body:
Just need to have a better understanding of using the internet explorer object in VBA.
So I want to click the following button with a code as following

OK

My code is as following -

 Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
 Set IE = New InternetExplorer
 With IE
 .Visible = True
 .Navigate2 "Somewebsite"

 .Document.getelemetbyclass("urBtnEmph").Click

 End With

End Sub

but when I try to run it, it says

'Object doesn't support this property or method'.

I'm very new to this internet explorer object and javascript :(

Edit:
I had changed the line to ' .Document.getelementsbyclass("urBtnEmph").Click' however still have the same warning.

Then I tried this '.Document.getElementById("DLG_VARIABLE_dlgBase_BTNOK").Click' and it shows 'Object variable or with block variable not set'. I had attached the html code for this button

Body:
Please check the Common VBA Methods & Properties used in web automation, you could use the getElementsByClassName or getElementById method to access web page element.

When using the getElementsByClassName method, it will return multiple elements with the same class name, so, if we want to get the special element, we could find it from the array list.

So, please modify your code as below:

Public Sub ClickTest()

    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "<website url>"

        While .Busy Or .readyState <> 4: DoEvents: Wend

        'ie.Document.getElementbyId("DLG_VARIABLE_dlgBase_BTNOK").Click  // it also work well. find element by id

        ie.Document.getElementsByClassName("urBtnEmph")(0).Click

    End With
End Sub


问:
Rotate Function for Component Drawed with Canvas Lazarus
I need a function in Lazarus that with it I can rotate some components instead of rewrite them (swapping x with y and viceversa)
for example:

i am using a class developed by another user
with this class i had to define the name of the component with properties and after a procedure NameComponent.Draw
the motedi engine draw the components reading this Draw procedure.
i save the components on a file sch (with also wires junction resistors etc)
when i load a circuit ...my software creates components (also wires junction) with saved properties (include points of connection where wire is attached)
wires has also node property
my software creates the netlist etc

```<code>procedure SW.Draw;
var angle:extended;
begin

if (self.Orientamento = '') or (self.Orientamento = '1') then
begin
  v2d.setpen(pssolid,1,clBlue);
  v2d.SetBrush(clwhite);
  v2d.Line(x,y+30,x+100,y+30);
  v2d.line(x,y+30,x,y+120);
  v2d.line(x,y+120,x+100,y+120);
  v2d.line(x+100,y+30,x+100,y+120);
  v2d.line(x+20,y+30,x+20,y+10);     // nc-
  v2d.line(x+80,y+30,x+80,y+10);     // nc+

  v2d.line(x+20,y+120,x+20,y+140);     // n-
  v2d.line(x+80,y+120,x+80,y+140);     // n+

  // interruttore dentro
  v2d.line(x+20,y+120,x+20,y+80);    // a
  v2d.line(x+80,y+120,x+80,y+80);    // b
  v2d.line(x+20,y+80,x+40,y+80);     // c
  v2d.line(x+60,y+80,x+80,y+80);     // d

  if (self.State = 'OFF') then
  begin
    v2d.setpen(pssolid,2,clGreen);
    v2d.line(x+40,y+80,x+63,y+72);      // e
  end
  else
  begin
    v2d.setpen(pssolid,2,clGreen);
    v2d.line(x+40,y+80,x+60,y+80);
  end;
  v2d.setpen(pssolid,1,clBlue);
  v2d.SetText(clRed, 6,'', true);
  v2d.Texto(X+82, Y +110, 'N+');
  v2d.Texto(X+74, Y +35, 'NC+');
  v2d.SetText(clBlack, 6,'', true);
  v2d.Texto(X+22, Y +110, 'N-');
  v2d.Texto(X+15, Y +35, 'NC-');
  v2d.SetText(clBlack, 8,'', true);
  v2d.Texto(x+104,y+35, self.Nome);
  v2d.Texto(x+104,y+50, self.VT);
  v2d.Texto(x+104,y+65, self.VH);
  v2d.Texto(x+104,y+80, self.RON);
  v2d.Texto(x+104,y+95, self.ROFF);

end;

if (self.Orientamento = '2') then
begin
  v2d.setpen(pssolid,1,clBlue);
  v2d.SetBrush(clwhite);
  v2d.line(x+30,y,x+30,y+100);
  v2d.line(x+30,y,x+120,y);
  v2d.line(x+120,y,x+120,y+100);
  v2d.line(x+30,y+100,x+120,y+100);
  v2d.line(x+30,y+20,x+10,y+20);  // nc-
  v2d.line(x+30,y+80,x+10,y+80); // nc +
  v2d.line(x+120,y+20, x+140,y+20); // n-
  v2d.line(x+120,y+80,x+140,y+80); // n+
  v2d.line(x+120, y+20, x+80, y+20);
  v2d.line(x+120,y+80,x+80,y+80);
  v2d.line(x+80, y+20, x+80, y+40);
  v2d.line(x+80, y+60, x+80, y+80);

  if (self.State = 'OFF') then
  begin
    v2d.setpen(pssolid,2,clGreen);
//    v2d.line(x+80, y+40, x+72, y+63);
    v2d.line(x+80, y+60, x+72, y+37);
  end
  else
  begin
    v2d.setpen(pssolid,2,clGreen);
    v2d.line(x+80,y+60, x+80, y+40);
//    v2d.line(x+80, y+40, x+80, y+60);
  end;

  v2d.setpen(pssolid,1,clBlue);
  v2d.SetText(clBlack, 6,'', true);
  v2d.texto(x+110, y+82, 'N-');
  v2d.texto(x+35, y+74, 'NC-');
  v2d.SetText(clRed, 6,'', true);
  v2d.Texto(x+110, y+22, 'N+');
  v2d.Texto(x+35, y+15, 'NC+');

end;

inherited;

end;
</code>```

答:
In case you're asking for code, that's supports degrees instead of pre-defined values, here's an example, which uses Math PI to perform sectoral rotation of a point on 2-dimensional space:

```<code>    function findCenter(Width, Height: Integer): TPoint;
    begin
         // Specify rotation center
         Result := TPoint.Create(Width DIV 2, Height DIV 2);
    end;
    function Rotate(What, Center: TPoint; Angle: Double): TPoint; overload;
    begin
    if Angle > 0 then
    begin
      // Perform rotation
      Result.X :=
                 ROUND(
                       Center.X + (What.X - Center.X)* COS(Angle)
                               - (What.Y - Center.Y)* SIN(Angle) );
      Result.Y :=
                 ROUND(
                       Center.X + (What.X - Center.X)* SIN(Angle)
                               + (What.Y - Center.Y)* COS(Angle) );
    end
    else
        Result := TPoint.Create(What);
    end;
    function Rotate(What, Center: TPoint; Degrees: Integer): TPoint; overload;
    var RotationAngle: Double;
    begin
      // Convert Degress to Radians
      RotationAngle := Degrees * PI/180;
      Result := Rotate(What, Center, RotationAngle);
    end;
    function Rotate(What: TPoint; Degrees: Integer): TPoint; overload;
    var RotationAngle: Double;
    begin
      RotationAngle := Degrees * PI/180;
      Result := Rotate(What, TPoint.Create(0,0), RotationAngle);
    end;
</code>```

Use the function Rotate() to rotate the location of your elements, for each of them you need to specify also a center of an element (Width and Height of parent  element, divided by 2), information to get the center of element for text you can gather from WinAPI ( CalcTextWidth or CalcTextRect either )
The actual height of the text is the Font.Size - 1, so you can get Height value without external functions.

Note, that this probably won't work, if you're resizing your polygons, to resize them you need to calculate relations between every point or to split polygons to the triangles and do it for them (every n-heighted polygon can be splitted to triangles, the exception is ellipse, which has its own sizing technique - modifying the diameter ).
Also, be aware, that you must calculate new area sizes and positions offsets in order to keep final picture in field of view.

Body:
I need a function in Lazarus that with it I can rotate some components instead of rewrite them (swapping x with y and viceversa)
for example:

i am using a class developed by another user
with this class i had to define the name of the component with properties and after a procedure NameComponent.Draw
the motedi engine draw the components reading this Draw procedure.
i save the components on a file sch (with also wires junction resistors etc)
when i load a circuit ...my software creates components (also wires junction) with saved properties (include points of connection where wire is attached)
wires has also node property
my software creates the netlist etc

procedure SW.Draw;
var angle:extended;
begin

if (self.Orientamento = '') or (self.Orientamento = '1') then
begin
  v2d.setpen(pssolid,1,clBlue);
  v2d.SetBrush(clwhite);
  v2d.Line(x,y+30,x+100,y+30);
  v2d.line(x,y+30,x,y+120);
  v2d.line(x,y+120,x+100,y+120);
  v2d.line(x+100,y+30,x+100,y+120);
  v2d.line(x+20,y+30,x+20,y+10);     // nc-
  v2d.line(x+80,y+30,x+80,y+10);     // nc+

  v2d.line(x+20,y+120,x+20,y+140);     // n-
  v2d.line(x+80,y+120,x+80,y+140);     // n+

  // interruttore dentro
  v2d.line(x+20,y+120,x+20,y+80);    // a
  v2d.line(x+80,y+120,x+80,y+80);    // b
  v2d.line(x+20,y+80,x+40,y+80);     // c
  v2d.line(x+60,y+80,x+80,y+80);     // d

  if (self.State = 'OFF') then
  begin
    v2d.setpen(pssolid,2,clGreen);
    v2d.line(x+40,y+80,x+63,y+72);      // e
  end
  else
  begin
    v2d.setpen(pssolid,2,clGreen);
    v2d.line(x+40,y+80,x+60,y+80);
  end;
  v2d.setpen(pssolid,1,clBlue);
  v2d.SetText(clRed, 6,'', true);
  v2d.Texto(X+82, Y +110, 'N+');
  v2d.Texto(X+74, Y +35, 'NC+');
  v2d.SetText(clBlack, 6,'', true);
  v2d.Texto(X+22, Y +110, 'N-');
  v2d.Texto(X+15, Y +35, 'NC-');
  v2d.SetText(clBlack, 8,'', true);
  v2d.Texto(x+104,y+35, self.Nome);
  v2d.Texto(x+104,y+50, self.VT);
  v2d.Texto(x+104,y+65, self.VH);
  v2d.Texto(x+104,y+80, self.RON);
  v2d.Texto(x+104,y+95, self.ROFF);

end;

if (self.Orientamento = '2') then
begin
  v2d.setpen(pssolid,1,clBlue);
  v2d.SetBrush(clwhite);
  v2d.line(x+30,y,x+30,y+100);
  v2d.line(x+30,y,x+120,y);
  v2d.line(x+120,y,x+120,y+100);
  v2d.line(x+30,y+100,x+120,y+100);
  v2d.line(x+30,y+20,x+10,y+20);  // nc-
  v2d.line(x+30,y+80,x+10,y+80); // nc +
  v2d.line(x+120,y+20, x+140,y+20); // n-
  v2d.line(x+120,y+80,x+140,y+80); // n+
  v2d.line(x+120, y+20, x+80, y+20);
  v2d.line(x+120,y+80,x+80,y+80);
  v2d.line(x+80, y+20, x+80, y+40);
  v2d.line(x+80, y+60, x+80, y+80);

  if (self.State = 'OFF') then
  begin
    v2d.setpen(pssolid,2,clGreen);
//    v2d.line(x+80, y+40, x+72, y+63);
    v2d.line(x+80, y+60, x+72, y+37);
  end
  else
  begin
    v2d.setpen(pssolid,2,clGreen);
    v2d.line(x+80,y+60, x+80, y+40);
//    v2d.line(x+80, y+40, x+80, y+60);
  end;

  v2d.setpen(pssolid,1,clBlue);
  v2d.SetText(clBlack, 6,'', true);
  v2d.texto(x+110, y+82, 'N-');
  v2d.texto(x+35, y+74, 'NC-');
  v2d.SetText(clRed, 6,'', true);
  v2d.Texto(x+110, y+22, 'N+');
  v2d.Texto(x+35, y+15, 'NC+');

end;

inherited;

end;

Body:
In case you're asking for code, that's supports degrees instead of pre-defined values, here's an example, which uses Math PI to perform sectoral rotation of a point on 2-dimensional space:

    function findCenter(Width, Height: Integer): TPoint;
    begin
         // Specify rotation center
         Result := TPoint.Create(Width DIV 2, Height DIV 2);
    end;
    function Rotate(What, Center: TPoint; Angle: Double): TPoint; overload;
    begin
    if Angle > 0 then
    begin
      // Perform rotation
      Result.X :=
                 ROUND(
                       Center.X + (What.X - Center.X)* COS(Angle)
                               - (What.Y - Center.Y)* SIN(Angle) );
      Result.Y :=
                 ROUND(
                       Center.X + (What.X - Center.X)* SIN(Angle)
                               + (What.Y - Center.Y)* COS(Angle) );
    end
    else
        Result := TPoint.Create(What);
    end;
    function Rotate(What, Center: TPoint; Degrees: Integer): TPoint; overload;
    var RotationAngle: Double;
    begin
      // Convert Degress to Radians
      RotationAngle := Degrees * PI/180;
      Result := Rotate(What, Center, RotationAngle);
    end;
    function Rotate(What: TPoint; Degrees: Integer): TPoint; overload;
    var RotationAngle: Double;
    begin
      RotationAngle := Degrees * PI/180;
      Result := Rotate(What, TPoint.Create(0,0), RotationAngle);
    end;

Use the function Rotate() to rotate the location of your elements, for each of them you need to specify also a center of an element (Width and Height of parent  element, divided by 2), information to get the center of element for text you can gather from WinAPI ( CalcTextWidth or CalcTextRect either )
The actual height of the text is the Font.Size - 1, so you can get Height value without external functions.

Note, that this probably won't work, if you're resizing your polygons, to resize them you need to calculate relations between every point or to split polygons to the triangles and do it for them (every n-heighted polygon can be splitted to triangles, the exception is ellipse, which has its own sizing technique - modifying the diameter ).
Also, be aware, that you must calculate new area sizes and positions offsets in order to keep final picture in field of view.


问:
how to set display member to a concatenated expression? datasource is linq query
i'm trying to set the display member of my listbox to a concatenated value from a linq query:

```<code>var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;
</code>```

I was hoping to be able to set the display member by doing something like this:

```<code>listBox1.DisplayMember = "FirstName" + "LastName";
</code>```

but obviously that doesn't work.

how do i do this? I guess the tricky part is the fact that the datasource is a linq query result object. But its indexable so there's gotta be some way.

答:
If you have a Customer class that you either wrote yourself or is genertaed but extendable, then the best method in my opinion is to add a new property to it

```<code>namespace SameNameSpaceAsGeneratedCustomerClass {
  public partial class Customer {
    public string FullName { get { return FirstName + " " + LastName; } }
  }
}</code>```

If you are unable to do this, then you will need to look at creating a ValueConverter http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx

Body:
i'm trying to set the display member of my listbox to a concatenated value from a linq query:

var query =
     from a in db.Customers
     select a;

listBox1.DataSouce = query;

I was hoping to be able to set the display member by doing something like this:

listBox1.DisplayMember = "FirstName" + "LastName";

but obviously that doesn't work.

how do i do this? I guess the tricky part is the fact that the datasource is a linq query result object. But its indexable so there's gotta be some way.

Body:
If you have a Customer class that you either wrote yourself or is genertaed but extendable, then the best method in my opinion is to add a new property to it

namespace SameNameSpaceAsGeneratedCustomerClass {
  public partial class Customer {
    public string FullName { get { return FirstName + " " + LastName; } }
  }
}

If you are unable to do this, then you will need to look at creating a ValueConverter http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx


问:
Convert js object array into associative array
By using array.push() I'm updating a following array. I want to add index/key to every object in the object array as I want to check is a record exist with same index/key before pushing new item.

My array is like

```<code>$data = [
  {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
  {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
  {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]
</code>```

and i want to convert this like

```<code>[
    0 => {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
    1 => {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
    2 => {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]
</code>```

Is there any way to do this? please give me an idea.
Thank you!

答: That is basically what you have already. The array of objects is effectively an associative array where the keys are integers - both extend Object.

Body:
By using array.push() I'm updating a following array. I want to add index/key to every object in the object array as I want to check is a record exist with same index/key before pushing new item.

My array is like

$data = [
  {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
  {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
  {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]

and i want to convert this like

[
    0 => {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
    1 => {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
    2 => {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]

Is there any way to do this? please give me an idea.
Thank you!


问:
Regex for /someChars1@someChars2BOT
I have a regex to find something like /someChars1@someChars2BOT in java

rules:

the text has to start with / symbol

someChars1 should contain at least 1 char or more (it could not be whiteSpace)

someChars2 has to start with @ symbol and it could not be whitespace

the text has to end with BOT word

the text could not contain whitespace

can someone help me?
thank you in advance

答:
You may try with this:

```<code>\/[\S]+@[\S]+BOT
</code>```

Explanation:

\/ Start with /

[\S]+ matches any non white space character where + means one or more

@ followed by @

[\S]+ matches any non white space character where + means one or more

BOT  matches BOT

Example

Title: Regex for /someChars1@someChars2BOT

Body:
You may try with this:

\/[\S]+@[\S]+BOT

Explanation:

\/ Start with /

[\S]+ matches any non white space character where + means one or more

@ followed by @

[\S]+ matches any non white space character where + means one or more

BOT  matches BOT

Example


问:
Using @babel/register for a React app in Node v13
I have an app built using create-react-app and it has an entrypoint that used something like this —

require('babel-register')({
  ignore: [/(node_modules)/],
  presets: ['es2015', 'react-app'],
  plugins: [
    'syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ]
});
require('./index');
```

<p>I'm in the process of upgrading Node (from v8 to v13.5) and decided to upgrade Babel too. Using Babel 7, the above piece of code was rewritten as —</p>

<pre class="lang-js prettyprint-override"><code>require('@babel/register')({
  ignore: [/(node_modules)/],
  presets: ['@babel/preset-env', 'react-app'],
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ],
});
require('./index');
</code>```

Now when I run this, I get the error —

```<code>internal/modules/cjs/loader.js:1160
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
require() of ES modules is not supported.
require() of /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js from /my-app/server/controllers/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename asyncToGenerator.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/package.json.
</code>```

I'm guessing this is because preset-env is using modules support as it is detecting it in my version of Node (v13.6.0). If that's how I can fix this issue, how do I force it to use the es2015 preset? They've long been deprecated in favor of preset-env.

答:
You can either downgrade to Node v10 or add this to the existing one</p>

```<code>  "start": "node --experimental-modules src/index.mjs "
</code>```

Body:
I have an app built using create-react-app and it has an entrypoint that used something like this —

require('babel-register')({
  ignore: [/(node_modules)/],
  presets: ['es2015', 'react-app'],
  plugins: [
    'syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ]
});
require('./index');

I'm in the process of upgrading Node (from v8 to v13.5) and decided to upgrade Babel too. Using Babel 7, the above piece of code was rewritten as —

require('@babel/register')({
  ignore: [/(node_modules)/],
  presets: ['@babel/preset-env', 'react-app'],
  plugins: [
    '@babel/plugin-syntax-dynamic-import',
    'dynamic-import-node',
    'react-loadable/babel'
  ],
});
require('./index');

Now when I run this, I get the error —

internal/modules/cjs/loader.js:1160
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js
require() of ES modules is not supported.
require() of /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js from /my-app/server/controllers/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename asyncToGenerator.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /my-app/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/package.json.

I'm guessing this is because preset-env is using modules support as it is detecting it in my version of Node (v13.6.0). If that's how I can fix this issue, how do I force it to use the es2015 preset? They've long been deprecated in favor of preset-env.

Body:
You can either downgrade to Node v10 or add this to the existing one

  "start": "node --experimental-modules src/index.mjs "


问:
How to display radio buttons as

I want to display my radio buttons as  so that i can give style sheet and make div clickable.

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

```<code><div class="radio-toolbar">
    <table>
        <tr>
            <td><input type="radio" id="radioone" name="product" value="first">
                <label for="radioone">50</label></td>

            <td><input type="radio" id="radiotwo" name="product" value="second">
                <label for="radiotwo">100</label></td>

            <td><input type="radio" id="radiothree" name="product" value="third">
                <label for="radiothree">500</label></td>
</div>
</code>```

CSS

```<code>.radio-toolbar input[type='radio']:focus + label {
  border: 2px thin blue;
}
.radio-toolbar input[type='radio']:checked + label {
  background-color: #86b1f7;
  border-color: #4c4;
  color: white;
}
</code>```

So how can I achive this
Small help will be appreciated.
Thanks in advance :)

答:
Try Like This. Make Your radio-toolbar input, width: 0;

also make your radio-toolbar label Like this

```<code>.radio-toolbar label {

    background-color: #A9A9A9;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 4px;
}
</code>```

Title: How to display radio buttons as <div>

Body:
I want to display my radio buttons as  so that i can give style sheet and make div clickable.

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

            <input type="radio" id="radioone" name="product" value="first">
                50

            <input type="radio" id="radiotwo" name="product" value="second">
                100

            <input type="radio" id="radiothree" name="product" value="third">
                500

CSS

.radio-toolbar input[type='radio']:focus + label {
  border: 2px thin blue;
}
.radio-toolbar input[type='radio']:checked + label {
  background-color: #86b1f7;
  border-color: #4c4;
  color: white;
}

So how can I achive this
Small help will be appreciated.
Thanks in advance :)

Body:
Try Like This. Make Your radio-toolbar input, width: 0;

also make your radio-toolbar label Like this

.radio-toolbar label {

    background-color: #A9A9A9;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 4px;
}


问:
How do I Make a PDF searchable for a flask search application?
I have been doing research for a very important personal project. I would like to create a Flask Search Application that allows me to search for content across 100 Plus PDF files. I have found Some information around A ElasticSearch Lib that works well with flask.

```<code>#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import libraries to help read and create PDF
import PyPDF2
from fpdf import FPDF
import base64
import json
from flask import Flask, jsonify, request, render_template,  json
from datetime import datetime
import pandas as pd

# import the Elasticsearch low-level client library
from elasticsearch import Elasticsearch
# create a new client instance of Elasticsearch
elastic_client = Elasticsearch(hosts=["localhost"])
es = Elasticsearch("http://localhost:9200/")
app = Flask(__name__)

# create a new PDF object with FPDF
pdf = FPDF()

# use an iterator to create 10 pages
for page in range(10):
    pdf.add_page()
    pdf.set_font("Arial", size=14)
    pdf.cell(150, 12, txt="Object Rocket ROCKS!!", ln=1, align="C")

# output all of the data to a new PDF file
pdf.output("object_rocket.pdf")

'''
read_pdf = PyPDF2.PdfFileReader("object_rocket.pdf")
page = read_pdf.getPage(0)
page_mode = read_pdf.getPageMode()
page_text = page.extractText()
print (type(page_text))
'''
#with open(path, 'rb') as file:

# get the PDF path and read the file
file = "Sheet3.pdf"
read_pdf = PyPDF2.PdfFileReader(file, strict=False)
#print (read_pdf)

# get the read object's meta info
pdf_meta = read_pdf.getDocumentInfo()

# get the page numbers
num = read_pdf.getNumPages()
print ("PDF pages:", num)

# create a dictionary object for page data
all_pages = {}

# put meta data into a dict key
all_pages["meta"] = {}

# Use 'iteritems()` instead of 'items()' for Python 2
for meta, value in pdf_meta.items():
    print (meta, value)
    all_pages["meta"][meta] = value

# iterate the page numbers
for page in range(num):
    data = read_pdf.getPage(page)
    #page_mode = read_pdf.getPageMode()

    # extract the page's text
    page_text = data.extractText()

    # put the text data into the dict
    all_pages[page] = page_text

# create a JSON string from the dictionary
json_data = json.dumps(all_pages)
#print ("\nJSON:", json_data)

# convert JSON string to bytes-like obj
bytes_string = bytes(json_data, 'utf-8')
#print ("\nbytes_string:", bytes_string)

# convert bytes to base64 encoded string
encoded_pdf = base64.b64encode(bytes_string)
encoded_pdf = str(encoded_pdf)
#print ("\nbase64:", encoded_pdf)

# put the PDF data into a dictionary body to pass to the API request
body_doc = {"data": encoded_pdf}

# call the index() method to index the data
result = elastic_client.index(index="pdf", doc_type="_doc", id="42", body=body_doc)

# print the returned sresults
#print ("\nindex result:", result['result'])

# make another Elasticsearch API request to get the indexed PDF
result = elastic_client.get(index="pdf", doc_type='_doc', id=42)

# print the data to terminal
result_data = result["_source"]["data"]
#print ("\nresult_data:", result_data, '-- type:', type(result_data))

# decode the base64 data (use to [:] to slice off
# the 'b and ' in the string)
decoded_pdf = base64.b64decode(result_data[2:-1]).decode("utf-8")
#print ("\ndecoded_pdf:", decoded_pdf)

# take decoded string and make into JSON object
json_dict = json.loads(decoded_pdf)
#print ("\njson_str:", json_dict, "\n\ntype:", type(json_dict))
result2 = elastic_client.index(index="pdftext", doc_type="_doc", id="42", body=json_dict)

# create new FPDF object
pdf = FPDF()

# build the new PDF from the Elasticsearch dictionary
# Use 'iteritems()` instead of 'items()' for Python 2
""" for page, value in json_data:
    if page != "meta":
        # create new page
        pdf.add_page()
        pdf.set_font("Arial", size=14)

        # add content to page
        output = value + " -- Page: " + str(int(page)+1)
        pdf.cell(150, 12, txt=output, ln=1, align="C")
    else:
        # create the meta data for the new PDF
        for meta, meta_val in json_dict["meta"].items():
            if "title" in meta.lower():
                pdf.set_title(meta_val)
            elif "producer" in meta.lower() or "creator" in meta.lower():
                pdf.set_creator(meta_val)
 """
# output the PDF object's data to a PDF file
#pdf.output("object_rocket_from_elaticsearch.pdf" )

@app.route('/', methods=['GET'])
def index():

    return jsonify(json_dict)

@app.route('/<id>', methods=['GET'])
def index_by_id(id):

    return jsonify(json_dict[id])

""" @app.route('/insert_data', methods=['PUT'])
def insert_data():
    slug = request.form['slug']
    title = request.form['title']
    content = request.form['content']

    body = {
        'slug': slug,
        'title': title,
        'content': content,
        'timestamp': datetime.now()
    }

    result = es.index(index='contents', doc_type='title', id=slug, body=body)

    return jsonify(result) """

app.run(port=5003, debug=True)
</code>```

------Progress------ I now have a working solution with no front-end search capability:

```<code># Load_single_PDF_BY_PAGE_TO_index.py
  #!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import libraries to help read and create PDF
import PyPDF2
from fpdf import FPDF
import base64

from flask import Flask, jsonify, request, render_template,  json
from datetime import datetime
import pandas as pd

# import the Elasticsearch low-level client library
from elasticsearch import Elasticsearch
# create a new client instance of Elasticsearch
elastic_client = Elasticsearch(hosts=["localhost"])
es = Elasticsearch("http://localhost:9200/")
app = Flask(__name__)

#with open(path, 'rb') as file:

# get the PDF path and read the file
file = "Sheet3.pdf"
read_pdf = PyPDF2.PdfFileReader(file, strict=False)
#print (read_pdf)

# get the read object's meta info
pdf_meta = read_pdf.getDocumentInfo()

# get the page numbers
num = read_pdf.getNumPages()
print ("PDF pages:", num)

# create a dictionary object for page data
all_pages = {}

# put meta data into a dict key
all_pages["meta"] = {}

# Use 'iteritems()` instead of 'items()' for Python 2
for meta, value in pdf_meta.items():
    print (meta, value)
    all_pages["meta"][meta] = value

x = 44
# iterate the page numbers
for page in range(num):
    data = read_pdf.getPage(page)
    #page_mode = read_pdf.getPageMode()

    # extract the page's text
    page_text = data.extractText()

    # put the text data into the dict
    all_pages[page] = page_text

    body_doc2 = {"data": page_text}
    result3 = elastic_client.index(index="pdfclearn", doc_type="_doc", id=x, body=body_doc2)
    x += 1
</code>```

The above code loads a single pdf into elasticsearch by page.

```<code>from flask import Flask, jsonify, request,render_template
from elasticsearch import Elasticsearch
from datetime import datetime
es = Elasticsearch("http://localhost:9200/")

app = Flask(__name__)

@app.route('/pdf', methods=['GET'])
def index():
    results = es.get(index='pdfclearn', doc_type='_doc', id='44')
    return jsonify(results['_source'])

@app.route('/pdf/<id>', methods=['GET'])
def index_by_id(id):
    results = es.get(index='pdfclearn', doc_type='_doc', id=id)
    return jsonify(results['_source'])

@app.route('/search/<keyword>', methods=['POST','GET'])
def search(keyword):
    keyword = keyword

    body = {
        "query": {
            "multi_match": {
                "query": keyword,
                "fields": ["data"]
            }
        }
    }

    res = es.search(index="pdfclearn", doc_type="_doc", body=body)

    return jsonify(res['hits']['hits'])

@app.route("/searhbar")
def searhbar():
    return render_template("index.html")

@app.route("/searhbar/<string:box>")
def process(box):
    query = request.args.get('query')
    if box == 'names':
         keyword = box

    body = {
        "query": {
            "multi_match": {
                "query": keyword,
                "fields": ["data"]
            }
        }
    }

    res = es.search(index="pdfclearn", doc_type="_doc", body=body)

    return jsonify(res['hits']['hits'])

app.run(port=5003, debug=True)
</code>```

In the above code we can search across all Pages for a keyword or phrase.

```<code>curl http://127.0.0.1:5003/search/test //it works!!
</code>```

I Found a blog about how to dave PDF files as a Base64 index in ElasticSearch. I have seen DocuSign's API do this for document templating. However, I dont understand How to Jsonify the Base64 PDF in a way thats searchable for ElasticSearch.

```<code>curl "http://localhost:9200/pdftext/_doc/42"

curl -X POST "http://localhost:9200/pdf/_search?q=*"
</code>```

I can retrieve the Base64 of a 700 Page document. But I think what I need is to Index and retrieve Each Page of the Document.

Blogs I Have Studied that got me part the way:

https://kb.objectrocket.com/elasticsearch/how-to-index-a-pdf-file-as-an-elasticsearch-index-267

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvi-full-text-search

endgame:

https://towardsdatascience.com/create-a-full-search-engine-via-flask-elasticsearch-javascript-d3js-and-bootstrap-275f9dc6efe1

I will continue to study Elastic Search and Base64 Encoding and decoding. But I would like some help getting to my goal. Any Detailed example would be much appreciated.

答:
So i found a lib called scout and...got it to work!

```<code>from scout_client import Scout

# import libraries to help read and create PDF

import PyPDF2
from fpdf import FPDF
import base64
import os
from flask import Flask, jsonify, request, render_template,  json

client = Scout('http://localhost:8000')

for k in range(7,18):
    read_pdf = PyPDF2.PdfFileReader("books/%s.pdf"%(k))
    num = read_pdf.getNumPages()
    print ("PDF pages:", num)
    all_pages = []
    for page in range(num):
        data = read_pdf.getPage(page)
        page_text = data.extractText()
        all_pages.append(page_text)

    import requests
    for z in all_pages:
        url = 'http://localhost:8000/documents/'
        data = {'content': z, 'indexes': ['test13']}
        headers = {
        'Content-Type': 'application/json',
        }

        response = requests.post(url, data=json.dumps(data), headers=headers)

    print(response)
</code>```

I can now loop though as many PDF's as I want locally

Post to the server for indexing

and search for keywords

Now I just need help with Making a basic front end with a search bar that calls data from a JSON response in python and flask.

Body:
I have been doing research for a very important personal project. I would like to create a Flask Search Application that allows me to search for content across 100 Plus PDF files. I have found Some information around A ElasticSearch Lib that works well with flask.

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import libraries to help read and create PDF
import PyPDF2
from fpdf import FPDF
import base64
import json
from flask import Flask, jsonify, request, render_template,  json
from datetime import datetime
import pandas as pd

# import the Elasticsearch low-level client library
from elasticsearch import Elasticsearch
# create a new client instance of Elasticsearch
elastic_client = Elasticsearch(hosts=["localhost"])
es = Elasticsearch("http://localhost:9200/")
app = Flask(__name__)

# create a new PDF object with FPDF
pdf = FPDF()

# use an iterator to create 10 pages
for page in range(10):
    pdf.add_page()
    pdf.set_font("Arial", size=14)
    pdf.cell(150, 12, txt="Object Rocket ROCKS!!", ln=1, align="C")

# output all of the data to a new PDF file
pdf.output("object_rocket.pdf")

'''
read_pdf = PyPDF2.PdfFileReader("object_rocket.pdf")
page = read_pdf.getPage(0)
page_mode = read_pdf.getPageMode()
page_text = page.extractText()
print (type(page_text))
'''
#with open(path, 'rb') as file:

# get the PDF path and read the file
file = "Sheet3.pdf"
read_pdf = PyPDF2.PdfFileReader(file, strict=False)
#print (read_pdf)

# get the read object's meta info
pdf_meta = read_pdf.getDocumentInfo()

# get the page numbers
num = read_pdf.getNumPages()
print ("PDF pages:", num)

# create a dictionary object for page data
all_pages = {}

# put meta data into a dict key
all_pages["meta"] = {}

# Use 'iteritems()` instead of 'items()' for Python 2
for meta, value in pdf_meta.items():
    print (meta, value)
    all_pages["meta"][meta] = value

# iterate the page numbers
for page in range(num):
    data = read_pdf.getPage(page)
    #page_mode = read_pdf.getPageMode()

    # extract the page's text
    page_text = data.extractText()

    # put the text data into the dict
    all_pages[page] = page_text

# create a JSON string from the dictionary
json_data = json.dumps(all_pages)
#print ("\nJSON:", json_data)

# convert JSON string to bytes-like obj
bytes_string = bytes(json_data, 'utf-8')
#print ("\nbytes_string:", bytes_string)

# convert bytes to base64 encoded string
encoded_pdf = base64.b64encode(bytes_string)
encoded_pdf = str(encoded_pdf)
#print ("\nbase64:", encoded_pdf)

# put the PDF data into a dictionary body to pass to the API request
body_doc = {"data": encoded_pdf}

# call the index() method to index the data
result = elastic_client.index(index="pdf", doc_type="_doc", id="42", body=body_doc)

# print the returned sresults
#print ("\nindex result:", result['result'])

# make another Elasticsearch API request to get the indexed PDF
result = elastic_client.get(index="pdf", doc_type='_doc', id=42)

# print the data to terminal
result_data = result["_source"]["data"]
#print ("\nresult_data:", result_data, '-- type:', type(result_data))

# decode the base64 data (use to [:] to slice off
# the 'b and ' in the string)
decoded_pdf = base64.b64decode(result_data[2:-1]).decode("utf-8")
#print ("\ndecoded_pdf:", decoded_pdf)

# take decoded string and make into JSON object
json_dict = json.loads(decoded_pdf)
#print ("\njson_str:", json_dict, "\n\ntype:", type(json_dict))
result2 = elastic_client.index(index="pdftext", doc_type="_doc", id="42", body=json_dict)

# create new FPDF object
pdf = FPDF()

# build the new PDF from the Elasticsearch dictionary
# Use 'iteritems()` instead of 'items()' for Python 2
""" for page, value in json_data:
    if page != "meta":
        # create new page
        pdf.add_page()
        pdf.set_font("Arial", size=14)

        # add content to page
        output = value + " -- Page: " + str(int(page)+1)
        pdf.cell(150, 12, txt=output, ln=1, align="C")
    else:
        # create the meta data for the new PDF
        for meta, meta_val in json_dict["meta"].items():
            if "title" in meta.lower():
                pdf.set_title(meta_val)
            elif "producer" in meta.lower() or "creator" in meta.lower():
                pdf.set_creator(meta_val)
 """
# output the PDF object's data to a PDF file
#pdf.output("object_rocket_from_elaticsearch.pdf" )

@app.route('/', methods=['GET'])
def index():

    return jsonify(json_dict)

@app.route('/<id>', methods=['GET'])
def index_by_id(id):

    return jsonify(json_dict[id])

""" @app.route('/insert_data', methods=['PUT'])
def insert_data():
    slug = request.form['slug']
    title = request.form['title']
    content = request.form['content']

    body = {
        'slug': slug,
        'title': title,
        'content': content,
        'timestamp': datetime.now()
    }

    result = es.index(index='contents', doc_type='title', id=slug, body=body)

    return jsonify(result) """

app.run(port=5003, debug=True)

------Progress------ I now have a working solution with no front-end search capability:

# Load_single_PDF_BY_PAGE_TO_index.py
  #!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import libraries to help read and create PDF
import PyPDF2
from fpdf import FPDF
import base64

from flask import Flask, jsonify, request, render_template,  json
from datetime import datetime
import pandas as pd

# import the Elasticsearch low-level client library
from elasticsearch import Elasticsearch
# create a new client instance of Elasticsearch
elastic_client = Elasticsearch(hosts=["localhost"])
es = Elasticsearch("http://localhost:9200/")
app = Flask(__name__)

#with open(path, 'rb') as file:

# get the PDF path and read the file
file = "Sheet3.pdf"
read_pdf = PyPDF2.PdfFileReader(file, strict=False)
#print (read_pdf)

# get the read object's meta info
pdf_meta = read_pdf.getDocumentInfo()

# get the page numbers
num = read_pdf.getNumPages()
print ("PDF pages:", num)

# create a dictionary object for page data
all_pages = {}

# put meta data into a dict key
all_pages["meta"] = {}

# Use 'iteritems()` instead of 'items()' for Python 2
for meta, value in pdf_meta.items():
    print (meta, value)
    all_pages["meta"][meta] = value

x = 44
# iterate the page numbers
for page in range(num):
    data = read_pdf.getPage(page)
    #page_mode = read_pdf.getPageMode()

    # extract the page's text
    page_text = data.extractText()

    # put the text data into the dict
    all_pages[page] = page_text

    body_doc2 = {"data": page_text}
    result3 = elastic_client.index(index="pdfclearn", doc_type="_doc", id=x, body=body_doc2)
    x += 1

The above code loads a single pdf into elasticsearch by page.

from flask import Flask, jsonify, request,render_template
from elasticsearch import Elasticsearch
from datetime import datetime
es = Elasticsearch("http://localhost:9200/")

app = Flask(__name__)

@app.route('/pdf', methods=['GET'])
def index():
    results = es.get(index='pdfclearn', doc_type='_doc', id='44')
    return jsonify(results['_source'])

@app.route('/pdf/<id>', methods=['GET'])
def index_by_id(id):
    results = es.get(index='pdfclearn', doc_type='_doc', id=id)
    return jsonify(results['_source'])

@app.route('/search/<keyword>', methods=['POST','GET'])
def search(keyword):
    keyword = keyword

    body = {
        "query": {
            "multi_match": {
                "query": keyword,
                "fields": ["data"]
            }
        }
    }

    res = es.search(index="pdfclearn", doc_type="_doc", body=body)

    return jsonify(res['hits']['hits'])

@app.route("/searhbar")
def searhbar():
    return render_template("index.html")

@app.route("/searhbar/<string:box>")
def process(box):
    query = request.args.get('query')
    if box == 'names':
         keyword = box

    body = {
        "query": {
            "multi_match": {
                "query": keyword,
                "fields": ["data"]
            }
        }
    }

    res = es.search(index="pdfclearn", doc_type="_doc", body=body)

    return jsonify(res['hits']['hits'])

app.run(port=5003, debug=True)

In the above code we can search across all Pages for a keyword or phrase.

curl http://127.0.0.1:5003/search/test //it works!!

I Found a blog about how to dave PDF files as a Base64 index in ElasticSearch. I have seen DocuSign's API do this for document templating. However, I dont understand How to Jsonify the Base64 PDF in a way thats searchable for ElasticSearch.

curl "http://localhost:9200/pdftext/_doc/42"

curl -X POST "http://localhost:9200/pdf/_search?q=*"

I can retrieve the Base64 of a 700 Page document. But I think what I need is to Index and retrieve Each Page of the Document.

Blogs I Have Studied that got me part the way:

https://kb.objectrocket.com/elasticsearch/how-to-index-a-pdf-file-as-an-elasticsearch-index-267

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvi-full-text-search

endgame:

https://towardsdatascience.com/create-a-full-search-engine-via-flask-elasticsearch-javascript-d3js-and-bootstrap-275f9dc6efe1

I will continue to study Elastic Search and Base64 Encoding and decoding. But I would like some help getting to my goal. Any Detailed example would be much appreciated.

Body:
So i found a lib called scout and...got it to work!

from scout_client import Scout

# import libraries to help read and create PDF

import PyPDF2
from fpdf import FPDF
import base64
import os
from flask import Flask, jsonify, request, render_template,  json

client = Scout('http://localhost:8000')

for k in range(7,18):
    read_pdf = PyPDF2.PdfFileReader("books/%s.pdf"%(k))
    num = read_pdf.getNumPages()
    print ("PDF pages:", num)
    all_pages = []
    for page in range(num):
        data = read_pdf.getPage(page)
        page_text = data.extractText()
        all_pages.append(page_text)

    import requests
    for z in all_pages:
        url = 'http://localhost:8000/documents/'
        data = {'content': z, 'indexes': ['test13']}
        headers = {
        'Content-Type': 'application/json',
        }

        response = requests.post(url, data=json.dumps(data), headers=headers)

    print(response)

I can now loop though as many PDF's as I want locally

Post to the server for indexing

and search for keywords

Now I just need help with Making a basic front end with a search bar that calls data from a JSON response in python and flask.


答:
Try:</p>

```<code>with open(r'file.txt', 'r') as f:
    for line in f:
        if 'A' not in line or 'C' not in line:
            print(line)
</code>```

Title: Find specific string and output the whole line Python

Body:
I am having the following input txt file:

17,21.01.2019,0,0,0,0,E,75,meter tamper alarm
132,22.01.2019,64,296,225,996,A,,
150,23.01.2019,63,353,351,805,A,,
213,24.01.2019,64,245,244,970,A,,
201,25.01.2019,86,297,364,943,A,,
56,26.01.2019,73,678,678,1437,A,,
201,27.01.2019,83,654,517,1212,A,,
117,28.01.2019,58,390,202,816,A,,
69,29.01.2019,89,354,282,961,C,,
123,30.01.2019,53,267,206,852,A,,

Need to make a python program that can parse through the file.
I need to find all the lines not containing A or C and output those lines in a new file.
I'm completely stuck after trying several regex :( can you help me ?

Body:
Try:

with open(r'file.txt', 'r') as f:
    for line in f:
        if 'A' not in line or 'C' not in line:
            print(line)


问:
jQuery dropdown - CSS issues
Hey, if you to go: http://catonthecouchproductions.com/fish/ and those images under the dropdown are suppose to be hidden then appear on hover, I have this so far:

```<code>$(document).ready(function() {
    $('.btn-fishing-trip').hover(function() {
        $('.fishing-trip').slideDown("slow");
    }, function() {
        $('.fishing-trip').slideUp("slow");
    });
    $('.btn-combo').hover(function() {
        $('.combo').slideDown("slow");
    }, function() {
        $('.combo').slideUp("slow");
    });
});
</code>```

But it is behaving weird. Any suggestions on what I can do? I think since once goes up the other slides over taking its place. Should i use animate() not slideDown?

答:
try this: </p>

```<code>$(document).ready(function() {
    $('.btn-fishing-trip').hover(function() {
        $('.fishing-trip').slideDown("slow");
        $('.combo').slideUp("slow");
    });
    $('.btn-combo').hover(function() {
        $('.combo').slideDown("slow");
        $('.fishing-trip').slideUp("slow");
    });
});
</code>```

LastEditorDisplayName: Soviut

ContentLicense: CC BY-SA 2.5

Title: jQuery dropdown - CSS issues

Body:
Hey, if you to go: http://catonthecouchproductions.com/fish/ and those images under the dropdown are suppose to be hidden then appear on hover, I have this so far:

$(document).ready(function() {
    $('.btn-fishing-trip').hover(function() {
        $('.fishing-trip').slideDown("slow");
    }, function() {
        $('.fishing-trip').slideUp("slow");
    });
    $('.btn-combo').hover(function() {
        $('.combo').slideDown("slow");
    }, function() {
        $('.combo').slideUp("slow");
    });
});

But it is behaving weird. Any suggestions on what I can do? I think since once goes up the other slides over taking its place. Should i use animate() not slideDown?

Body:
try this:

$(document).ready(function() {
    $('.btn-fishing-trip').hover(function() {
        $('.fishing-trip').slideDown("slow");
        $('.combo').slideUp("slow");
    });
    $('.btn-combo').hover(function() {
        $('.combo').slideDown("slow");
        $('.fishing-trip').slideUp("slow");
    });
});

OwnerDisplayName: Bigballs


问:
isEqualToString not returning true
The "Stopping" statement never gets printed even if you type 'stop' when running the program. Is the initWithUTF8String: method introducing extra formatting?

```<code>int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    char holderText[256];

    fgets(holderText, 256, stdin);
    NSString *words = [[NSString alloc] initWithUTF8String:holderText];

    if ([words isEqualToString:@"stop"]) {

        NSLog(@"STOPPING");

    }
    NSLog(@"This is what you typed: %@", words);

    [pool drain];
    return 0;
}
</code>```

答:
Since fgets will probably include a trailing newline, you might want to do a trim of all newlines in the string by using stringByTrimmingCharactersInSet::

```<code>NSString *trimmed = [words stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

if([trimmed isEqualToString:@"stop"]]) {
  //...
}
</code>```

Title: isEqualToString not returning true

Body:
The "Stopping" statement never gets printed even if you type 'stop' when running the program. Is the initWithUTF8String: method introducing extra formatting?

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    char holderText[256];

    fgets(holderText, 256, stdin);
    NSString *words = [[NSString alloc] initWithUTF8String:holderText];

    if ([words isEqualToString:@"stop"]) {

        NSLog(@"STOPPING");

    }
    NSLog(@"This is what you typed: %@", words);

    [pool drain];
    return 0;
}

Body:
Since fgets will probably include a trailing newline, you might want to do a trim of all newlines in the string by using stringByTrimmingCharactersInSet::

NSString *trimmed = [words stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

if([trimmed isEqualToString:@"stop"]]) {
  //...
}


问:
How do i prevent the player from dragging an image outside the specified area?
I am trying to drag an Image in a certain area. For that I am using IDragHandler. To prevent the image to go outside the area, i put four box colliders in a square shape. The box was still moving out. So, I put the fixed timestep to 0.0001. Now, when the image goes out of boundry, it pushes back the image in the specified area which is fine but I want the image to stop moving out the boundary the moment it touch the edge of the image.
Here's my code:</p>

```<code>public class Draggable : MonoBehaviour, IDragHandler
{
    public GameObject box;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Triggered");

    }

    public void OnDrag(PointerEventData eventData)
    {
        box.transform.position = eventData.position;
    }
}
</code>```

答:
Don’t use physics and fixed timestep to solve this problem. It is performance killer to reduce timestep.

One way to do it : use Physics.OverlapBox ( see documentation https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html)

Do this test between your draggable object and the limit of your draggable zone in your OnDrag method. Calculate the « Wanted » position base on the event you receive and if your object overlap with your borders then dont move it, if not your are safe and you can move it.

Body:
I am trying to drag an Image in a certain area. For that I am using IDragHandler. To prevent the image to go outside the area, i put four box colliders in a square shape. The box was still moving out. So, I put the fixed timestep to 0.0001. Now, when the image goes out of boundry, it pushes back the image in the specified area which is fine but I want the image to stop moving out the boundary the moment it touch the edge of the image.
Here's my code:

public class Draggable : MonoBehaviour, IDragHandler
{
    public GameObject box;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Debug.Log("Triggered");

    }

    public void OnDrag(PointerEventData eventData)
    {
        box.transform.position = eventData.position;
    }
}


答:
Try

```<code>with open('filename') as f:
    for line in f.readlines():
        if 'A' not in line or 'C' not in line:
            print(line)
</code>```

OR Better, as your file content seems to resemble a csv(Comma Seperated Values) format, use pandas for better manipulations

Read the file

```<code>import pandas as pd
df = pd.read_csv('filename', header=None, sep=',')

     0           1   2    3    4     5  6     7                   8
0   17  21.01.2019   0    0    0     0  E  75.0  meter tamper alarm
1  132  22.01.2019  64  296  225   996  A   NaN                 NaN
2  150  23.01.2019  63  353  351   805  A   NaN                 NaN
3  213  24.01.2019  64  245  244   970  A   NaN                 NaN
4  201  25.01.2019  86  297  364   943  A   NaN                 NaN
5   56  26.01.2019  73  678  678  1437  A   NaN                 NaN
6  201  27.01.2019  83  654  517  1212  A   NaN                 NaN
7  117  28.01.2019  58  390  202   816  A   NaN                 NaN
8   69  29.01.2019  89  354  282   961  C   NaN                 NaN
9  123  30.01.2019  53  267  206   852  A   NaN                 NaN
</code>```

Output

```<code>print(df[~df[6].str.contains('A|C', regex=True)])

    0           1  2  3  4  5  6     7                   8
0  17  21.01.2019  0  0  0  0  E  75.0  meter tamper alarm
</code>```

Body:
Try

with open('filename') as f:
    for line in f.readlines():
        if 'A' not in line or 'C' not in line:
            print(line)

OR Better, as your file content seems to resemble a csv(Comma Seperated Values) format, use pandas for better manipulations

Read the file

import pandas as pd
df = pd.read_csv('filename', header=None, sep=',')

     0           1   2    3    4     5  6     7                   8
0   17  21.01.2019   0    0    0     0  E  75.0  meter tamper alarm
1  132  22.01.2019  64  296  225   996  A   NaN                 NaN
2  150  23.01.2019  63  353  351   805  A   NaN                 NaN
3  213  24.01.2019  64  245  244   970  A   NaN                 NaN
4  201  25.01.2019  86  297  364   943  A   NaN                 NaN
5   56  26.01.2019  73  678  678  1437  A   NaN                 NaN
6  201  27.01.2019  83  654  517  1212  A   NaN                 NaN
7  117  28.01.2019  58  390  202   816  A   NaN                 NaN
8   69  29.01.2019  89  354  282   961  C   NaN                 NaN
9  123  30.01.2019  53  267  206   852  A   NaN                 NaN

Output

print(df[~df[6].str.contains('A|C', regex=True)])

    0           1  2  3  4  5  6     7                   8
0  17  21.01.2019  0  0  0  0  E  75.0  meter tamper alarm


问:
Load a text file with values into a tuple in Python
I have text file file.txt with values like this:

```<code>word1
word2
word3
word4
word5
</code>```

What I want is a tuple like this in Python 3:

```<code>my_tuple = ('word1','word2','word3','word4','word5')
</code>```

Any advice?

答:
You can create a list and then convert it into a tuple.

```<code>import os.path
text_file = open("file.txt", encoding="utf8")
my_list = []

for line in text_file:
    my_list.append(line)

my_tuple = tuple(my_list)
print(my_tuple)
print(type(my_tuple))
</code>```

Body:
I have text file file.txt with values like this:

word1
word2
word3
word4
word5

What I want is a tuple like this in Python 3:

my_tuple = ('word1','word2','word3','word4','word5')

Any advice?

Body:
You can create a list and then convert it into a tuple.

import os.path
text_file = open("file.txt", encoding="utf8")
my_list = []

for line in text_file:
    my_list.append(line)

my_tuple = tuple(my_list)
print(my_tuple)
print(type(my_tuple))


问:
Filling VB.net datatable with result of SQl query (link to microsoft access relational database)
Hello I was wondering if someone could help me.
I need to output the result of an SQL query on a relational database. I wanted the output to be just like the table you see if you execute the query in Microsoft Access.  For this I used a VB.net Data Grid. I see the result of simple queries such as...

"SELECT * FROM Form;"

however if I try to add any more detail to the SQL statement than that (even just a WHERE), the code throws the error System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
The specific SQL statement I need is...

"SELECT [Student data].[Student First Name], [Student data].[Student Last Name], [Student data].Severity, [Student data].[Form group] FROM Form INNER JOIN [Student data] ON Form.[Form group] = [Student data].[Form group] WHERE ((([Student data].Severity)= High));"

This is my current simple code that works:

```<code>Private Sub data_table()
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
        datafile = "P:\Documents\SCHOOL WORK\A level\COMPUTER SCIENCE\PROJECT\Visual basic\Student Data.accdb"
        connstring = provider & datafile
        myconnection.ConnectionString = connstring
        myconnection.Open()
        Dim command As New OleDbCommand("SELECT * FROM Form;", myconnection)
        Dim reader As OleDbDataReader = command.ExecuteReader()
        Dim dt As New DataTable()
        dt.Load(reader)
        DataGridView1.DataSource = dt
        myconnection.Close()
End Sub
</code>```

And this is the code which shows the error:

```<code>Private Sub data_table()
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
        datafile = "P:\Documents\SCHOOL WORK\A level\COMPUTER SCIENCE\PROJECT\Visual basic\Student Data.accdb"
        connstring = provider & datafile
        myconnection.ConnectionString = connstring
        myconnection.Open()
        Dim command As New OleDbCommand("SELECT [Student data].[Student First Name], [Student data]. [Student Last Name], [Student data].Severity, [Student data].[Form group] FROM Form INNER JOIN [Student data] ON Form.[Form group] = [Student data].[Form group] WHERE ((([Student data].Severity)= High));", myconnection)
        Dim reader As OleDbDataReader = command.ExecuteReader()
        Dim dt As New DataTable()
        dt.Load(reader)
        DataGridView1.DataSource = dt
        myconnection.Close()
End Sub
</code>```

Please can you help me I'm quite lost.
Thank you :)

答:
Most database objects need to be not only closed but also disposed. Using...End Using blocks handle this for you even if there is an error. A single Using block handles both the connection and the command here.

Once the connection and command are closed and disposed by the End Using, we update the user interface.

I really don't get why you needed a Join in your query. All the data was being pulled from the same table and the Where clause referenced the same table.

```<code>Private Sub data_table()
    Dim dt As New DataTable
    Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Documents\SCHOOL WORK\A level\COMPUTER SCIENCE\PROJECT\Visual basic\Student Data.accdb;"),
            cmd As New OleDbCommand("SELECT
                            [Student First Name],
                            [Student Last Name],
                            Severity,
                            [Form group]
                            FROM [Student data]  WHERE Severity= 'High'));", cn)
        cn.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
    DataGridView1.DataSource = dt
End Sub
</code>```

Body:
Hello I was wondering if someone could help me.
I need to output the result of an SQL query on a relational database. I wanted the output to be just like the table you see if you execute the query in Microsoft Access.  For this I used a VB.net Data Grid. I see the result of simple queries such as...

"SELECT * FROM Form;"

however if I try to add any more detail to the SQL statement than that (even just a WHERE), the code throws the error System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
The specific SQL statement I need is...

"SELECT [Student data].[Student First Name], [Student data].[Student Last Name], [Student data].Severity, [Student data].[Form group] FROM Form INNER JOIN [Student data] ON Form.[Form group] = [Student data].[Form group] WHERE ((([Student data].Severity)= High));"

This is my current simple code that works:

Private Sub data_table()
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
        datafile = "P:\Documents\SCHOOL WORK\A level\COMPUTER SCIENCE\PROJECT\Visual basic\Student Data.accdb"
        connstring = provider & datafile
        myconnection.ConnectionString = connstring
        myconnection.Open()
        Dim command As New OleDbCommand("SELECT * FROM Form;", myconnection)
        Dim reader As OleDbDataReader = command.ExecuteReader()
        Dim dt As New DataTable()
        dt.Load(reader)
        DataGridView1.DataSource = dt
        myconnection.Close()
End Sub

And this is the code which shows the error:

Private Sub data_table()
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
        datafile = "P:\Documents\SCHOOL WORK\A level\COMPUTER SCIENCE\PROJECT\Visual basic\Student Data.accdb"
        connstring = provider & datafile
        myconnection.ConnectionString = connstring
        myconnection.Open()
        Dim command As New OleDbCommand("SELECT [Student data].[Student First Name], [Student data]. [Student Last Name], [Student data].Severity, [Student data].[Form group] FROM Form INNER JOIN [Student data] ON Form.[Form group] = [Student data].[Form group] WHERE ((([Student data].Severity)= High));", myconnection)
        Dim reader As OleDbDataReader = command.ExecuteReader()
        Dim dt As New DataTable()
        dt.Load(reader)
        DataGridView1.DataSource = dt
        myconnection.Close()
End Sub

Please can you help me I'm quite lost.
Thank you :)

Body:
Most database objects need to be not only closed but also disposed. Using...End Using blocks handle this for you even if there is an error. A single Using block handles both the connection and the command here.

Once the connection and command are closed and disposed by the End Using, we update the user interface.

I really don't get why you needed a Join in your query. All the data was being pulled from the same table and the Where clause referenced the same table.

Private Sub data_table()
    Dim dt As New DataTable
    Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Documents\SCHOOL WORK\A level\COMPUTER SCIENCE\PROJECT\Visual basic\Student Data.accdb;"),
            cmd As New OleDbCommand("SELECT
                            [Student First Name],
                            [Student Last Name],
                            Severity,
                            [Form group]
                            FROM [Student data]  WHERE Severity= 'High'));", cn)
        cn.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
    DataGridView1.DataSource = dt
End Sub


答:
The code looks fine, even though you're leaking the words string. You need to add an [autorelease] on the end of that alloc call.

You could try initWithCString and also trim new lines and surrounding whitespace.

```<code>NSString *words = [[[NSString alloc] initWithCString:holderText] autorelease];
words = [words stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
</code>```

Title: isEqualToString not returning true

Body:
The code looks fine, even though you're leaking the words string. You need to add an [autorelease] on the end of that alloc call.

You could try initWithCString and also trim new lines and surrounding whitespace.

NSString *words = [[[NSString alloc] initWithCString:holderText] autorelease];
words = [words stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];


答:
You can use a forEach loop. Array cannot have key and value pairs like objects so an extra object has to be made so as to keys the values with numbered keys

var x=[
  {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
  {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
  {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]
var obj={};
x.forEach((e,j)=>{
obj[j+'=>']=e;
})
x=[obj]
console.log(x)```

Title: Convert js object array into associative array

Body:
By using array.push() I'm updating a following array. I want to add index/key to every object in the object array as I want to check is a record exist with same index/key before pushing new item.

My array is like

$data = [
  {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
  {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
  {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]

and i want to convert this like

[
    0 => {
    "id": 37,
    "permit_id": 1,
    "document_description": "zzxc",
    "file_name": "zxc"
  },
    1 => {
    "permit_id": "1",
    "document_description": "aa",
    "file_name": "az"
  },
    2 => {
    "permit_id": "1",
    "document_description": "aax",
    "file_name": "azx"
  }
]

Is there any way to do this? please give me an idea.
Thank you!


问:
IONIC 5: Issues in changing Events to Observable
Since Ionic 5 came out I decided to try it out.
I have learned that they are now using Oberservables instead of Events.
I have the following event in my code:

Subscribing like this in my constructor:

```<code>                this.events.subscribe('go-to-slide', (tab, id) => {
  this.currentID = id;
  if (id === 0) {
    this.showLeftButton = false;
  }
  // if data has already been loaded
  if (this.dataLoadedFlag === true) {
    // from tile
    if (this.globalVariableService.comesFromTileClick === true) {
      if (this.globalVariableService.languageChanged === true) {
        this.languageChanged = false;
        this.slidesComponent.slides.slideTo(id, 0);
        this.getSectorTitlesAndColours();
        this.dataLoadedFlag = true;
        this.updateHeader(id);
      } else if (this.globalVariableService.languageChanged === false) {
        this.updateHeader(id);
      }
    } else if (this.globalVariableService.comesFromTileClick === false) {

    }
  } else if (this.dataLoadedFlag === false) {

    if (this.globalVariableService.comesFromTileClick === true) {
      this.slidesComponent.slides.slideTo(id, 0);
      this.getSectorTitlesAndColours();
      this.dataLoadedFlag = true;
      this.updateHeader(id);
    } else if (this.globalVariableService.comesFromTileClick === false) {
      this.getSectorTitlesAndColours();
      this.showRightButton = true;
      this.dataLoadedFlag = true;
      this.updateHeader(0);
    }
  }
  const tempGlobalVariableService = this.globalVariableService;
  // tslint:disable-next-line: only-arrow-functions
  setTimeout(function() {
    tempGlobalVariableService.comesFromTileClick = false;
  }, 500);
});
}
</code>```

and publishing the event like this in different components/methods:

```<code>this.events.publish('go-to-slide', 1, 1);
</code>```

I tried different ways to change this code to observable but I can't seem to find the right way.

Anyone tried this already and can help me out?
Thanks

答:
I have already answered it here https://stackoverflow.com/a/60246906/2405040

You can create a small service for that like:

```<code>import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class GlobalFooService {

    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}
</code>```

For a complete example, please refer to the other answer.

And by the way, to discuss on this comment:

I have learned that they are now using Oberservables instead of Events

This is not that true. Basically, they have removed the Events service from Ionic 5 and asking us to use the Observables instead, by creating our own similar implementation.

They might have been using the Events internally since Ionic 3. But since Ionic 4that, they have removed the internal usage as Obersables has grown so much and it's a kind of backbone to both Angular & Ionic.

Body:
Since Ionic 5 came out I decided to try it out.
I have learned that they are now using Oberservables instead of Events.
I have the following event in my code:

Subscribing like this in my constructor:

                this.events.subscribe('go-to-slide', (tab, id) => {
  this.currentID = id;
  if (id === 0) {
    this.showLeftButton = false;
  }
  // if data has already been loaded
  if (this.dataLoadedFlag === true) {
    // from tile
    if (this.globalVariableService.comesFromTileClick === true) {
      if (this.globalVariableService.languageChanged === true) {
        this.languageChanged = false;
        this.slidesComponent.slides.slideTo(id, 0);
        this.getSectorTitlesAndColours();
        this.dataLoadedFlag = true;
        this.updateHeader(id);
      } else if (this.globalVariableService.languageChanged === false) {
        this.updateHeader(id);
      }
    } else if (this.globalVariableService.comesFromTileClick === false) {

    }
  } else if (this.dataLoadedFlag === false) {

    if (this.globalVariableService.comesFromTileClick === true) {
      this.slidesComponent.slides.slideTo(id, 0);
      this.getSectorTitlesAndColours();
      this.dataLoadedFlag = true;
      this.updateHeader(id);
    } else if (this.globalVariableService.comesFromTileClick === false) {
      this.getSectorTitlesAndColours();
      this.showRightButton = true;
      this.dataLoadedFlag = true;
      this.updateHeader(0);
    }
  }
  const tempGlobalVariableService = this.globalVariableService;
  // tslint:disable-next-line: only-arrow-functions
  setTimeout(function() {
    tempGlobalVariableService.comesFromTileClick = false;
  }, 500);
});
}

and publishing the event like this in different components/methods:

this.events.publish('go-to-slide', 1, 1);

I tried different ways to change this code to observable but I can't seem to find the right way.

Anyone tried this already and can help me out?
Thanks

Body:
I have already answered it here https://stackoverflow.com/a/60246906/2405040

You can create a small service for that like:

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class GlobalFooService {

    private fooSubject = new Subject<any>();

    publishSomeData(data: any) {
        this.fooSubject.next(data);
    }

    getObservable(): Subject<any> {
        return this.fooSubject;
    }
}

For a complete example, please refer to the other answer.

And by the way, to discuss on this comment:

I have learned that they are now using Oberservables instead of Events

This is not that true. Basically, they have removed the Events service from Ionic 5 and asking us to use the Observables instead, by creating our own similar implementation.

They might have been using the Events internally since Ionic 3. But since Ionic 4that, they have removed the internal usage as Obersables has grown so much and it's a kind of backbone to both Angular & Ionic.


问:
jQuery: How to open file open dialog box on click button
How can I make a dialog box open on click of button on swallow rendering.
It can be dynamically repeatable button as it is inside li.

//Code

```<code>var wrapper = $(this).parents(".file-upload-wrapper")[0];
$(wrapper).find('.attachment-button-div')[0].click(function() {
 $(wrapper).find('.attachment-button')[0].trigger('click');

});

$(wrapper).find('.file-upload').change(function() {
 $('input[type=text]').val($(this).val());
});
</code>```

But it is not working as expected . Any suggestion.

答:
why you don't simply use input tag with file type? It opens the choose file dialog box.

Please choose your attachment:

<form action="">
  Select files:
  <input type="file" id="myfile" name="myfile" multiple>

  <input type="submit">
</form>```

Body:
How can I make a dialog box open on click of button on swallow rendering.
It can be dynamically repeatable button as it is inside li.

//Code

var wrapper = $(this).parents(".file-upload-wrapper")[0];
$(wrapper).find('.attachment-button-div')[0].click(function() {
 $(wrapper).find('.attachment-button')[0].trigger('click');

});

$(wrapper).find('.file-upload').change(function() {
 $('input[type=text]').val($(this).val());
});

But it is not working as expected . Any suggestion.

Body:
why you don't simply use input tag with file type? It opens the choose file dialog box.

<h3>Please choose your attachment:</h3>
<form action="">
  <label for="myfile">Select files:</label>
  <input type="file" id="myfile" name="myfile" multiple><br><br>
  <input type="submit">
</form>


问:
Angular 2 : No NgModule metadata found
I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found. Despite following all of the steps, Angular just won't work; I get the following error:

```<code>compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.
</code>```

and the component doesn't load at all.

Here are my files:

package.json:

```<code>{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}
</code>```

index.html:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">
  </head>
  <body>

    <app>
      ... before angular loads.
    </app>

    <script src="polyfills.bundle.js"></script>
    <script src="vendor.bundle.js"></script>
    <script src="main.bundle.js"></script>

  </body>
</html>
</code>```

main.ts:

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

app.ts:

```<code>import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `
    <div>
      <h3>
        Yo, world!
      </h3>
    </div>
    `
})

export class App {}
</code>```

app.module.ts:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})

export class AppModule{};
</code>```

Thanks for your time.

答:
This error says necessary data for your module can't be found.
In my case i missed an @ symbol in start of NgModule.

Correct NgModule definition:

```<code> @NgModule ({
    ...
 })
 export class AppModule {

 }
</code>```

My case (Wrong case) :

```<code>NgModule ({ // => this line must starts with @
   ...
})
export class AppModule {

}
</code>```

Title: Angular 2 : No NgModule metadata found

Body:
I'm brand new to Angular 2 and attempting to follow along with a video tutorial I found. Despite following all of the steps, Angular just won't work; I get the following error:

compiler.umd.js:13854 Uncaught Error: No NgModule metadata found for 'App'.

and the component doesn't load at all.

Here are my files:

package.json:

{
  "name": "retain",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "webpack --config webpack.spec.ts --progress --color && karma start",
    "start": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000  --content-base src"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "core-js": "2.4.1",
    "lodash": "4.16.1",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.25"
  },
  "devDependencies": {
    "@types/core-js": "0.9.33",
    "@types/lodash": "4.14.35",
    "@types/node": "6.0.39",
    "awesome-typescript-loader": "2.2.4",
    "css-loader": "0.23.1",
    "jasmine-core": "2.4.1",
    "karma": "1.1.1",
    "karma-chrome-launcher": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-mocha-reporter": "2.0.4",
    "raw-loader": "0.5.1",
    "to-string-loader": "1.1.4",
    "ts-helpers": "1.1.1",
    "typescript": "2.0.2",
    "webpack": "1.13.1",
    "webpack-dev-server": "1.14.1"
  }
}

index.html:

<!DOCTYPE html>

    <meta charset=UTF-8>
    <title>Retain</title>
    <link rel="icon" href="data:;base64,iVBORw0KGgo=">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='https://cdnjs.cloudflare.com/ajax/libs/normalize/4.1.1/normalize.min.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/flexboxgrid/6.3.0/flexboxgrid.min.css" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link href="global.css" rel="stylesheet">
    <base href="/">

    <app>
      ... before angular loads.
    </app>

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

import { App } from './app/app';

const platform = platformBrowserDynamic();
platform.bootstrapModule(App);

platformBrowserDynamic().bootstrapModule(AppModule);

app.ts:

import { Component } from '@angular/core';
import { NgModule }      from '@angular/core';

@Component({
  selector: 'app',
  template: `

        Yo, world!

    `
})

export class App {}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { App } from './app';

@NgModule({
  imports: [BrowserModule],
  declarations: [App],
  bootstrap: [App]
})

export class AppModule{};

Thanks for your time.

Body:
This error says necessary data for your module can't be found.
In my case i missed an @ symbol in start of NgModule.

Correct NgModule definition:

 @NgModule ({
    ...
 })
 export class AppModule {

 }

My case (Wrong case) :

NgModule ({ // => this line must starts with @
   ...
})
export class AppModule {

}


问:
How to convert a nested json string into accessible structure in C# for printing select items?
Which procedure and data-structure should I use that will give me access all the key-value pairs in a nested JSON string in C#?

Pictured below is a portion of the JSON string I am working with. As you can see it is nested. I am seeking to retrieve the "date" and "message" from each block with their respective keys using C-Sharp C#.

I have tried putting my JSON string into a Dictionary.

```<code>private static async Task<String> ProcessRepo()
{

   var stringTask = APIclient.GetStringAsync("https://a.RESTapi.fakecom");
   var x = await stringTask;
   Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(x);

   return data;
}
</code>```

This gives me 2 key-values pairs. One is "pagelen" with a value of 30, and the other is "values" with a value of everything that followed in one long string. Not very useful.

This is my first time using C#.  Please point me in the right direction. I have spent many hours searching for something that will work.

答:
The clear solution depends on your goals, but simplest way is something like this:</p>

```<code>var obj = JsonConvert.DeserializeObject(json);
foreach (var jo in (JArray)((JObject)obj)["values"])
{
     Console.WriteLine($"{jo["message"]}, {jo["date"]}");
}
</code>```

Body:
Which procedure and data-structure should I use that will give me access all the key-value pairs in a nested JSON string in C#?

Pictured below is a portion of the JSON string I am working with. As you can see it is nested. I am seeking to retrieve the "date" and "message" from each block with their respective keys using C-Sharp C#.

I have tried putting my JSON string into a Dictionary.

private static async Task<String> ProcessRepo()
{

   var stringTask = APIclient.GetStringAsync("https://a.RESTapi.fakecom");
   var x = await stringTask;
   Dictionary<string, object> data = JsonConvert.DeserializeObject<Dictionary<string, object>>(x);

   return data;
}

This gives me 2 key-values pairs. One is "pagelen" with a value of 30, and the other is "values" with a value of everything that followed in one long string. Not very useful.

This is my first time using C#.  Please point me in the right direction. I have spent many hours searching for something that will work.

Body:
The clear solution depends on your goals, but simplest way is something like this:

var obj = JsonConvert.DeserializeObject(json);
foreach (var jo in (JArray)((JObject)obj)["values"])
{
     Console.WriteLine($"{jo["message"]}, {jo["date"]}");
}


问:
Background image responsive without getting cropped
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page </p>

```<code><div class="inner-banner has-base-color-overlay text-center" style="background: url(header.jpg); background-size: cover; position: center;">
    <div class="container">
        <div class="box">
            <h3>About Us</h3>
        </div>
    </div>
</div>
</code>```

答: If you are using background image and You want see in mobile view then it will be cut off of the background image you need to call img src.</p>

Body:
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page

About Us