问:
asp.net vb CheckBoxList Selected from CSV
I am learning asp.net and needed to have a CheckBoxList which items will be initially selected if the are in a CSV string from a database.

I have got it working although I just wondered if I have gone about it the best way as it seemed a little long winded?

Thanks for any help provided.

ASPX

```<code><asp:CheckBoxList ID="rh_type" runat="server" CssClass="chkbox"
RepeatLayout="Flow" CausesValidation="True">
<asp:ListItem>House</asp:ListItem>
<asp:ListItem>Flat/Apartment</asp:ListItem>
<asp:ListItem>Bungalow</asp:ListItem>
<asp:ListItem>Any</asp:ListItem>
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
</code>```

CODE

```<code>    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim i As Integer
    Dim str_rh_type As String = "House,Bungalow"
    Dim split As String() = str_rh_type.Split(","c)

    For Each s As String In split
        'Response.Write(s & "<br />")

        For i = 0 To rh_type.Items.Count - 1
            If rh_type.Items(i).Text = s Then

                rh_type.Items(i).Selected = True

            End If
        Next

    Next s

End Sub
</code>```

Thanks again
J.

答:
Your code is functional but maybe some tweaking for maintainability would help.  Also not sure you necessarily need nested loops to load your drop down items.

This should be just a reference point to make your own decisions on coding practices.  Certainly what works for some doesn't work for others.

Here's how I'd code this...

ASP.NET Control:

```<code><asp:CheckBoxList ID="CheckBoxListHomeType" runat="server"
    CssClass="chkbox" RepeatLayout="Flow" CausesValidation="True" />
...
</code>```

ID of CheckBoxListHomeType is easy to remember and intellisense will get me the rest of the way. (or another common approach would be cblHomeType as the ID).  Getting intellisense to help on a name like rh_type may be just as easy but IDs that resemble what kind of control it is can really help when maintaining code

VB.NET:

```<code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        LoadHomeTypes()
    End If
End Sub

Protected Sub LoadHomeTypes()
    Dim houseTypes = "House,Bungalow,Flat/Apartment,Any"
    For Each houseType As String In houseTypes.Split(",")
        CheckBoxListHomeType.Items.Add(New ListItem(houseType))
    Next
End Sub
</code>```

Keeping the logic in a separate LoadHomeTypes function can make the code more readable.

Creating a new ListItem while iterating the list of homeTypes should remove the need to iterate over the CheckBoxList items, (if you need to clear out the existing ones you can add CheckBoxListHomeType.Items.Clear() to the top of the function)

the Not Page.IsPostBack check prevents the need for loading the drop down values every postback, unless you have need for them to change.

Body:
I am learning asp.net and needed to have a CheckBoxList which items will be initially selected if the are in a CSV string from a database.

I have got it working although I just wondered if I have gone about it the best way as it seemed a little long winded?

Thanks for any help provided.

ASPX

<asp:CheckBoxList ID="rh_type" runat="server" CssClass="chkbox"
RepeatLayout="Flow" CausesValidation="True">
<asp:ListItem>House</asp:ListItem>
<asp:ListItem>Flat/Apartment</asp:ListItem>
<asp:ListItem>Bungalow</asp:ListItem>
<asp:ListItem>Any</asp:ListItem>
</asp:CheckBoxList>

<asp:Button ID="Button1" runat="server" Text="Button" />

CODE

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim i As Integer
    Dim str_rh_type As String = "House,Bungalow"
    Dim split As String() = str_rh_type.Split(","c)

    For Each s As String In split
        'Response.Write(s & "
")

        For i = 0 To rh_type.Items.Count - 1
            If rh_type.Items(i).Text = s Then

                rh_type.Items(i).Selected = True

            End If
        Next

    Next s

End Sub

Thanks again
J.

Body:
Your code is functional but maybe some tweaking for maintainability would help.  Also not sure you necessarily need nested loops to load your drop down items.

This should be just a reference point to make your own decisions on coding practices.  Certainly what works for some doesn't work for others.

Here's how I'd code this...

ASP.NET Control:

<asp:CheckBoxList ID="CheckBoxListHomeType" runat="server"
    CssClass="chkbox" RepeatLayout="Flow" CausesValidation="True" />
...

ID of CheckBoxListHomeType is easy to remember and intellisense will get me the rest of the way. (or another common approach would be cblHomeType as the ID).  Getting intellisense to help on a name like rh_type may be just as easy but IDs that resemble what kind of control it is can really help when maintaining code

VB.NET:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        LoadHomeTypes()
    End If
End Sub

Protected Sub LoadHomeTypes()
    Dim houseTypes = "House,Bungalow,Flat/Apartment,Any"
    For Each houseType As String In houseTypes.Split(",")
        CheckBoxListHomeType.Items.Add(New ListItem(houseType))
    Next
End Sub

Keeping the logic in a separate LoadHomeTypes function can make the code more readable.

Creating a new ListItem while iterating the list of homeTypes should remove the need to iterate over the CheckBoxList items, (if you need to clear out the existing ones you can add CheckBoxListHomeType.Items.Clear() to the top of the function)

the Not Page.IsPostBack check prevents the need for loading the drop down values every postback, unless you have need for them to change.


来源: stackexchange

问:
Chrome interprets ISO time without Z as UTC; C# issue
Run this jsfiddle: http://jsfiddle.net/E9gq9/7/ on Chrome, FF, and IE and you get:

Chrome:

Chrome http://images.devs-on.net/Image/vBTz86J0f4o8zlL3-Region.png

Firefox:

Firefox http://images.devs-on.net/Image/aNPxNPUpltyjVpSX-Region.png

IE:

IE http://images.devs-on.net/Image/WXLM5Ev1Viq4ecFq-Region.png

Safari:

Safari http://images.devs-on.net/Image/AEcyUouX04k2yIPo-Region.png

ISO 8601 does not appear to say how a string without a trailing Z should be interpreted.

Our server (ASP.NET MVC4) is pulling UTC times out of our database as DateTimes and simply stuffing them in JSON. As you can see because of this we are getting inconsistent results on the browser.

Should we just append Z to them on the server side?

答:
In addition to @tig's answer (which was exactly what I was looking for):

Here's the solution for .NetCore 1

```<code>services.AddMvc();
services.Configure<MvcJsonOptions>(o =>
{
    o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
});
</code>```

or

```<code>services.AddMvc().AddJsonOptions(o => o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);
</code>```

For .NetCore 1.0.1

```<code>services
    .AddMvcCore()
    .AddJsonFormatters(o => o...);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In addition to @tig's answer (which was exactly what I was looking for):

Here's the solution for .NetCore 1

services.AddMvc();
services.Configure<MvcJsonOptions>(o =>
{
    o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
});

or

services.AddMvc().AddJsonOptions(o => o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc);

For .NetCore 1.0.1

services
    .AddMvcCore()
    .AddJsonFormatters(o => o...);

ContentLicense: CC BY-SA 4.0


问:
Fastest method to find a complex type in a list (Vector, Array, Dictionary, whatever is faster)
Hail, Stack!

I need to know the best method to find an item inside a list (Vector, Array, Dictionary, whatever is faster) of complex type (extensions of Objects and Sprites).

I've used "Needle in Haystack" method, but it seems that it isn't fast enough.

E.g.
Suppose that I have a collection of Sprites (a pool, in fact).

Each sprite will be added to the stage and perform some action. After that, it will die.

I don't want to pay the cost to dispose it (garbage collect) and create another (new) one every time so I'll keep the dead sprites in a collection.

Sometimes times I'll call a method that will add a sprite to the stage.

This sprite can be a old one, if it is already dead, or a new one, if the pool don't have any free sprite.

One of the scenarios that pushed me to this question was a Particle System.

A "head" particle leaving a "trail" of particles every frame and exploding into a flashy multitude of particles... Every frame...

Some times this counts up to 50.000 PNGs with motion, rotation, alpha, event dispatching, scale, etc...

But, this is JUST ONE scenario...

At the moment I'm trying to use a Object Pool with a Linked List...

Hopes that it will be faster that running a whole Array/Vector or create new instances every frame an let them dye with Garbage Collection.

Someone knows a better/faster way to do it?

答:
This is really going to depend on how you need to identify the object. Are you comparing some value of it or comparing references?

Assuming references, you should be using the built in methods found on both Array & Vector. Linear searches (like looping over the entire list) grow slower as the number of items in the list increases. The built in solutions will use faster non-linear search algorithms. For example:

```<code>myList.indexOf(myObject);
</code>```

The fastest thing you can do is direct access. If you are using either an Object or Dictionary you can use the object or a unique id as the key, this gives you direct access. But this doesn't help if you need the objects position in the list. eg:

```<code>//when setting it
var map = {};
map[myObject] = myObject;
//or
map[myObject.id] = myObject;

//then later
var myObject = map[THE KEY]
</code>```

Body:
This is really going to depend on how you need to identify the object. Are you comparing some value of it or comparing references?

Assuming references, you should be using the built in methods found on both Array & Vector. Linear searches (like looping over the entire list) grow slower as the number of items in the list increases. The built in solutions will use faster non-linear search algorithms. For example:

myList.indexOf(myObject);

The fastest thing you can do is direct access. If you are using either an Object or Dictionary you can use the object or a unique id as the key, this gives you direct access. But this doesn't help if you need the objects position in the list. eg:

//when setting it
var map = {};
map[myObject] = myObject;
//or
map[myObject.id] = myObject;

//then later
var myObject = map[THE KEY]


问:
echo language construct is discouraged. (PHP)
why codacy(code review tool) showing "echo language construct is discouraged."

how to solve this issue.

1:

答:
Codacy detects linting problems on your code base. Linting problems may be security bugs, code style issues, etc.

In your case, it's bad practice to use php "echo". Just like you shouldn't use println in other languages. If you need to print something, you should use loggers


问:
Reading through a .m File and Python keeps reading a character in the .m File as a line?
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.

I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.

# Example of what I did
with open('MyFile.m') as f:
   for line in f:
       text = f.readline()
       if text.startswith('%'):
         continue
       else:
          my_string = text.strip("=")
          my_list.append(my_string)
```

This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e  S t r i n g"

答:
As suggested by Xander, you shouldn't call readline since the for line in f does that for you.

```<code>my_list = []
with open('MyFile.m') as f:
   for line in f:
       line = line.strip()   # lose the \n if you want to
       if line.startswith('%'):
           continue
       else:
           my_string = line.strip("=")
           my_list.append(my_string)
</code>```

Body:
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.

I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.

# Example of what I did
with open('MyFile.m') as f:
   for line in f:
       text = f.readline()
       if text.startswith('%'):
         continue
       else:
          my_string = text.strip("=")
          my_list.append(my_string)

This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e  S t r i n g"

Body:
As suggested by Xander, you shouldn't call readline since the for line in f does that for you.

my_list = []
with open('MyFile.m') as f:
   for line in f:
       line = line.strip()   # lose the \n if you want to
       if line.startswith('%'):
           continue
       else:
           my_string = line.strip("=")
           my_list.append(my_string)


问:
linux systemd service on port 80
I try to create systemd service on centos7:

```<code>[Unit]
Description=Node.js Weeki Server
Requires=After=mongod.service

[Service]
ExecStart=/usr/bin/node /var/node/myapp/bin/www
Restart=always
StandardOutput=syslog               # Output to syslog
StandardError=syslog                # Output to syslog
SyslogIdentifier=nodejs-weeki
User=weeki
Environment=NODE_ENV=production PORT=80

[Install]
WantedBy=multi-user.target
</code>```

When i use port 8080 the service start successfully, but when i change the port to 80, the service failed to start.
I try to open the firewall with the command:

```<code>firewall-cmd --zone=public --add-port=80/tcp --permanent
</code>```

But it still not working.

答: User should have root privileges to open ports below 1024.</p>

Title: linux systemd service on port 80

Body:
I try to create systemd service on centos7:

[Unit]
Description=Node.js Weeki Server
Requires=After=mongod.service

[Service]
ExecStart=/usr/bin/node /var/node/myapp/bin/www
Restart=always
StandardOutput=syslog               # Output to syslog
StandardError=syslog                # Output to syslog
SyslogIdentifier=nodejs-weeki
User=weeki
Environment=NODE_ENV=production PORT=80

[Install]
WantedBy=multi-user.target

When i use port 8080 the service start successfully, but when i change the port to 80, the service failed to start.
I try to open the firewall with the command:

firewall-cmd --zone=public --add-port=80/tcp --permanent

But it still not working.


问:
Is there an easy way to nest functions together so they run as one from a single raw_input?
I am having some issues nesting my functions together. The purpose of my program is to take a file, create a backup then change the name of the backup copy and original copy. Currently, I have to enter the filename with the additional filename extension to make this happen, I am fairly new at programming and have appreciated the help I have gotten so far on this script and will gladly take anymore feedback. Thanks in advance!

Here is my working code that does this. In my data folder I always start with a filename.vr (10000.vr) and its backup filename.vrb (10000.vrb).

```<code>
import os, sys, shutil, copy

# This creates the copy of the .vrb file

def copy_vrb(oldvrb):
    newvrb = os.path.splitext(oldvrb)[0] + "_COPY"
    shutil.copy(oldvrb, newvrb + ".vrb")
oldvrb=raw_input("Enter the Filename.vr that crashed: ")
copy_vrb(oldvrb)

# This renames the crashed file to Filename_BAD.vr

def file_rename(oldvr):
    newvrb = os.path.splitext(oldvrb)[0] + "_BAD"
    shutil.copy(oldvrb, newvrb + ".vr")
oldvr=raw_input("Rename file to 'Filename_BAD.vr': ")
file_rename(oldvr)

# This renames the Filename_COPY.vrb to Filename_NEW.vr

def rename_copy(oldvr):
    newvrb = os.path.splitext(oldvrb)[0] + "_NEW"
    shutil.copy(oldvrb, newvrb + ".vr")
oldvr=raw_input("Rename to 'Filename_NEW': ")
rename_copy(oldvr)

</code>```

The goal is to only need one raw_input at the beginning then have the program use that file to create the other files.

答:
The goal is to only need one raw_input at the beginning then have the program use that file to create the other files.

Well, literally put only one raw_input before calling the functions...

```<code>import os, sys, shutil, copy

# First define all your functions
def copy_vrb(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_COPY"
    shutil.copy(oldvr, newvrb + ".vrb")

def file_rename(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_BAD"
    shutil.copy(oldvr, newvrb + ".vr")

def rename_copy(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_NEW"
    shutil.copy(oldvr, newvrb + ".vr")

oldvr = raw_input('Type something: ')
copy_vrb(oldvr)
file_rename(oldvr)
rename_copy(oldvr)
</code>```

... and: Python2.7 is dead, consider moving to python 3, it's basically the same, just better.

Body:
I am having some issues nesting my functions together. The purpose of my program is to take a file, create a backup then change the name of the backup copy and original copy. Currently, I have to enter the filename with the additional filename extension to make this happen, I am fairly new at programming and have appreciated the help I have gotten so far on this script and will gladly take anymore feedback. Thanks in advance!

Here is my working code that does this. In my data folder I always start with a filename.vr (10000.vr) and its backup filename.vrb (10000.vrb).

import os, sys, shutil, copy

# This creates the copy of the .vrb file

def copy_vrb(oldvrb):
    newvrb = os.path.splitext(oldvrb)[0] + "_COPY"
    shutil.copy(oldvrb, newvrb + ".vrb")
oldvrb=raw_input("Enter the Filename.vr that crashed: ")
copy_vrb(oldvrb)

# This renames the crashed file to Filename_BAD.vr

def file_rename(oldvr):
    newvrb = os.path.splitext(oldvrb)[0] + "_BAD"
    shutil.copy(oldvrb, newvrb + ".vr")
oldvr=raw_input("Rename file to 'Filename_BAD.vr': ")
file_rename(oldvr)

# This renames the Filename_COPY.vrb to Filename_NEW.vr

def rename_copy(oldvr):
    newvrb = os.path.splitext(oldvrb)[0] + "_NEW"
    shutil.copy(oldvrb, newvrb + ".vr")
oldvr=raw_input("Rename to 'Filename_NEW': ")
rename_copy(oldvr)

The goal is to only need one raw_input at the beginning then have the program use that file to create the other files.

Body:
The goal is to only need one raw_input at the beginning then have the program use that file to create the other files.

Well, literally put only one raw_input before calling the functions...

import os, sys, shutil, copy

# First define all your functions
def copy_vrb(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_COPY"
    shutil.copy(oldvr, newvrb + ".vrb")

def file_rename(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_BAD"
    shutil.copy(oldvr, newvrb + ".vr")

def rename_copy(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_NEW"
    shutil.copy(oldvr, newvrb + ".vr")

oldvr = raw_input('Type something: ')
copy_vrb(oldvr)
file_rename(oldvr)
rename_copy(oldvr)

... and: Python2.7 is dead, consider moving to python 3, it's basically the same, just better.


问:
How can I search in month and year in SQL Server 2012?
I'm trying to write a query for searching for month and year only. What I made is searching for month. Can someone tell how I can modify this query to search for month and year like : 5/2019 or 5-2019 ?</p>

```<code>select firstname, lastname, date
from tblInfo
where data = 02/2019
</code>```

答:
Search for the interval between the first day of the month including and the first day of the following month excluding.

```<code>SELECT firstname,
       lastname,
       date
       FROM tblInfo
       WHERE data >= '2019-02-01'
             AND data < '2019-03-01';
</code>```

This has the advantage over solutions with datepart() or year() and month() that it can use an index on data if one is there and therefore perform (way) better in that case.

Using a left open interval instead of a closed one (using BETWEEN with the first and last day of the month) also has the advantage that it will also work if data has a time portion. If such a date/time is after the last day of the month at 00:00 but before the first day of the next month (at 00:00), for an arbitrary precision of the time fractions, it will be included.

Body:
I'm trying to write a query for searching for month and year only. What I made is searching for month. Can someone tell how I can modify this query to search for month and year like : 5/2019 or 5-2019 ?

select firstname, lastname, date
from tblInfo
where data = 02/2019

Body:
Search for the interval between the first day of the month including and the first day of the following month excluding.

SELECT firstname,
       lastname,
       date
       FROM tblInfo
       WHERE data >= '2019-02-01'
             AND data < '2019-03-01';

This has the advantage over solutions with datepart() or year() and month() that it can use an index on data if one is there and therefore perform (way) better in that case.

Using a left open interval instead of a closed one (using BETWEEN with the first and last day of the month) also has the advantage that it will also work if data has a time portion. If such a date/time is after the last day of the month at 00:00 but before the first day of the next month (at 00:00), for an arbitrary precision of the time fractions, it will be included.


问:
Reading / Writing files in Javascript - IE6
I need a database storage system for Javascript where the state can be maintained on the local disk.

Here comes the spanners in the works :-

It only needs to support Internet Explorer but the minimum version must be IE6

Files need to be written so they can be read in again later (upon closing and re-opening of browser)

There can be no web server (unless it's extremely easy to distribute and does not require a install) since the HTML pages will be distributed on USB.

Does anyone know of any solutions that might help here?

答:
I would suggest that you not try to read/write using JavaScript but instead head down the road of embedding a small web server on the USB drive.  I did this for an app once and it worked out well.  I used the Cassini web server.

I created two projects in visual studio.  First, I created an ASP.Net web site to read/write from an SQLite database.  This site displayed all my content and was built just like any other ASP.Net site.  Second, I created a Windows Forms application that hosted the Cassini web server and presented the user with a form that contained a single web browser control.  This made the user experience very simple ... they just clicked MYAPP.EXE from the root of the USB drive and the form opens, starts the web server, and navigates the browser control to the start page of the web site.


问:
Do package installed with pip change according to python configuration?
I have a conceptual doubt regarding how Python packages dependencies are installed/configured, this is related to compilation configurations.

Case 1

Installed packages pyscreenshot, image, pillow using pip from a python 2.7 configured with ucs2 in the user lib space (--user). Executed some api to get desktop screenshot, everything runs smoothly.

Case 2

Executed another python 2.7 configured with ucs4, it finds the packages due that those were installed in the user space. Executed same api to get desktop screenshot, it crashes. The ucs4 configuration was incompatible with how the packages works.

So why that happened? could different versions of the same packages be installed depending on how Python was configured?

Note:
ucs2/ucs4 explanation https://docs.python.org/2/c-api/unicode.html

答:
So why that happened?

It happened because when both C (binary) codes were loaded into memory, each one of them treated strings in different ways. In python documentation it is clearly stated that: "... UCS2 and UCS4 Python builds are not binary compatible. Please keep this in mind when writing extensions or interfaces."

Documentation also says that: "Python’s default builds use a 16-bit type for Py_UNICODE and store Unicode values internally as UCS2." So what you did was to: install a package compatible with the default interpreter and run it with a non compatible Python interpreter.

could different versions of the same packages be installed depending on how Python was configured?

I am not sure if pip is able to handle UCS2 and UCS4 package variants. What happens when you install the same packages using the pip from your UCS4 interpreter? If the UCS2 version of the package is installed when using the UCS4 version of pip, I would recommend to download the source distribution of the package and compile it yourself with UCS4.

I know that pip can differentiate between os (windows / linux) and ABI, but I don't think it can handle UCS differences.


问:
A protocol is not conforming to a class inherited from a generic parent class?
I am trying to conform a class to a protocol however, I am getting error. Here is the code:

```<code>class UserSearchViewController: GenericSearchViewController<User>
</code>```

I am trying to conform it to a buttontappeddelegate:

```<code>extension UserSearchViewController: ButtonDidGetTappedDelegate {
func button(wasTappedInCell cell: UserCollectionViewCell) {
    print("Cell Tapped")
   }
}
</code>```

I get the error when I assign self to the delegate:

```<code>adapter.delegate = self
</code>```

Cannot assign value of type 'UserSearchViewController.Type' to type 'ButtonDidGetTappedDelegate?'

What is the issue here? Any help would be appreciated.

```<code>class UserSearchViewController: GenericSearchViewController<User> {
    static func searchV (Config: ConfigurationProtocol,
                     dataSource: DataSource,
                     viewer: User) ->  UserSearchViewController
  let vc = UserSearchViewController(Config, dataSource,viewer)
   ......
   ...
  adapter.delegate = self
  return vc

}
</code>```

答:
Because you are doing this in a static function, you can't use self to refer to an instance of your VC. Instead, you have an instance of your VC already! It's vc.

Just set vc as the delegate instead of self:

```<code>adapter.delegate = vc
</code>```

Body:
I am trying to conform a class to a protocol however, I am getting error. Here is the code:

class UserSearchViewController: GenericSearchViewController<User>

I am trying to conform it to a buttontappeddelegate:

extension UserSearchViewController: ButtonDidGetTappedDelegate {
func button(wasTappedInCell cell: UserCollectionViewCell) {
    print("Cell Tapped")
   }
}

I get the error when I assign self to the delegate:

adapter.delegate = self

Cannot assign value of type 'UserSearchViewController.Type' to type 'ButtonDidGetTappedDelegate?'

What is the issue here? Any help would be appreciated.

class UserSearchViewController: GenericSearchViewController<User> {
    static func searchV (Config: ConfigurationProtocol,
                     dataSource: DataSource,
                     viewer: User) ->  UserSearchViewController
  let vc = UserSearchViewController(Config, dataSource,viewer)
   ......
   ...
  adapter.delegate = self
  return vc

}

Body:
Because you are doing this in a static function, you can't use self to refer to an instance of your VC. Instead, you have an instance of your VC already! It's vc.

Just set vc as the delegate instead of self:

adapter.delegate = vc


问:
iOS shadow is blocked by siblings child views
I have a problem where my view's shadow is blocked by the siblings child view.

This is how my view hierarchy looks:

```<code>ViewController View
    NavigationView with shadow
       TabBar
    ContainerView
       ViewController view
          ScrollBar
             ContentView
                Item view's that block the shadow
</code>```

My view looks like this:

The background color of the ContainerView is custom gray and the background color of the ContentView is clear color. If I don't set the background color of the ContentView to clear, the shadow doesn't appear at all.

So the shadow is still visible on the content view that is scrolling. But whenever I scroll so that a child item of the content view is behind the tab bar, the shadow completely disappears.

I have tried adding 4 NavigationViews into each other and then adding the TabBar into the last view so that my hierarchy looks like:

```<code>ViewController View
    NavigationView with shadow
       NavigationView with shadow 1
          NavigationView with shadow 2
              NavigationView with shadow 3
                  NavigationView with shadow 4
                     TabBar
    ContainerView
       ViewController view
          ScrollBar
             ContentView
                Item view's that block the shadow
</code>```

But that didn't help.

Is there a solution to this?

答:
So you are saying that your Tabbar's shadow is hide when you are scrolling. And Your card would hide that shadow. And when you scroll, this happens :

```<code>ViewController View
    NavigationView with shadow
       TabBar
    ContainerView
       ViewController view
          ScrollBar
             ContentView
                Item view's that block the shadow
</code>```

Change this hierarchy only in story board to :

```<code>ViewController View

  |ContainerView
  |   ViewController view
  |      ScrollBar
  |         ContentView
  |            Item view's that block the shadow
  |
  |NavigationView with shadow
      TabBar
</code>```

And assume that : Tabbar is inside NavigationView(UIView). NavigationView(UIView) has shadow. Bottom of navigation there is ContainerView(UIView).

So when you scroll your page :

And this would be your hierarchy :

Body:
I have a problem where my view's shadow is blocked by the siblings child view.

This is how my view hierarchy looks:

ViewController View
    NavigationView with shadow
       TabBar
    ContainerView
       ViewController view
          ScrollBar
             ContentView
                Item view's that block the shadow

My view looks like this:

The background color of the ContainerView is custom gray and the background color of the ContentView is clear color. If I don't set the background color of the ContentView to clear, the shadow doesn't appear at all.

So the shadow is still visible on the content view that is scrolling. But whenever I scroll so that a child item of the content view is behind the tab bar, the shadow completely disappears.

I have tried adding 4 NavigationViews into each other and then adding the TabBar into the last view so that my hierarchy looks like:

ViewController View
    NavigationView with shadow
       NavigationView with shadow 1
          NavigationView with shadow 2
              NavigationView with shadow 3
                  NavigationView with shadow 4
                     TabBar
    ContainerView
       ViewController view
          ScrollBar
             ContentView
                Item view's that block the shadow

But that didn't help.

Is there a solution to this?

Body:
So you are saying that your Tabbar's shadow is hide when you are scrolling. And Your card would hide that shadow. And when you scroll, this happens :

ViewController View
    NavigationView with shadow
       TabBar
    ContainerView
       ViewController view
          ScrollBar
             ContentView
                Item view's that block the shadow

Change this hierarchy only in story board to :

ViewController View

  |ContainerView
  |   ViewController view
  |      ScrollBar
  |         ContentView
  |            Item view's that block the shadow
  |
  |NavigationView with shadow
      TabBar

And assume that : Tabbar is inside NavigationView(UIView). NavigationView(UIView) has shadow. Bottom of navigation there is ContainerView(UIView).

So when you scroll your page :

And this would be your hierarchy :


问:
How can I generate every combination of pattern of 4 numbers and 2 A-Z characters
I wrote a small script to talk with a database that I got from a friend so I can link a dutch zip code with a street name. But I want to do it by myself

The ZIP codes are build up like NNNNCC where N is a number 0-9 (Ignoring the first 0's 0000-0999 isn't possible) and C = character A-Z.

How can I generate every possible combination in PHP?

答:
To build on @dWinder answer. You could build a list.

```<code>foreach(range(0,9999) as $num)
    foreach(range('A', 'Z') as $c1)
        foreach(range('A', 'Z') as $c2)
//      This comes out to 6,760,000 items
//          $zips[] = sprintf("%04s%s%s<br>", $num, $c1, $c2);
</code>```

If you just want to check format you can do pattern matching.

```<code>echo testZipNl('1t00AA') .' 1t00AA<br>';

echo testZipNl('11000AA') .' 11000AA<br>';

echo testZipNl('1000AA') .' 1000AA<br>';

function testZipNl($input){
    $input = trim($input);
    $regex = "/^[0-9]{4}[A-Z]{2}$/";
    if (preg_match($regex, $input) AND strlen($input) == 6) {
     return 'True';
    }
 return 'False';
}
</code>```

Body:
To build on @dWinder answer. You could build a list.

foreach(range(0,9999) as $num)
    foreach(range('A', 'Z') as $c1)
        foreach(range('A', 'Z') as $c2)
//      This comes out to 6,760,000 items
//          $zips[] = sprintf("%04s%s%s<br>", $num, $c1, $c2);

If you just want to check format you can do pattern matching.

echo testZipNl('1t00AA') .' 1t00AA<br>';

echo testZipNl('11000AA') .' 11000AA<br>';

echo testZipNl('1000AA') .' 1000AA<br>';

function testZipNl($input){
    $input = trim($input);
    $regex = "/^[0-9]{4}[A-Z]{2}$/";
    if (preg_match($regex, $input) AND strlen($input) == 6) {
     return 'True';
    }
 return 'False';
}


问:
unrecognized selector sent to instance
I am getting the following error message which I cannot understand why its happening because I am not using any UIImageView.  Sometimes I get the same error but its a CALayer?!?

Its worth also mentioning that I have 2 nibs and 2 controllers and a base controller where this code resides.

EDIT:

This is the structure of my project

MainViewController & its nib
- HomeViewController in nib

MainViewController-Landscape & its nib
- HomeViewController-Landscape in nib

HomeViewControllerBase - no nib
- Base class where all outlets and item configuration code exists.
- Outlets are used by both child classes below.
- Outlets are linked to controls in each of the main nibs.

HomeViewController
- Inherits from HomeViewControllerBase

HomeViewController-Landscape
- Inherits from HomeViewControllerBase

So whats happening is that the child class is trying to dealloc its base class (which has all the outlets in it).  I have designed it this way to avoid duplication of code in the different orientation viewcontrollers.

```<code>@implementation MainViewController
- (void)orientationChanged:(NSNotification *)notification
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;

    if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView)
    {
        [self presentModalViewController:self.landscapeViewController
                                animated:YES];

        isShowingLandscapeView = YES;
    }
    else if (UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView)
    {
        [self dismissModalViewControllerAnimated:YES];
        isShowingLandscapeView = NO;
    }
}

- (id)init
{
    self = [super initWithNibName:@"MainViewController" bundle:nil];

    if (self)
    {
        isShowingLandscapeView = NO;
        self.landscapeViewController = [[[MainViewController_Landscape alloc]
                                            initWithNibName:@"MainViewController-Landscape" bundle:nil] autorelease];

        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(orientationChanged:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }

    return self;
}
@end

@implementation HomeViewControllerBase

    - (void)bestSellItemTapped:(id)sender
    {
        NSLog(@"best sell item tapped");
    }

    - (void)configureBestSellItems
    {
        [self startRetrievingRegions];

        // load all the images from our bundle and add them to the scroll view
        //  NSUInteger i;
        for (int i = 0; i <= 150; i++)
        {

            UILabel *itemTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
            itemTitle.text = @"Majorca";

            UILabel *itemPrice = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 100, 50)];
            itemPrice.text = @"£249";

            NSString *imageName = @"tempImage.jpg";
            UIImage *image = [UIImage imageNamed:imageName];

            UIButton *mainButton = [[[UIButton alloc]init] autorelease];

            [mainButton addTarget:self action:@selector(bestSellItemTapped:) forControlEvents:UIControlEventTouchUpInside];
            [mainButton setBackgroundImage:image forState:UIControlStateNormal];

            // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
            CGRect rect = mainButton.frame;
            rect.size.height = kScrollObjHeight;
            rect.size.width = kScrollObjWidth;

            mainButton.frame = rect;
            mainButton.tag = i;

            [mainButton addSubview:itemTitle]; [itemTitle release];
            [mainButton addSubview:itemPrice]; [itemPrice release];

            [self.bestSellScrollView addSubview:mainButton];

        }

        [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
    }

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self configureBestSellItems];
    }

    - (void)layoutScrollImages
    {
        UIButton *view = nil;
        NSArray *subviews = [self.bestSellScrollView subviews];

        // reposition all image subviews in a horizontal serial fashion
        CGFloat curXLoc = 0;
        for (view in subviews)
        {
            if ([view isKindOfClass:[UIButton class]] && view.tag > 0)
            {
                CGRect frame = view.frame;
                frame.origin = CGPointMake(curXLoc, 0);
                view.frame = frame;

                curXLoc += (kScrollObjWidth + kScrollObjPadding);
            }
        }

        // set the content size so it can be scrollable
        [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                           [self.bestSellScrollView bounds].size.height)];
    }

@end

@interface HomeViewController : HomeViewControllerBase
@end

@interface HomeViewController_Landscape : HomeViewControllerBase
@end

@implementation HomeViewController

- (void)dealloc
{
    [super dealloc]; //When I remove this it works
}

@end

@implementation HomeViewController_Landscape

- (void)dealloc
{
   [super dealloc]; //When I remove this it works
}

@end
</code>```

```<code>-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0 2011-04-12 15:45:26.665 [21532:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0'
*** Call stack at first throw: (    0   CoreFoundation                      0x00dc85a9 __exceptionPreprocess + 185  1   libobjc.A.dylib                   0x00f1c313 objc_exception_throw + 44  2   CoreFoundation                    0x00dca0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187  3   CoreFoundation                      0x00d39966 ___forwarding___ + 966   4   CoreFoundation                      0x00d39522 _CF_forwarding_prep_0 + 50   5   UIKit                             0x0001a4fd -[UIApplication sendAction:to:from:forEvent:] + 119    6 UIKit                               0x000aa799 -[UIControl sendAction:to:forEvent:] + 67  7   UIKit                               0x000acc2b -[UIControl(Internal)
_sendActionsForEvents:withEvent:] + 527     8   UIKit                         0x000ab7d8 -[UIControl touchesEnded:withEvent:] + 458     9   UIKit                               0x002ad4de
_UIGestureRecognizerSortAndSendDelayedTouches
+ 3609  10  UIKit                               0x002adc53
_UIGestureRecognizerUpdateObserver + 927    11  CoreFoundation                0x00da989b
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
+ 27    12  CoreFoundation                      0x00d3e6e7 __CFRunLoopDoObservers + 295     13  CoreFoundation                0x00d071d7 __CFRunLoopRun + 1575  14  CoreFoundation                      0x00d06840 CFRunLoopRunSpecific + 208   15  CoreFoundation                    0x00d06761 CFRunLoopRunInMode + 97    16 GraphicsServices                    0x010001c4 GSEventRunModal + 217     17  GraphicsServices                    0x01000289 GSEventRun + 115     18  UIKit 0x00028c93 UIApplicationMain + 1160   19                      0x000027a9 main + 121   20
                      0x00002725 start + 53 ) terminate called after throwing an instance of 'NSException'
</code>```

答:
Is the whatever ViewController this code is from still alive when the button is tapped? An error like this (unrelated object - UIImageView in this case) usually means you have a pointer to some area of the memory that has been released and reused for something else (UIImageView in this case).

Add an NSLog() printout to the -dealloc method of the view controller and make sure it's not fired before you tap the button.

Actually, add one more NSLog to the beginning of configureBestSellItems - NSLog(@"I am %x", self); (yes, %x, not %@). This will print out the address of your view controller - compare it with the address of the crashing object (as in "unrecognized selector sent to instance 0x681c2b0" - see if it prints "I am 0x681c2b0" initially)

Title: unrecognized selector sent to instance

Body:
I am getting the following error message which I cannot understand why its happening because I am not using any UIImageView.  Sometimes I get the same error but its a CALayer?!?

Its worth also mentioning that I have 2 nibs and 2 controllers and a base controller where this code resides.

EDIT:

This is the structure of my project

MainViewController & its nib
- HomeViewController in nib

MainViewController-Landscape & its nib
- HomeViewController-Landscape in nib

HomeViewControllerBase - no nib
- Base class where all outlets and item configuration code exists.
- Outlets are used by both child classes below.
- Outlets are linked to controls in each of the main nibs.

HomeViewController
- Inherits from HomeViewControllerBase

HomeViewController-Landscape
- Inherits from HomeViewControllerBase

So whats happening is that the child class is trying to dealloc its base class (which has all the outlets in it).  I have designed it this way to avoid duplication of code in the different orientation viewcontrollers.

@implementation MainViewController
- (void)orientationChanged:(NSNotification *)notification
{
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;

    if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView)
    {
        [self presentModalViewController:self.landscapeViewController
                                animated:YES];

        isShowingLandscapeView = YES;
    }
    else if (UIDeviceOrientationIsPortrait(deviceOrientation) && isShowingLandscapeView)
    {
        [self dismissModalViewControllerAnimated:YES];
        isShowingLandscapeView = NO;
    }
}

- (id)init
{
    self = [super initWithNibName:@"MainViewController" bundle:nil];

    if (self)
    {
        isShowingLandscapeView = NO;
        self.landscapeViewController = [[[MainViewController_Landscape alloc]
                                            initWithNibName:@"MainViewController-Landscape" bundle:nil] autorelease];

        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(orientationChanged:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }

    return self;
}
@end

@implementation HomeViewControllerBase

    - (void)bestSellItemTapped:(id)sender
    {
        NSLog(@"best sell item tapped");
    }

    - (void)configureBestSellItems
    {
        [self startRetrievingRegions];

        // load all the images from our bundle and add them to the scroll view
        //  NSUInteger i;
        for (int i = 0; i <= 150; i++)
        {

            UILabel *itemTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
            itemTitle.text = @"Majorca";

            UILabel *itemPrice = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 100, 50)];
            itemPrice.text = @"£249";

            NSString *imageName = @"tempImage.jpg";
            UIImage *image = [UIImage imageNamed:imageName];

            UIButton *mainButton = [[[UIButton alloc]init] autorelease];

            [mainButton addTarget:self action:@selector(bestSellItemTapped:) forControlEvents:UIControlEventTouchUpInside];
            [mainButton setBackgroundImage:image forState:UIControlStateNormal];

            // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
            CGRect rect = mainButton.frame;
            rect.size.height = kScrollObjHeight;
            rect.size.width = kScrollObjWidth;

            mainButton.frame = rect;
            mainButton.tag = i;

            [mainButton addSubview:itemTitle]; [itemTitle release];
            [mainButton addSubview:itemPrice]; [itemPrice release];

            [self.bestSellScrollView addSubview:mainButton];

        }

        [self layoutScrollImages];  // now place the photos in serial layout within the scrollview
    }

    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self configureBestSellItems];
    }

    - (void)layoutScrollImages
    {
        UIButton *view = nil;
        NSArray *subviews = [self.bestSellScrollView subviews];

        // reposition all image subviews in a horizontal serial fashion
        CGFloat curXLoc = 0;
        for (view in subviews)
        {
            if ([view isKindOfClass:[UIButton class]] && view.tag > 0)
            {
                CGRect frame = view.frame;
                frame.origin = CGPointMake(curXLoc, 0);
                view.frame = frame;

                curXLoc += (kScrollObjWidth + kScrollObjPadding);
            }
        }

        // set the content size so it can be scrollable
        [self.bestSellScrollView setContentSize:CGSizeMake((150 * kScrollObjWidth),
                                                           [self.bestSellScrollView bounds].size.height)];
    }

@end

@interface HomeViewController : HomeViewControllerBase
@end

@interface HomeViewController_Landscape : HomeViewControllerBase
@end

@implementation HomeViewController

- (void)dealloc
{
    [super dealloc]; //When I remove this it works
}

@end

@implementation HomeViewController_Landscape

- (void)dealloc
{
   [super dealloc]; //When I remove this it works
}

@end

-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0 2011-04-12 15:45:26.665 [21532:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView bestSellItemTapped:]: unrecognized selector sent to instance 0x681c2b0'
*** Call stack at first throw: (    0   CoreFoundation                      0x00dc85a9 __exceptionPreprocess + 185  1   libobjc.A.dylib                   0x00f1c313 objc_exception_throw + 44  2   CoreFoundation                    0x00dca0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187  3   CoreFoundation                      0x00d39966 ___forwarding___ + 966   4   CoreFoundation                      0x00d39522 _CF_forwarding_prep_0 + 50   5   UIKit                             0x0001a4fd -[UIApplication sendAction:to:from:forEvent:] + 119    6 UIKit                               0x000aa799 -[UIControl sendAction:to:forEvent:] + 67  7   UIKit                               0x000acc2b -[UIControl(Internal)
_sendActionsForEvents:withEvent:] + 527     8   UIKit                         0x000ab7d8 -[UIControl touchesEnded:withEvent:] + 458     9   UIKit                               0x002ad4de
_UIGestureRecognizerSortAndSendDelayedTouches
+ 3609  10  UIKit                               0x002adc53
_UIGestureRecognizerUpdateObserver + 927    11  CoreFoundation                0x00da989b
__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
+ 27    12  CoreFoundation                      0x00d3e6e7 __CFRunLoopDoObservers + 295     13  CoreFoundation                0x00d071d7 __CFRunLoopRun + 1575  14  CoreFoundation                      0x00d06840 CFRunLoopRunSpecific + 208   15  CoreFoundation                    0x00d06761 CFRunLoopRunInMode + 97    16 GraphicsServices                    0x010001c4 GSEventRunModal + 217     17  GraphicsServices                    0x01000289 GSEventRun + 115     18  UIKit 0x00028c93 UIApplicationMain + 1160   19                      0x000027a9 main + 121   20
                      0x00002725 start + 53 ) terminate called after throwing an instance of 'NSException'


问:
Is it possible to provide a passwordless login via email (like Slack's magic log-in links) using AAD B2C?
I would like to have the administrator of my app create users in Azure AD B2C and then have Azure AD B2C send a passwordless link to the user via email or pass me the link so that I can send it via email.  Is this possible via the existing service or API?

This article helps explain the concept using Auth0:
https://auth0.com/docs/connections/passwordless/regular-web-app-email-link

答: I went to a meetup yesterday about Azure AD B2C Custom Policies. I asked the speaker if he knew if they could handle passwordless login, like entering your email address on an MFD then getting a popup on your mobile app to approve/deny but he wasn't sure. Later on he sent me Azure Active Directory B2C: Custom CIAM User Journeys - Multi factor authentication enhancements. From this it looks like Azure AD B2C: TOTP multi-factor authentication may have some useful examples.</p>


问:
Match two consecutive words in a sentence
I have a bunch of sentences and want to figure out if the sentence contains a specific set of consecutive words. As an example, I have a list like below

```<code>  list = ["Data Scientist",  "Data Analyst", "Data Engineer"]
</code>```

and have sentences like below

```<code>  Sentence1 = "I am first going to be a Data Analyst and then a Data Scientist"
  Sentence2 = "I only like to be a Data Engineer"
</code>```

with the desired output picking out "Data Analyst" and "Data Scientist" for Sentence1 and "Data Engineer" for Sentence2.

答:
Use regex for that:</p>

```<code>import re

lst = ["Data Scientist",  "Data Analyst", "Data Engineer"]

s = re.compile('|'.join(lst))

matches = re.findall(s, senetence)
</code>```

Body:
I have a bunch of sentences and want to figure out if the sentence contains a specific set of consecutive words. As an example, I have a list like below

  list = ["Data Scientist",  "Data Analyst", "Data Engineer"]

and have sentences like below

  Sentence1 = "I am first going to be a Data Analyst and then a Data Scientist"
  Sentence2 = "I only like to be a Data Engineer"

with the desired output picking out "Data Analyst" and "Data Scientist" for Sentence1 and "Data Engineer" for Sentence2.

Body:
Use regex for that:

import re

lst = ["Data Scientist",  "Data Analyst", "Data Engineer"]

s = re.compile('|'.join(lst))

matches = re.findall(s, senetence)


问:
Allowing "overriding" zero-initialized object with internal linkage
I'm designing a micro-framework for unit testing and want to be able to provide an ability for client to define a "test suite name". So I have the following header file called test_suite.h:

```<code>static const char *const test_suite_name;

static inline void run_all_tests(void){
    printf("Running ");
    if(!test_suite_name){
        printf("unnamed suite");
    } else {
        printf("%s suite", test_suite_name);
    }
    //run tests
}
</code>```

The intention of this is to allow clients to "override" the test_suite_name as follows:

```<code>#include "test_suite.h"

extern const char *const test_suite_name = "suite1";
</code>```

I think the behavior of such usage is well-defined since static const char *const test_suite_name; constitutes a tentative-definition and then extern const char *const test_suite_name = "suite1"; constitutes an external definition. There is no linkage disagreement since 6.2.2(p4):

For an identifier declared with the storage-class specifier extern in a
  scope in which a prior declaration of that identifier is visible,31) if
  the prior declaration specifies internal or external  linkage,  the
  linkage  of  the  identifier  at  the  later  declaration  is  the
  same  as  the linkage specified at the prior declaration.

I ran some experiments:

https://coliru.stacked-crooked.com:

Prints the following error message:

```<code>error: redefinition of 'const char* const suite_name'
 extern const char *const suite_name = "some suite";
</code>```

DEMO

https://ideone.com/:

Works completely fine with no warnings produced

DEMO

gcc7.4.0 on my machine.

Produces warning:

```<code>warning: ‘test_suite_name’ initialized and declared ‘extern’
</code>```

Question: Is the behavior of the code shown above well-defined?

I'm pretty sure that the behavior would be undefined if write the following:

```<code>#include "test_suite.h"

const char *const test_suite_name = "suite1"; //without extern
</code>```

because of 6.2.2(p5)(emphasize  mine):

If the declaration of an identifier for a function has no
  storage-class specifier, its linkage is  determined  exactly  as  if
  it  were  declared  with  the  storage-class  specifier extern. If the
  declaration of an identifier for an object has file scope and no
  storage-class specifier, its linkage is external.

So we would have linkage disagreement between static const char *const test_suite_name; with internal linkage and const char *const test_suite_name = "suite1"; with external linkage.

答:
Use of static

You may actually be able to use static instead of external.
Making a quick test with gcc under Ubuntu:

```<code>#include "test_suite.h"

static const char *const test_suite_name = "huhu";

int main() {
      run_all_tests();
      return 0;
}
</code>```

If I compile with:

```<code>gcc -Wall -Wpedantic -Wextra mytest.c -o mytest
</code>```

it gives as output:

```<code>Running huhu suite
</code>```

Omitting static

If you accidentally forget to specify static it should give a compile time error then. So if I change this line to:

```<code>const char *const test_suite_name = "huhu";
</code>```

and try to compile it like this:

```<code>gcc -Wall -Wpedantic -Wextra mytest2.c -o mytest2
</code>```

this error message will be displayed:

```<code>mytest2.c:3:19: error: non-static declaration of ‘test_suite_name’ follows static declaration
 const char *const test_suite_name = "huhu";
                   ^~~~~~~~~~~~~~~
In file included from mytest2.c:1:
test_suite.h:3:26: note: previous declaration of ‘test_suite_name’ was here
 static const char *const test_suite_name;
</code>```

Since it is an error it is also output if you compile with:

```<code>gcc mytest2.c -o mytest2
</code>```

Screenshot of Error Message

Body:
I'm designing a micro-framework for unit testing and want to be able to provide an ability for client to define a "test suite name". So I have the following header file called test_suite.h:

static const char *const test_suite_name;

static inline void run_all_tests(void){
    printf("Running ");
    if(!test_suite_name){
        printf("unnamed suite");
    } else {
        printf("%s suite", test_suite_name);
    }
    //run tests
}

The intention of this is to allow clients to "override" the test_suite_name as follows:

#include "test_suite.h"

extern const char *const test_suite_name = "suite1";

I think the behavior of such usage is well-defined since static const char *const test_suite_name; constitutes a tentative-definition and then extern const char *const test_suite_name = "suite1"; constitutes an external definition. There is no linkage disagreement since 6.2.2(p4):

For an identifier declared with the storage-class specifier extern in a
  scope in which a prior declaration of that identifier is visible,31) if
  the prior declaration specifies internal or external  linkage,  the
  linkage  of  the  identifier  at  the  later  declaration  is  the
  same  as  the linkage specified at the prior declaration.

I ran some experiments:

https://coliru.stacked-crooked.com:

Prints the following error message:

error: redefinition of 'const char* const suite_name'
 extern const char *const suite_name = "some suite";

DEMO

https://ideone.com/:

Works completely fine with no warnings produced

DEMO

gcc7.4.0 on my machine.

Produces warning:

warning: ‘test_suite_name’ initialized and declared ‘extern’

Question: Is the behavior of the code shown above well-defined?

I'm pretty sure that the behavior would be undefined if write the following:

#include "test_suite.h"

const char *const test_suite_name = "suite1"; //without extern

because of 6.2.2(p5)(emphasize  mine):

If the declaration of an identifier for a function has no
  storage-class specifier, its linkage is  determined  exactly  as  if
  it  were  declared  with  the  storage-class  specifier extern. If the
  declaration of an identifier for an object has file scope and no
  storage-class specifier, its linkage is external.

So we would have linkage disagreement between static const char *const test_suite_name; with internal linkage and const char *const test_suite_name = "suite1"; with external linkage.

Body:
Use of static

You may actually be able to use static instead of external.
Making a quick test with gcc under Ubuntu:

#include "test_suite.h"

static const char *const test_suite_name = "huhu";

int main() {
      run_all_tests();
      return 0;
}

If I compile with:

gcc -Wall -Wpedantic -Wextra mytest.c -o mytest

it gives as output:

Running huhu suite

Omitting static

If you accidentally forget to specify static it should give a compile time error then. So if I change this line to:

const char *const test_suite_name = "huhu";

and try to compile it like this:

gcc -Wall -Wpedantic -Wextra mytest2.c -o mytest2

this error message will be displayed:

mytest2.c:3:19: error: non-static declaration of ‘test_suite_name’ follows static declaration
 const char *const test_suite_name = "huhu";
                   ^~~~~~~~~~~~~~~
In file included from mytest2.c:1:
test_suite.h:3:26: note: previous declaration of ‘test_suite_name’ was here
 static const char *const test_suite_name;

Since it is an error it is also output if you compile with:

gcc mytest2.c -o mytest2

Screenshot of Error Message


答:
Do your raw_input in your main thread, then pass the result to each function.

```<code>import os, sys, shutil, copy

def copy_vrb(oldvrb):
    newvrb = os.path.splitext(oldvrb)[0] + "_COPY")
    shutil.copy(oldvrb, newvrb + ".vrb")

def file_rename(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_BAD"
    shutil.copy(oldvr, newvrb + ".vr")

def rename_copy(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_NEW"
    shutil.copy(oldvr, newvrb + ".vr")

if __name__ == '__main__':
    oldvr = raw_input("File that crashed: ")
    copy_vrb(oldvr)
    file_rename(oldvr)
    rename_copy(oldvr)
</code>```

FIXED local variable names per comments.

Title: Is there an easy way to nest functions together so they run as one from a single raw_input?

Body:
Do your raw_input in your main thread, then pass the result to each function.

import os, sys, shutil, copy

def copy_vrb(oldvrb):
    newvrb = os.path.splitext(oldvrb)[0] + "_COPY")
    shutil.copy(oldvrb, newvrb + ".vrb")

def file_rename(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_BAD"
    shutil.copy(oldvr, newvrb + ".vr")

def rename_copy(oldvr):
    newvrb = os.path.splitext(oldvr)[0] + "_NEW"
    shutil.copy(oldvr, newvrb + ".vr")

if __name__ == '__main__':
    oldvr = raw_input("File that crashed: ")
    copy_vrb(oldvr)
    file_rename(oldvr)
    rename_copy(oldvr)

FIXED local variable names per comments.


问:
How to scrape the html code from the response received?
I am trying to crawl-scrape a website with scrapy and splash.
I want to scrape a specific html code from a response which seems in the image.
Here is the response with its headers:

Here is the response (the html I want to scrape):

I can find that HTML with the Inspect Tool. What my code returns is the html which I can see with "View page source" Tool. So, this means taht Javascript modifies the code before embedding it. But, the splash role is to run javascript and return HTML, isn't it??
The response.body returns the source code of the page without the html code i need from the response i mentioned above.

import scrapy
from scrapy_splash import SplashRequest
from bs4 import BeautifulSoup

class NetherSplashSpider(scrapy.Spider):
    name = 'nether_splash'
    download_delay = 10

    custom_settings = {
        'SPLASH_URL': 'http://localhost:8050',
        'DOWNLOADER_MIDDLEWARES': {
            'scrapy_splash.SplashCookiesMiddleware': 723,
            'scrapy_splash.SplashMiddleware': 725,
            'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
        },
        'SPIDER_MIDDLEWARES': {
            'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
        },
        'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter',
    }

    def start_requests(self):
        yield SplashRequest(
            url='https://www.gaslicht.com/stroom-vergelijken?partial=true&aanbieders=eneco&skip=0&take=10&_=1559207102962',
            callback=self.parse,
        )

    def parse(self, response):

        filename = 'splash.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
```

答:
In order to load the full page, you will need to add the "wait" parameter.
Try adding "args={'wait': 1.0}" to your SplashRequest.</p>

```<code>yield SplashRequest(
            url='https://www.gaslicht.com/stroom-vergelijken?partial=true&aanbieders=eneco&skip=0&take=10&_=1559207102962',
            callback=self.parse, args={'wait': 1.0}
        )
</code>```

Body:
In order to load the full page, you will need to add the "wait" parameter.
Try adding "args={'wait': 1.0}" to your SplashRequest.

yield SplashRequest(
            url='https://www.gaslicht.com/stroom-vergelijken?partial=true&aanbieders=eneco&skip=0&take=10&_=1559207102962',
            callback=self.parse, args={'wait': 1.0}
        )


问:
Kernel died restarting whenever training a model
Here's the code:

```<code># import libraries
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

# import dataset
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator()

test_datagen = ImageDataGenerator()

training_set = train_datagen.flow_from_directory(
                                            'data/spectrogramme/ensemble_de_formation',
                                            target_size = (64, 64),
                                            batch_size = 128,
                                            class_mode = 'binary')

test_set = test_datagen.flow_from_directory('data/spectrogramme/ensemble_de_test',
                                            target_size = (64, 64),
                                            batch_size = 128,
                                            class_mode = 'binary')

# initializing
reseau = Sequential()

# 1. convolution
reseau.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))
reseau.add(Conv2D(32, (3, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))
reseau.add(Conv2D(64, (3, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))
reseau.add(Conv2D(64, (3, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))

# 2. flatenning
reseau.add(Flatten())

# 3. fully connected
from keras.layers import Dropout
reseau.add(Dense(units = 64, activation = 'relu'))
reseau.add(Dropout(0.1))
reseau.add(Dense(units = 128, activation = 'relu'))
reseau.add(Dropout(0.05))
reseau.add(Dense(units = 256, activation = 'relu'))
reseau.add(Dropout(0.03))
reseau.add(Dense(units = 1, activation = 'sigmoid'))

# 4. compile
reseau.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# 5. fit
reseau.fit_generator(training_set, steps_per_epoch = 8000, epochs = 1,
                     validation_data = test_set, validation_steps = 2000)
</code>```

This should prove that I have tensorflow GPU with CUDA and CUDNN installed pic

I don't know what to do, I have reinstalled CUDA and CUDNN multiple times

HOWEVER, if I uninstall tensorflow-gpu, the program runs flawlessly... with the exception of needing 5000 seconds per epoch... I'd like to avoid that

FYI, this is all happening on Windows

Any help is appreciated.

答:
in my case I needed to install

conda install keras

Body:
Here's the code:

# import libraries
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

# import dataset
from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator()

test_datagen = ImageDataGenerator()

training_set = train_datagen.flow_from_directory(
                                            'data/spectrogramme/ensemble_de_formation',
                                            target_size = (64, 64),
                                            batch_size = 128,
                                            class_mode = 'binary')

test_set = test_datagen.flow_from_directory('data/spectrogramme/ensemble_de_test',
                                            target_size = (64, 64),
                                            batch_size = 128,
                                            class_mode = 'binary')

# initializing
reseau = Sequential()

# 1. convolution
reseau.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))
reseau.add(Conv2D(32, (3, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))
reseau.add(Conv2D(64, (3, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))
reseau.add(Conv2D(64, (3, 3), activation = 'relu'))
reseau.add(MaxPooling2D(pool_size = (2, 2)))

# 2. flatenning
reseau.add(Flatten())

# 3. fully connected
from keras.layers import Dropout
reseau.add(Dense(units = 64, activation = 'relu'))
reseau.add(Dropout(0.1))
reseau.add(Dense(units = 128, activation = 'relu'))
reseau.add(Dropout(0.05))
reseau.add(Dense(units = 256, activation = 'relu'))
reseau.add(Dropout(0.03))
reseau.add(Dense(units = 1, activation = 'sigmoid'))

# 4. compile
reseau.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# 5. fit
reseau.fit_generator(training_set, steps_per_epoch = 8000, epochs = 1,
                     validation_data = test_set, validation_steps = 2000)

This should prove that I have tensorflow GPU with CUDA and CUDNN installed pic

I don't know what to do, I have reinstalled CUDA and CUDNN multiple times

HOWEVER, if I uninstall tensorflow-gpu, the program runs flawlessly... with the exception of needing 5000 seconds per epoch... I'd like to avoid that

FYI, this is all happening on Windows

Any help is appreciated.


问:
Deploying React + Express App to Kubernetes. How to structure it with docker?
So I've been struggling with how to deploy a dockerized application. The app consists of a react frontend, and an express API.
My docker-compose.yml for the development environment looks like the following:

```<code>version: '3'
services:
  # Express Container
  backend:
    build: ./backend
    expose:
      - ${BACKEND_PORT}
    env_file:
      - ./.env
    environment:
      - PORT=${BACKEND_PORT}
    ports:
      - ${BACKEND_PORT}:${BACKEND_PORT}
    volumes:
      - ./backend:/backend
    command: npm run devstart
    links:
      - mongo
  # React Container
  frontend:
    build: './frontend'
    expose:
      - ${REACT_APP_PORT}
    env_file:
      - ./.env
    environment:
      - REACT_APP_BACKEND_PORT=${BACKEND_PORT}
    ports:
      - ${REACT_APP_PORT}:${REACT_APP_PORT}
    volumes:
      - ./frontend/src:/frontend/src
      - ./frontend/public:/frontend/public
    links:
      - backend
    command: npm start
  mongo:
    image: mongo
    ports:
      - "27017:27017"
</code>```

But I've been struggling on how to structure it for production.

I've seen that there is basically 3 options:

Deploy the frontend and backend separately to different servers. In this case, the react frontend would be on some web hosting service, and the express backend would be hosted on kubernetes

Have the express application serve out the react application

Have the applications separate but use NGINX to proxy API requests to the express app

I was thinking I would go with option 3, because it would keep development and production environments quite similar. (Please tell me if this is bad structure, this application is expected to receive a lot of traffic.)

Should I maybe forget docker-compose and create a multistage dockerfile that uses multistage builds to copy over frontend and backend code? That way I can deploy a single Docker container?

My folder structure looks like the following:

```<code>app/
  .env
  docker-compose.yml
  docker-compose.prod.yml
  .gitignore
  frontend/
    Dockerfile
    ... react stuff
  backend
    Dockerfile
    .. express stuff
</code>```

Am I going about this all wrong? How have you deployed your applications with docker-compose to production (preferably on kubernetes).

I can find tons of stuff about how to get this stuff running in development, but I'm lost when it comes to direction for deploying this type of stack.

答:
I keep the front end and the back end as completely separate applications. They are each in their own GitHub repository, with their own test suites, Dockerfiles, Jenkins builds, everything. This allows us to version them independently which allows for more frequent iterations; smaller, lower risk deployments; and faster, more efficient development.

All calls to the back end are on the /API/ path which is handled by an nginx ingress controller (very simple) and routed appropriately to the back end service.

Body:
So I've been struggling with how to deploy a dockerized application. The app consists of a react frontend, and an express API.
My docker-compose.yml for the development environment looks like the following:

version: '3'
services:
  # Express Container
  backend:
    build: ./backend
    expose:
      - ${BACKEND_PORT}
    env_file:
      - ./.env
    environment:
      - PORT=${BACKEND_PORT}
    ports:
      - ${BACKEND_PORT}:${BACKEND_PORT}
    volumes:
      - ./backend:/backend
    command: npm run devstart
    links:
      - mongo
  # React Container
  frontend:
    build: './frontend'
    expose:
      - ${REACT_APP_PORT}
    env_file:
      - ./.env
    environment:
      - REACT_APP_BACKEND_PORT=${BACKEND_PORT}
    ports:
      - ${REACT_APP_PORT}:${REACT_APP_PORT}
    volumes:
      - ./frontend/src:/frontend/src
      - ./frontend/public:/frontend/public
    links:
      - backend
    command: npm start
  mongo:
    image: mongo
    ports:
      - "27017:27017"

But I've been struggling on how to structure it for production.

I've seen that there is basically 3 options:

Deploy the frontend and backend separately to different servers. In this case, the react frontend would be on some web hosting service, and the express backend would be hosted on kubernetes

Have the express application serve out the react application

Have the applications separate but use NGINX to proxy API requests to the express app

I was thinking I would go with option 3, because it would keep development and production environments quite similar. (Please tell me if this is bad structure, this application is expected to receive a lot of traffic.)

Should I maybe forget docker-compose and create a multistage dockerfile that uses multistage builds to copy over frontend and backend code? That way I can deploy a single Docker container?

My folder structure looks like the following:

app/
  .env
  docker-compose.yml
  docker-compose.prod.yml
  .gitignore
  frontend/
    Dockerfile
    ... react stuff
  backend
    Dockerfile
    .. express stuff

Am I going about this all wrong? How have you deployed your applications with docker-compose to production (preferably on kubernetes).

I can find tons of stuff about how to get this stuff running in development, but I'm lost when it comes to direction for deploying this type of stack.


问:
Tomcat Server running slow - how to edit server status configurations
Hi I am really new to Tomcat and backend engineering.  My Tomcat 7 server status is showing a lot of heap memory being used and my applications are running incredibly slow. Per the photo below, what can I do to update the JVM memory amount? I've read online about editing the catalina.bat or catalina.sh files with updated memory parameters, but my bin folder doesn't have either of these files. So I am not sure what to do, should I create them using command line? I also went in and added parameters to  Java. Set the run time parameters to -Xms1024m, but this doesn't effect Tomcat.  This server currently runs three applications and will soon need to serve & host a fourth.

Any help on this is greatly appreciated! Thank you!!

答:
I was able to fix this issue. I did not have correct administrative rights to view the proper control panel. Want to leave the answer for anyone else who has this issue.

If adding a .bat file and setting Catalina_Opts and java_opts doesn't work for you, you must go to this Tomcat properties panel and adjust the memory pools there.


问:
what is wrong with this code to obtain some statistics after lapply() in R
My data is something like this:

```<code>ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
ind4 <- rnorm(99)
ind5 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
group <- rep(c("A", "B", "C"), each=33)
df <- data.frame(dep,group, ind1, ind2, ind3, ind4, ind5)
head(df)

         dep group        ind1       ind2       ind3       ind4          ind5
1 -3.4471651     A -1.61903503  0.8047651 -0.1498872 -0.1421423  0.0003106164
2  1.6097232     A -0.07202246 -1.7419735 -0.4600787 -0.8966089  0.5476866447
3  0.2419204     A  0.37266251  1.1456788  0.2693086 -0.7610068 -0.6588102710
4  0.4157412     A  1.17342107  0.4829935  1.5044331  0.4902491 -0.1845711119
5 -1.1026655     A  0.31428775  0.9488747  0.1806105  0.4187126 -0.4420550339
6  1.9605406     A  1.36719867  1.1116940  0.7026870  0.6450296 -1.0824261091
</code>```

The next lines of code intend to run linear model for all possible combination of independent variables in the dataframe.

After selecting the significant models by p < 0.05 and ranking them by AIC value, I want to get following outputs: equation, estimate, R2, adj.R2, P value, AIC.

I tried it this way but the outputs are different from what I wanted. Does anyone have any idea to get them right?

```<code> indvar_list <- lapply(1:5, function(x)
   combn(paste0("ind", 1:5), x, , simplify = FALSE))

 formulas_list <- rapply(indvar_list, function(x)
   as.formula(paste("dep ~", paste(x, collapse="+"))))

 mult.lm <- lapply(formulas_list, function(x) glance(lm(as.formula(x),
 data = df)))

 outputs <- bind_rows(mult.lm, .id = 'index') %>%
   filter(p.value < 0.05) %>%
   arrange(AIC) %>%
   filter(index %in% head(unique(index)))
</code>```

thanks in advance!

答:
Use base::format to get the equation and broom::tidy to get the estimates "coefficients"

```<code>mult.lm <- lapply(formulas_list, function(x) {
mod <- lm(as.formula(x), data = df)
data.frame(model=format(x), tidy(mod), glance(mod),
           stringsAsFactors = FALSE, row.names = NULL)
})

#To return more clean dataframe
mult.lm <- lapply(formulas_list, function(x) {
mod <- lm(as.formula(x), data = df)
tmod <- tidy(mod)
gmod <- glance(mod)
gmod[2:nrow(tmod),] <- ''

data.frame(model=c(format(x), rep('', nrow(tmod)-1)), tmod, gmod,
           stringsAsFactors = FALSE, row.names = NULL)
})
</code>```

Body:
My data is something like this:

ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
ind4 <- rnorm(99)
ind5 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
group <- rep(c("A", "B", "C"), each=33)
df <- data.frame(dep,group, ind1, ind2, ind3, ind4, ind5)
head(df)

         dep group        ind1       ind2       ind3       ind4          ind5
1 -3.4471651     A -1.61903503  0.8047651 -0.1498872 -0.1421423  0.0003106164
2  1.6097232     A -0.07202246 -1.7419735 -0.4600787 -0.8966089  0.5476866447
3  0.2419204     A  0.37266251  1.1456788  0.2693086 -0.7610068 -0.6588102710
4  0.4157412     A  1.17342107  0.4829935  1.5044331  0.4902491 -0.1845711119
5 -1.1026655     A  0.31428775  0.9488747  0.1806105  0.4187126 -0.4420550339
6  1.9605406     A  1.36719867  1.1116940  0.7026870  0.6450296 -1.0824261091

The next lines of code intend to run linear model for all possible combination of independent variables in the dataframe.

After selecting the significant models by p < 0.05 and ranking them by AIC value, I want to get following outputs: equation, estimate, R2, adj.R2, P value, AIC.

I tried it this way but the outputs are different from what I wanted. Does anyone have any idea to get them right?

 indvar_list <- lapply(1:5, function(x)
   combn(paste0("ind", 1:5), x, , simplify = FALSE))

 formulas_list <- rapply(indvar_list, function(x)
   as.formula(paste("dep ~", paste(x, collapse="+"))))

 mult.lm <- lapply(formulas_list, function(x) glance(lm(as.formula(x),
 data = df)))

 outputs <- bind_rows(mult.lm, .id = 'index') %>%
   filter(p.value < 0.05) %>%
   arrange(AIC) %>%
   filter(index %in% head(unique(index)))

thanks in advance!

Body:
Use base::format to get the equation and broom::tidy to get the estimates "coefficients"

mult.lm <- lapply(formulas_list, function(x) {
mod <- lm(as.formula(x), data = df)
data.frame(model=format(x), tidy(mod), glance(mod),
           stringsAsFactors = FALSE, row.names = NULL)
})

#To return more clean dataframe
mult.lm <- lapply(formulas_list, function(x) {
mod <- lm(as.formula(x), data = df)
tmod <- tidy(mod)
gmod <- glance(mod)
gmod[2:nrow(tmod),] <- ''

data.frame(model=c(format(x), rep('', nrow(tmod)-1)), tmod, gmod,
           stringsAsFactors = FALSE, row.names = NULL)
})


问:
Automate push to github in laravel project
I'm trying to add, commit & push to github using php code from Laravel controller using:

```<code>shell_exec('git add . && git commit -m "Nero" && git push origin master');
system('git add . && git commit -m "Nero" && git push origin master');
</code>```

The code added files changed successfully.

The code commit successfully.

It takes too long time and still didn't push the code.

I tried a lot of commands and it successfully run, the problem is in

```<code>git push

git push origin master
</code>```

答:
Are you sure your git credentials are correctly configured? My guess is that the push command is waiting for you to enter your Github username/password.

You could verify by getting the shell_exec output like this:

```<code>$output = shell_exec('git add . && git commit -m "Nero" && git push origin master');
</code>```

Body:
I'm trying to add, commit & push to github using php code from Laravel controller using:

shell_exec('git add . && git commit -m "Nero" && git push origin master');
system('git add . && git commit -m "Nero" && git push origin master');

The code added files changed successfully.

The code commit successfully.

It takes too long time and still didn't push the code.

I tried a lot of commands and it successfully run, the problem is in

git push

git push origin master

Body:
Are you sure your git credentials are correctly configured? My guess is that the push command is waiting for you to enter your Github username/password.

You could verify by getting the shell_exec output like this:

$output = shell_exec('git add . && git commit -m "Nero" && git push origin master');


问:
Ruby on Rails Loan Amortization Schedule
What would be the best way to incorporate a loan amortization schedule in my rails app? Is it possible? Is ruby on rails even a good way to implement something like that? I have built them in excel a few times before, but just can't picture how to do it in rails.</p>

答:
This all depends on the actions your users will need to perform on/with the schedule.

If your goal is simply displaying the schedule, there's no need to persist the entire array of dates/payments/etc.  Simply store a start/end date, payment interval, loan amount, interest rate and the payment amount.  It isn't heavy work to construct the actual schedule given this information.

If your users should be able to annotate specific items within the schedule, then consider which properties of each item would make good unique identifiers (hint: loan + item date).  From there, your models should flesh out easily:

```<code>class ScheduleItem
{
  date dueDate;
  float paymentAmount;
  string annotations;
  bool isPaid;
  ...
}

class Schedule
{
  int loanId;
  date startDate;
  date endDate;
  ...
}
</code>```

If you do decide you need models (to persist or just to generate views) representing the schedule start with the simplest implementation possible and expand from there.  You're most likely having trouble getting started because you're trying to incorporate every variable from the start.  Keep it simple.  Get things rolling.

Body:
This all depends on the actions your users will need to perform on/with the schedule.

If your goal is simply displaying the schedule, there's no need to persist the entire array of dates/payments/etc.  Simply store a start/end date, payment interval, loan amount, interest rate and the payment amount.  It isn't heavy work to construct the actual schedule given this information.

If your users should be able to annotate specific items within the schedule, then consider which properties of each item would make good unique identifiers (hint: loan + item date).  From there, your models should flesh out easily:

class ScheduleItem
{
  date dueDate;
  float paymentAmount;
  string annotations;
  bool isPaid;
  ...
}

class Schedule
{
  int loanId;
  date startDate;
  date endDate;
  ...
}

If you do decide you need models (to persist or just to generate views) representing the schedule start with the simplest implementation possible and expand from there.  You're most likely having trouble getting started because you're trying to incorporate every variable from the start.  Keep it simple.  Get things rolling.


问:
How to implement a pythonic line continuation read
I am trying to implement a python script to read and extract lines from an ASCII text file. This seems to be a rather easy thing, however I ended up with an issue which I can't resolve myself.
The file I am trying to read contains test and some of the lines
begin with *tr999. This pattern can have either big or small letters and the number of digits and the presence of the * is optional. The asterisk can also be before and after. This signal keyword is followed by numbers, either int or folat.  To catch the signal, I use a python regexp expression

```<code>re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line)
</code>```

The text file looks like this

```<code>tr10* 1 2 3 22 1 1 13 12 33 33 33
*Tr20 12 22 -1 2  2 2 5 5 5 6 6 6 77
Tr20 1 1 1 &
           2 0 0
           1 1 1
           2 2 2
c that is a comment and below is the problem case '&' is missing
*tr22221 2 2 2
         1 1 1
         2 2 2
</code>```

The code I wrote can't catch the last case. Where the continue line signal & is missing. The use of & to continue line is optional and can be replaced by a number of white spaces at the begging of the continued  line .

The code I wrote is

```<code>import sys

fp=open(sys.argv[1],'r')
import re

# get the integers only
def loop_conv(string):
        conv=[]
        for i in string.split(" "):
            try:
                conv.append(float(i))
            except ValueError:
                pass
        return conv

# extract the information
def extract_trans_card(line,fp):
            extracted=False
            if len(line)>2 and not re.search("[cC]",line.split()[0]) and re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line) :
                extracted=True
                trans_card=[]
                trans_card.append(line.split()[0])
                line_old=line
   # this part here is because after the read signal,
   # data to be extracted might be on the same line
                for val in loop_conv(line):
                        trans_card.append(val)
# this part here fails. I am not able to catch the case '&' missing.
# i tried to peek the next line with seek() but it i got a system error.
# the idea is to loop until i have a continue line case
                while (re.search("^(\s){5,60}",line) or re.search("[&$]",line_old)) and len(trans_card) <13:

                    line=fp.readline()
                    for val in loop_conv(line):
                        trans_card.append(val)
                    line_old=line

                #print('M',trans_card)
                print('value',trans_card)
                trans_card=[]
            return extracted

# read the file with a loop
for line in fp:
        if not extract_trans_card(line,fp) :
            print(line,end='')
</code>```

The output is:

```<code>value ['tr10*', 1.0, 2.0, 3.0, 22.0, 1.0, 1.0, 13.0, 12.0, 33.0, 33.0, 33.0]
value ['*Tr20', 12.0, 22.0, -1.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 77.0]
value ['Tr20', 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
    c that is a comment and below is the problem case '&' is missing
value ['*tr22221', 2.0, 2.0, 2.0]
             1 1 1
             2 2 2
</code>```

The last line is the problem. Since the 1 1 1 and 2 2 2 get ignored and are just echoed.
This problem looks similar to how python does continue line. Either by spaces or by using &.
I hope someone will help we with this and would point the proper manner to do this problem

答:
Here is a Pythonic way of processing a file (actually anything that is iterable where the next() item returns a string, possibly ending in a newline character or not) where continuation can be designated by '&' in the last column of the current "record" (Python actually uses '\') or a space character in the next "record":

```<code>import re

def read_lines_with_continue(iter):
    """This function is passed an interator where each iteration returns the next line.
       This function processes logical continuations consisting of lines that end with '&' or lines
       that begin a space."""

    next_line = ''
    saw_continue = True
    for line in iter:
        # get rid of any trailing '&'
        edited_line = re.sub(r'&$', '', line)
        if saw_continue:
            next_line += edited_line
            saw_continue = False
        elif line[0] == ' ':
            next_line += edited_line
        elif next_line != '':
            yield next_line
            next_line = edited_line
        if line != edited_line:
            saw_continue = True
    if next_line != '':
        yield next_line

lines = [
    '1abc',
    '2def&',
    'ghi',
    ' xyz',
    ' ver&',
    'jkl',
    '3aaa',
    '4xxx',
    ' yyy'
]

# instead of passing a list, you could also pass a file
for l in read_lines_with_continue(lines):
    print(l)

1abc
2defghi xyz verjkl
3aaa
4xxx yyy
</code>```

Body:
I am trying to implement a python script to read and extract lines from an ASCII text file. This seems to be a rather easy thing, however I ended up with an issue which I can't resolve myself.
The file I am trying to read contains test and some of the lines
begin with *tr999. This pattern can have either big or small letters and the number of digits and the presence of the * is optional. The asterisk can also be before and after. This signal keyword is followed by numbers, either int or folat.  To catch the signal, I use a python regexp expression

re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line)

The text file looks like this

tr10* 1 2 3 22 1 1 13 12 33 33 33
*Tr20 12 22 -1 2  2 2 5 5 5 6 6 6 77
Tr20 1 1 1 &
           2 0 0
           1 1 1
           2 2 2
c that is a comment and below is the problem case '&' is missing
*tr22221 2 2 2
         1 1 1
         2 2 2

The code I wrote can't catch the last case. Where the continue line signal & is missing. The use of & to continue line is optional and can be replaced by a number of white spaces at the begging of the continued  line .

The code I wrote is

import sys

fp=open(sys.argv[1],'r')
import re

# get the integers only
def loop_conv(string):
        conv=[]
        for i in string.split(" "):
            try:
                conv.append(float(i))
            except ValueError:
                pass
        return conv

# extract the information
def extract_trans_card(line,fp):
            extracted=False
            if len(line)>2 and not re.search("[cC]",line.split()[0]) and re.search("[*]{0,1}[Tt][Rr][0-9]{1,5}[*]{0,1}",line) :
                extracted=True
                trans_card=[]
                trans_card.append(line.split()[0])
                line_old=line
   # this part here is because after the read signal,
   # data to be extracted might be on the same line
                for val in loop_conv(line):
                        trans_card.append(val)
# this part here fails. I am not able to catch the case '&' missing.
# i tried to peek the next line with seek() but it i got a system error.
# the idea is to loop until i have a continue line case
                while (re.search("^(\s){5,60}",line) or re.search("[&$]",line_old)) and len(trans_card) <13:

                    line=fp.readline()
                    for val in loop_conv(line):
                        trans_card.append(val)
                    line_old=line

                #print('M',trans_card)
                print('value',trans_card)
                trans_card=[]
            return extracted

# read the file with a loop
for line in fp:
        if not extract_trans_card(line,fp) :
            print(line,end='')

The output is:

value ['tr10*', 1.0, 2.0, 3.0, 22.0, 1.0, 1.0, 13.0, 12.0, 33.0, 33.0, 33.0]
value ['*Tr20', 12.0, 22.0, -1.0, 2.0, 2.0, 2.0, 5.0, 5.0, 5.0, 6.0, 6.0, 6.0, 77.0]
value ['Tr20', 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
    c that is a comment and below is the problem case '&' is missing
value ['*tr22221', 2.0, 2.0, 2.0]
             1 1 1
             2 2 2

The last line is the problem. Since the 1 1 1 and 2 2 2 get ignored and are just echoed.
This problem looks similar to how python does continue line. Either by spaces or by using &.
I hope someone will help we with this and would point the proper manner to do this problem

Body:
Here is a Pythonic way of processing a file (actually anything that is iterable where the next() item returns a string, possibly ending in a newline character or not) where continuation can be designated by '&' in the last column of the current "record" (Python actually uses '\') or a space character in the next "record":

import re

def read_lines_with_continue(iter):
    """This function is passed an interator where each iteration returns the next line.
       This function processes logical continuations consisting of lines that end with '&' or lines
       that begin a space."""

    next_line = ''
    saw_continue = True
    for line in iter:
        # get rid of any trailing '&'
        edited_line = re.sub(r'&$', '', line)
        if saw_continue:
            next_line += edited_line
            saw_continue = False
        elif line[0] == ' ':
            next_line += edited_line
        elif next_line != '':
            yield next_line
            next_line = edited_line
        if line != edited_line:
            saw_continue = True
    if next_line != '':
        yield next_line

lines = [
    '1abc',
    '2def&',
    'ghi',
    ' xyz',
    ' ver&',
    'jkl',
    '3aaa',
    '4xxx',
    ' yyy'
]

# instead of passing a list, you could also pass a file
for l in read_lines_with_continue(lines):
    print(l)

1abc
2defghi xyz verjkl
3aaa
4xxx yyy